-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathauthManagement.ts
More file actions
261 lines (245 loc) · 7.35 KB
/
Copy pathauthManagement.ts
File metadata and controls
261 lines (245 loc) · 7.35 KB
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
import { RequestHandler } from 'express';
import { User } from '../../models/user';
import { saveUser, generateToken, userResponse } from './helpers';
import {
GenericResponseBody,
PublicUserOrErrorOrGeneric,
UnlinkThirdPartyResponseBody,
PublicUserOrError,
ResetPasswordInitiateRequestBody,
ResetOrUpdatePasswordRequestParams,
UpdatePasswordRequestBody,
UpdateSettingsRequestBody
} from '../../types';
import { mailerService } from '../../utils/mail';
import { renderResetPassword, renderEmailConfirmation } from '../../views/mail';
/**
* - Method: `POST`
* - Endpoint: `/reset-password`
* - Authenticated: `false`
* - Id: `UserController.resetPasswordInitiate`
*
* Description:
* - Send an Reset-Password email to the registered email account
*/
export const resetPasswordInitiate: RequestHandler<
{},
GenericResponseBody,
ResetPasswordInitiateRequestBody
> = async (req, res) => {
try {
const token = await generateToken();
const user = await User.findByEmail(req.body.email);
if (!user) {
res.json({
success: true,
message:
'If the email is registered with the editor, an email has been sent.'
});
return;
}
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
await user.save();
const protocol = process.env.NODE_ENV === 'production' ? 'https' : 'http';
const mailOptions = renderResetPassword({
body: {
domain: `${protocol}://${req.headers.host}`,
link: `${protocol}://${req.headers.host}/reset-password/${token}`
},
to: user.email
});
await mailerService.send(mailOptions);
res.json({
success: true,
message:
'If the email is registered with the editor, an email has been sent.'
});
} catch (err) {
if (process.env.NODE_ENV !== 'test') {
// don't log in test env
console.log(err);
}
res.json({ success: false });
}
};
/**
* - Method: `GET`
* - Endpoint: `/reset-password/:token`
* - Authenticated: `false`
* - Id: `UserController.validateResetPasswordToken`
*
* Description:
* - The link in the Reset Password email, which contains a reset token that is valid for 1h
* - If valid, the user will see a form to reset their password
* - Else they will see a message that their token has expired
*/
export const validateResetPasswordToken: RequestHandler<
ResetOrUpdatePasswordRequestParams,
GenericResponseBody
> = async (req, res) => {
const user = await User.findOne({
resetPasswordToken: req.params.token,
resetPasswordExpires: { $gt: Date.now() }
}).exec();
if (!user) {
res.status(401).json({
success: false,
message: 'Password reset token is invalid or has expired.'
});
return;
}
res.json({ success: true });
};
/**
* - Method: `POST`
* - Endpoint: `/reset-password/:token`
* - Authenticated: `false`
* - Id: `UserController.updatePassword`
*
* Description:
* - Used by the new password form to update a user's password with the valid token
* - Returns a Generic 401 - 'Password reset token is invalid or has expired.' if the token timed out
* - Returns a PublicUser if successfully saved
* - Returns an Error if network error on save attempt
*/
export const updatePassword: RequestHandler<
ResetOrUpdatePasswordRequestParams,
PublicUserOrErrorOrGeneric,
UpdatePasswordRequestBody
> = async (req, res) => {
const user = await User.findOne({
resetPasswordToken: req.params.token,
resetPasswordExpires: { $gt: Date.now() }
}).exec();
if (!user) {
res.status(401).json({
success: false,
message: 'Password reset token is invalid or has expired.'
});
return;
}
user.password = req.body.password;
user.resetPasswordToken = undefined;
user.resetPasswordExpires = undefined;
await user.save();
req.logIn(user, (loginErr) => res.json(userResponse(req.user!)));
// eventually send email that the password has been reset
};
/**
* - Method: `PUT`
* - Endpoint: `/account`
* - Authenticated: `true`
* - Id: `UserController.updateSettings`
*
* Description:
* - Used to update the user's username, email, or password on the `/account` page while authenticated
* - Currently the client only shows the `currentPassword` and `newPassword` fields if no social logins (github & google) are enabled
*/
export const updateSettings: RequestHandler<
{},
PublicUserOrError,
UpdateSettingsRequestBody
> = async (req, res) => {
try {
const user = await User.findById(req.user!.id);
if (!user) {
res.status(404).json({ error: 'User not found' });
return;
}
user.username = req.body.username;
if (req.body.newPassword) {
if (user.password === undefined) {
user.password = req.body.newPassword;
saveUser(res, user);
}
if (!req.body.currentPassword) {
res.status(401).json({ error: 'Current password is not provided.' });
return;
}
}
if (req.body.currentPassword) {
const isMatch = await user.comparePassword(req.body.currentPassword);
if (!isMatch) {
res.status(401).json({ error: 'Current password is invalid.' });
return;
}
user.password = req.body.newPassword!;
await saveUser(res, user);
} else if (user.email !== req.body.email) {
const EMAIL_VERIFY_TOKEN_EXPIRY_TIME = Date.now() + 3600000 * 24; // 24 hours
user.verified = User.EmailConfirmation().Sent;
user.email = req.body.email;
const token = await generateToken();
user.verifiedToken = token;
user.verifiedTokenExpires = EMAIL_VERIFY_TOKEN_EXPIRY_TIME;
await saveUser(res, user);
const protocol = process.env.NODE_ENV === 'production' ? 'https' : 'http';
const mailOptions = renderEmailConfirmation({
body: {
domain: `${protocol}://${req.headers.host}`,
link: `${protocol}://${req.headers.host}/verify?t=${token}`
},
to: user.email
});
await mailerService.send(mailOptions);
} else {
await saveUser(res, user);
}
} catch (err) {
console.error('Could not save settings:', err);
res.status(500).json({ error: 'Internal server error' });
}
};
/**
* - Method: `DELETE`
* - Endpoint: `/auth/github`
* - Authenticated: `false` -- TODO: update to true?
* - Id: `UserController.unlinkGithub`
*
* Description:
* - Unlink github account
*/
export const unlinkGithub: RequestHandler<
{},
UnlinkThirdPartyResponseBody
> = async (req, res) => {
if (req.user) {
req.user.github = undefined;
req.user.tokens = req.user.tokens.filter(
(token) => token.kind !== 'github'
);
await saveUser(res, req.user);
return;
}
res.status(404).json({
success: false,
message: 'You must be logged in to complete this action.'
});
};
/**
* - Method: `DELETE`
* - Endpoint: `/auth/google`
* - Authenticated: `false` -- TODO: update to true?
* - Id: `UserController.unlinkGoogle`
*
* Description:
* - Unlink google account
*/
export const unlinkGoogle: RequestHandler<
{},
UnlinkThirdPartyResponseBody
> = async (req, res) => {
if (req.user) {
req.user.google = undefined;
req.user.tokens = req.user.tokens.filter(
(token) => token.kind !== 'google'
);
await saveUser(res, req.user);
return;
}
res.status(404).json({
success: false,
message: 'You must be logged in to complete this action.'
});
};