-
Notifications
You must be signed in to change notification settings - Fork 4k
/
auth.js
97 lines (81 loc) · 2.75 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
import locals from '../../middlewares/locals';
import { validatePasswordResetCodeAndFindUser, convertToBcrypt} from '../../libs/password';
let api = {};
// Internal authentication routes
function renderPasswordResetPage (options = {}) {
// res is express' res, error any error and success if the password was successfully changed
let {res, hasError, success = false, message} = options;
return res.status(hasError ? 401 : 200).render('auth/reset-password-set-new-one.jade', {
env: res.locals.habitrpg,
success,
hasError,
message, // can be error or success message
});
}
// Set a new password after having requested a password reset (GET route to input password)
api.resetPasswordSetNewOne = {
method: 'GET',
url: '/static/user/auth/local/reset-password-set-new-one',
middlewares: [locals],
runCron: false,
async handler (req, res) {
let user = await validatePasswordResetCodeAndFindUser(req.query.code);
let isValidCode = Boolean(user);
const hasError = !isValidCode;
const message = !isValidCode ? res.t('invalidPasswordResetCode') : null;
return res.redirect(`/reset-password?hasError=${hasError}&message=${message}`);
},
};
// Set a new password after having requested a password reset (POST route to save password)
api.resetPasswordSetNewOneSubmit = {
method: 'POST',
url: '/static/user/auth/local/reset-password-set-new-one',
middlewares: [locals],
runCron: false,
async handler (req, res) {
let user = await validatePasswordResetCodeAndFindUser(req.query.code);
let isValidCode = Boolean(user);
if (!isValidCode) return renderPasswordResetPage({
res,
hasError: true,
message: res.t('invalidPasswordResetCode'),
});
let newPassword = req.body.newPassword;
let confirmPassword = req.body.confirmPassword;
if (!newPassword) {
return renderPasswordResetPage({
res,
hasError: true,
message: res.t('missingNewPassword'),
});
}
if (newPassword !== confirmPassword) {
return renderPasswordResetPage({
res,
hasError: true,
message: res.t('passwordConfirmationMatch'),
});
}
// set new password and make sure it's using bcrypt for hashing
await convertToBcrypt(user, String(newPassword));
user.auth.local.passwordResetCode = undefined; // Reset saved password reset code
await user.save();
return renderPasswordResetPage({
res,
hasError: false,
success: true,
message: res.t('passwordChangeSuccess'),
});
},
};
// Logout the user from the website.
api.logout = {
method: 'GET',
url: '/logout',
async handler (req, res) {
if (req.logout) req.logout(); // passportjs method
req.session = null;
res.redirect('/');
},
};
module.exports = api;