-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.ts
58 lines (48 loc) · 1.35 KB
/
auth.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
import { User } from "@prisma/client";
import { Context } from "./context";
import { GraphQLError } from "graphql";
export type UserFromJWT = {
id: number,
username: string;
};
export const comparePasswords = (password, hash) => {
return bcrypt.compare(password, hash);
};
export const hashPassword = (password) => {
return bcrypt.hash(password, 5);
};
export const createJWT = (user: User) => {
const token = jwt.sign(<UserFromJWT>{
id: user.id,
username: user.username
},
process.env.JWT_SECRET
);
return token;
};
export const mustBeAuthenticated = (context: Context) => {
if (!context.isAuthenticated) {
throw new GraphQLError(
'Not authenticated',
{ extensions: { code: 'UNAUTHENTICATED' } }
);
}
};
export const mustNotBeAuthenticated = (context: Context) => {
if (context.isAuthenticated) {
throw new GraphQLError(
'Already authenticated',
{ extensions: { code: 'UNAUTHORIZED' } }
);
}
};
export const mustBeOwner = (context: Context, movie) => {
if (movie.creatorId !== context.user.id) {
throw new GraphQLError(
'Not authorized to modify this movie',
{ extensions: { code: 'UNAUTHORIZED' } }
);
}
};