-
Notifications
You must be signed in to change notification settings - Fork 69
/
authController.ts
169 lines (145 loc) · 3.59 KB
/
authController.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
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import { AuthenticationError, UserInputError } from 'apollo-server-micro'
import bcrypt from 'bcrypt'
import { nanoid } from 'nanoid'
import type { Context } from '../../@types/helpers'
import type {
LoginMutationVariables,
SignupMutationVariables
} from '../../graphql'
import prisma from '../../prisma'
import { decode, encode } from '../../helpers/encoding'
import { signupValidation } from '../../helpers/formValidation'
import { sendSignupEmail } from '../../helpers/mail'
const THREE_DAYS = 1000 * 60 * 60 * 24 * 3
export const login = async (_parent: void, arg: LoginMutationVariables) => {
const { username, password } = arg
let user = await prisma.user.findFirst({ where: { username } })
// TODO change username column to be unique
// const user = await prisma.user.findUnique({ where: { username } })
if (!user) {
throw new UserInputError('User does not exist')
}
const validLogin = user.password
? await bcrypt.compare(password, user.password)
: false
if (!validLogin) {
throw new AuthenticationError('Password is invalid')
}
if (!user.cliToken) {
user = await prisma.user.update({
where: {
id: user.id
},
data: { cliToken: nanoid() }
})
}
const cliToken = { id: user.id, cliToken: user.cliToken }
return {
success: true,
username: user.username,
cliToken: encode(cliToken),
id: user.id
}
}
export const logout = async (_parent: void, _: void, ctx: Context) => {
const { req } = ctx
const { session } = req
return new Promise((resolve, reject) => {
if (!session) {
return reject({
success: false,
error: 'Session Error'
})
}
session.destroy(err => {
if (err) {
req.error(err)
reject({
success: false,
error: err.message
})
}
resolve({
success: true
})
})
})
}
export const signup = async (
_parent: void,
arg: SignupMutationVariables,
ctx: Context
) => {
const { req } = ctx
const { firstName, lastName, username, email } = arg
const validEntry = await signupValidation.isValid({
firstName,
lastName,
username,
email
})
if (!validEntry) {
throw new UserInputError('Register form is not completely filled out')
}
// Check for existing user or email
const existingUser = await prisma.user.findFirst({
where: {
username
}
})
if (existingUser) {
throw new UserInputError('User already exists')
}
const existingEmail = await prisma.user.findFirst({
where: {
email
}
})
if (existingEmail) {
throw new UserInputError('Email already exists')
}
const name = `${firstName} ${lastName}`
let newUser = await prisma.user.create({
data: {
name,
username,
email
}
})
const forgotToken = encode({
userId: newUser.id,
userToken: nanoid()
})
const tokenExpiration = new Date(Date.now() + THREE_DAYS)
newUser = await prisma.user.update({
where: {
id: newUser.id
},
data: {
forgotToken,
tokenExpiration
}
})
try {
await sendSignupEmail(email, forgotToken)
} catch (error) {
req.error(`
Error while sending signup email
${JSON.stringify(error, null, 2)}
`)
}
return {
success: true,
username: newUser.username,
cliToken: forgotToken,
id: newUser.id
}
}
export const isTokenValid = async (
_parent: void,
arg: { cliToken: string }
) => {
const { id, cliToken } = decode(arg.cliToken)
const user = await prisma.user.findUnique({ where: { id } })
return user?.cliToken === cliToken || false
}