-
Notifications
You must be signed in to change notification settings - Fork 2
/
auth.js
304 lines (226 loc) · 7.65 KB
/
auth.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
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
const httpStatus = require('http-status')
const { addMinutes, getUnixTime,addYears } = require('date-fns')
const Auth = require('#models/auth')
const User = require('#models/user')
const Errors = require('#errors/common')
const config = require('#config')
const sendMail = require('#lib/email')
const jwt = require('jwt-simple')
const crypto = require("crypto")
exports.register = async (req, res) => {
try {
const isExisting = await Auth.findOne({ email: req.body.email })
if (isExisting) {
throw new Error("Already such an email registered.")
}
const newAuth = await Auth.create({ ...req.body })
const newUser = await (await User.create({ userInfo: newAuth._id, email: newAuth.email })).populate("userInfo")
// & sending a token after user creation
const token = createAccessToken(newUser)
const options = {
expires: token.expiresIn,
httpOnly: true
}
res.status(httpStatus.CREATED).cookie('token', token.token, options).json({
status: true,
message: "success",
token: token,
user: newUser
})
} catch (error) {
return res.status(500).json(error.message)
}
}
// ? login user function with email and password
exports.logInWithEmailAndPassword = async function (req, res, next) {
try {
const { email, password } = req.body
//& data validtion from frontend
if (!email || !password) {
return next(new Errors.ApiError())
}
//& Check if user exists in db if yes fetch them
const user = await Auth.findOne({ email }).select("+password")
if (!user) {
return res.status(500).json("Password or email may be incorrect")
}
//& validating the password if they match with one from Db
const isPasswordCorrect = await user.isValidatedPassword(password)
if (!isPasswordCorrect) {
return res.status(500).json("Password or email may be incorrect")
}
const currentUser = await User.findOne({ userInfo: user._id}).populate('userInfo');
//& sending a token after validation
const token = createAccessToken(currentUser)
const options = {
expires: token.expiresIn,
httpOnly: true
}
res.status(httpStatus.CREATED).cookie('token', token.token, options).json({
status: true,
message: "success",
token: token,
user: currentUser
})
} catch (error) {
return res.status(500).json(error.message)
return next(new Errors.ApiError())
}
}
// ? Reset password and create new one function
exports.emailVerification = async function (req, res, next) {
try {
//& get reset pasword token and encrypt it to match the Db one
const token = req.params.token
const encryptedToken = crypto.createHash('sha256').update(token).digest("hex")
//& get user with same encrypted token
const user = await Auth.findOne({ emailVerificationToken: encryptedToken })
if (!user) {
return next(new Errors.ApiError())
}
//& save the emailVerified to Db and delete the token
user.emailVerificationToken = undefined
user.emailVerified = true
await user.save({ validateBeforeSave: false })
//& sending a token after verification
const newToken = createAccessToken(user)
const options = {
expires: token.expiresIn,
httpOnly: true
}
res.status(httpStatus.CREATED).cookie('token', newToken.token, options).json({
status: true,
message: "success",
token: newToken,
user: user
})
} catch (error) {
return next(new Errors.ApiError())
}
}
// ? logout user function
exports.logout = async function (req, res, next) {
res.cookie('token', null, { expires: new Date(Date.now()), httpOnly: true })
res.status(httpStatus.OK).json({
success: true,
message: "logout success"
})
}
// ? Send forget password email function
exports.forgotPassword = async function (req, res, next) {
const { email } = req.body
//& data validtion from frontend
if (!email) {
return next(new Errors.ApiError())
}
//& check if user exists in the DB
const user = await Auth.findOne({ email })
if (!user) {
return next(new Errors.UserNotFoundError())
}
//& Create a token and save it in the database
const forgotToken = await user.getForgetPasswordToken();
await user.save({ validateBeforeSave: false })
//& Send the user a reset pasword to their email
const url = `${req.protocol}://${req.get('host')}/api/v1/password/reset/${forgotToken}`
const message = `Copy paste this link in our Url and hit enter \n\n ${url}`
try {
await sendMail({
to: user.email,
subject: "Password reset",
html: message
})
res.status(httpStatus.OK).json({
success: true,
message: "Email sent Successfully",
info: "Check your email and follow the steps to recover your account "
})
} catch (error) {
//& if the email wasnt sent we delete the token from db
user.forgotPasswordToken = undefined
user.forgotPasswordExpiry = undefined
await user.save({ validateBeforeSave: false })
//& send an error response
return next(new Errors.ApiError())
}
}
// ? Reset password and create new one function
exports.passwordReset = async function (req, res, next) {
try {
//& get reset pasword token and encrypt it to match the Db one
const token = req.params.token
const encryptedToken = crypto.createHash('sha256').update(token).digest("hex")
//& geet user with same encrypted token and not expired
const user = await Auth.findOne({
forgotPasswordToken: encryptedToken,
forgotPasswordExpiry: { $gt: Date.now() }
})
if (!user) {
return next(new Errors.ApiError())
}
//& save the new password to Db and delete the tokens
user.password = req.body.password
user.forgotPasswordToken = undefined
user.forgotPasswordExpiry = undefined
await user.save({ validateBeforeSave: false })
//& send user a new token
//& sending a token after user creation
const newToken = createAccessToken(user)
const options = {
expires: token.expiresIn,
httpOnly: true
}
//& remember not to send the password
// user.password = undefined
res.status(httpStatus.CREATED).cookie('token', newToken.token, options).json({
status: true,
message: "success",
token: newToken,
user: user
})
} catch (error) {
return next(new Errors.ApiError())
}
}
//? Update user password function
exports.passwordUpdate = async function (req, res, next) {
try {
const { oldPassword, newPassword } = req.body
//& data validtion from frontend
if (!oldPassword) {
return next(new Errors.ApiError())
}
//& get old password from Db and validate if it is same to the one sent
const user = await Auth.findById(req.user.id).select("+password")
const isCorrectOldPassword = await user.isValidatedPassword(oldPassword)
if (!isCorrectOldPassword) {
return next(new Errors.ApiError())
}
//& Update the password and send them a new login token
user.password = newPassword
await user.save()
res.status(httpStatus.CREATED).json({
status: true,
message: "success",
user: user
})
} catch (error) {
return next(new Errors.ApiError())
}
}
//* Helper functions
function createAccessToken(user) {
return {
tokenType: "Bearer",
expiresIn: addMinutes(Date.now(), config.auth.jwtExpirationInterval),
token: createJwt(user._id),
}
}
function createJwt(encoder) {
const payload = {
exp: getUnixTime(addYears(Date.now(), config.auth.jwtExpirationInterval)),
iat: getUnixTime(Date.now()),
id: encoder,
}
return jwt.encode(payload, config.auth.jwtSecret)
}