This repository was archived by the owner on May 16, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusers.js
More file actions
330 lines (274 loc) · 8.75 KB
/
Copy pathusers.js
File metadata and controls
330 lines (274 loc) · 8.75 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
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
const User = require('@models/user');
const Session = require('@models/session');
const Token = require('@models/token');
const bcrypt = require('bcrypt');
const { zxcvbn } = require('@zxcvbn-ts/core');
const ms = require('ms');
const { validate: emailValidator } = require('deep-email-validator');
const crypto = require('crypto');
const emailSends = require('@services/email');
/**
* נרמול כתובת מייל - הסרת נקודות מיותרות, מה שאחרי הפלוס, וכדומה
* לצורך וידוא שהמייל לא רשום כבר
* @param {String} email כתובת המייל שהתקבלה מהמשתמש
* @returns
*/
function normalizeEmail (email) {
email = email.toLowerCase();
if (/g(oogle)?mail\.com|hotmail\.com|outlook\.com/.test(email)) {
const emailRew = email.replace('googlemail', 'gmail');
const emailParts = emailRew.split('@');
let part1 = emailParts[0].replace(/.*\+/, '');
if (/gmail\.com/.test(part1)) {
part1 = part1.replaceAll('.', '');
}
return part1 + '@' + emailParts[1];
} else {
return email;
}
};
async function signup (req, res) {
const { email, password } = req.body;
/**
* normalize-email by regex
*/
const emailProcessed = normalizeEmail(email);
/**
* validate email
*/
const validateEmail = await emailValidator({
email: emailProcessed,
validateRegex: true,
validateMx: true,
validateTypo: false,
validateDisposable: true,
validateSMTP: false
});
if (!validateEmail.valid) {
if (validateEmail.reason === 'disposable') {
return res.status(400).json({
message: 'disposable email not allowed'
});
} else {
return res.status(400).json({
message: 'email is not valid'
});
}
}
const { score: scorePass } = zxcvbn(password);
if (scorePass < 1) {
return res.status(400).json({
message: 'Weak password'
});
}
const hash = await bcrypt.hash(password, 10);
const users = await User.find({ emailProcessed });
if (users.length) {
return res.status(409).json({
message: 'Email exists'
});
}
const user = new User({
password: hash,
emailProcessed,
emailFront: email
});
const verifyEmailToken = await Token.create({
userId: user._id,
type: 'verifyEmail',
token: crypto.randomInt(10000, 100000)
});
await emailSends.verifyEmail({
code: verifyEmailToken.token,
address: email
});
await user.save();
res.status(200).json({
message: 'User created and verification email sent'
});
};
async function login (req, res) {
const { email, password } = req.body;
const emailProcessed = normalizeEmail(email);
const users = await User.find({ emailProcessed });
if (!users.length) {
return res.status(401).json({
message: 'Auth failed'
});
}
const [user] = users;
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(401).json({
message: 'Auth failed'
});
}
const session = await Session.create({
uuid: crypto.randomUUID(),
userId: user._id
});
res.status(200).cookie('session', session.uuid, { path: '/', secure: false, httpOnly: true, maxAge: ms('30d') }).json({
message: 'Auth successful',
sessionUuid: session.uuid,
user: {
email: user.emailFront,
verified: user.verified
}
});
};
async function logout (req, res) {
const { sessionId } = res.locals;
await Session.findByIdAndDelete(sessionId);
res.status(200).clearCookie('session').json({
message: 'Logout successful'
});
};
async function verifyEmail (req, res) {
const { code } = req.body;
const { _id: userId } = res.locals.user;
const user = await User.findById(userId);
if (!user) {
return res.status(404).json({
message: `User ${userId} is not found`
});
}
if (user.verified) {
return res.status(200).json({
message: 'User already verified'
});
}
const existsTokens = await Token.find({ userId, type: 'verifyEmail', token: code });
if (!existsTokens.length) {
return res.status(401).json({
message: 'code not correct or expired'
});
}
await User.findByIdAndUpdate(userId, { verified: true });
res.status(200).json({
message: 'User verified successfully'
});
};
async function resendVerificationEmail (req, res) {
const { _id: userId, verified: isVerified, emailFront } = res.locals.user;
if (isVerified) {
return res.status(409).json({
message: 'you already verified'
});
}
const rateLimit = '1h';
const existsTokens = await Token.find({ userId, type: 'verifyEmail' }).sort({ createdAt: -1 });
if (existsTokens.length > 1) {
const FreshTokens = existsTokens.filter(token => (Date.now() - token.createdAt) < ms(rateLimit));
if (FreshTokens.length) {
return res.status(429).json({
message: `Too many requests. Try again in ${ms(ms(rateLimit) - (Date.now() - existsTokens[0].createdAt), { long: true })}`
});
}
}
const verifyToken = new Token({
userId,
type: 'verifyEmail',
token: crypto.randomInt(10000, 100000)
});
await emailSends.verifyEmail({
code: verifyToken.token,
address: emailFront
});
await verifyToken.save();
res.status(200).json({
message: `verify email sent again to ${emailFront}`
});
};
async function forgotPassword (req, res) {
const { email } = req.body;
const emailProcessed = normalizeEmail(email);
const user = await User.findOne({ emailProcessed });
if (!user) {
return res.status(404).json({
message: 'User not found'
});
}
const rateLimit = '1h';
const existsTokens = await Token.find({ userId: user._id, type: 'forgotPassword' }).sort({ createdAt: -1 });
if (existsTokens.length) {
const FreshTokens = existsTokens.filter(token => (Date.now() - token.createdAt) < ms(rateLimit));
if (FreshTokens.length) {
return res.status(429).json({
message: `Too many requests. Try again in ${ms(ms(rateLimit) - (Date.now() - existsTokens[0].createdAt), { long: true })}`
});
}
}
const resetToken = new Token({
userId: user._id,
type: 'forgotPassword',
token: crypto.randomInt(10000, 100000)
});
await emailSends.forgotPassword({
token: resetToken.token,
address: user.emailFront
});
await resetToken.save();
res.status(200).json({
message: 'reset password email sent successfully'
});
};
async function changePassword (req, res) {
const { token, email, newPassword } = req.body;
const emailProcessed = normalizeEmail(email);
const user = await User.findOne({ emailProcessed });
if (!user) {
return res.status(404).json({
message: 'User not found'
});
}
const tokenSaved = await Token.findOne({ userId: user._id, type: 'forgotPassword', token });
if (!tokenSaved) {
return res.status(400).json({
message: 'Token is wrong or expired'
});
}
const { score: scorePass } = zxcvbn(newPassword);
if (scorePass < 1) {
return res.status(400).json({
message: 'Weak password'
});
}
const hash = await bcrypt.hash(newPassword, 10);
await User.findByIdAndUpdate(user._id, {
password: hash
});
await Token.findByIdAndDelete(tokenSaved._id);
await Session.deleteMany({ userId: user._id });
res.status(200).json({
message: 'change password successful'
});
};
async function getSettings (req, res) {
const { user } = res.locals;
return res.status(200).json({
enableEmailNotifications: user.enableEmailNotifications,
allowAttachmentsInEmail: user.allowAttachmentsInEmail
});
};
async function updateSettings (req, res) {
const { _id: userId } = res.locals.user;
const { enableEmailNotifications, allowAttachmentsInEmail } = req.body;
await User.findByIdAndUpdate(userId, {
enableEmailNotifications,
allowAttachmentsInEmail
});
return res.status(200).json({
message: 'settings updated successfully'
});
};
module.exports = {
signup,
login,
logout,
verifyEmail,
resendVerificationEmail,
forgotPassword,
changePassword,
getSettings,
updateSettings
};