/
resolvers.js
89 lines (78 loc) · 2.21 KB
/
resolvers.js
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import {
AuthenticationError,
ApolloError,
UserInputError,
} from 'apollo-server-micro'
import cookie from 'cookie'
import jwt from 'jsonwebtoken'
import getConfig from 'next/config'
const JWT_SECRET = getConfig().serverRuntimeConfig.JWT_SECRET
export const resolvers = {
Query: {
async viewer(_parent, _args, context, _info) {
const { token } = cookie.parse(context.req.headers.cookie ?? '')
if (token) {
try {
const { id, email } = jwt.verify(token, JWT_SECRET)
return await context.models.User.findOne({ where: { id, email } })
} catch {
throw new AuthenticationError(
'Authentication token is invalid, please log in'
)
}
}
return null
},
},
Mutation: {
async signUp(_parent, args, context, _info) {
const user = await context.models.User.create(args.input).catch(
error =>
new ApolloError('ValidationError', 'VALIDATION_ERROR', {
errors: error.errors,
fields: error.fields,
})
)
return { user }
},
async signIn(_parent, args, context, _info) {
const user = await context.models.User.findOne({
where: { email: args.input.email },
})
if (user && user.validPassword(args.input.password)) {
const token = jwt.sign(
{ email: user.email, id: user.id, time: new Date() },
JWT_SECRET,
{
expiresIn: '6h',
}
)
context.res.setHeader(
'Set-Cookie',
cookie.serialize('token', token, {
httpOnly: true,
maxAge: 6 * 60 * 60,
path: '/',
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
})
)
return { user }
}
throw new UserInputError('Invalid email and password combination')
},
async signOut(_parent, _args, context, _info) {
context.res.setHeader(
'Set-Cookie',
cookie.serialize('token', '', {
httpOnly: true,
maxAge: -1,
path: '/',
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
})
)
return true
},
},
}