-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathuserAuth.controller.js
More file actions
511 lines (391 loc) · 18.7 KB
/
Copy pathuserAuth.controller.js
File metadata and controls
511 lines (391 loc) · 18.7 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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { z } = require('zod');
const mongoose = require('mongoose');
const {Project} = require('@urbackend/common');
const {redis} = require('@urbackend/common');
const { authEmailQueue } = require('@urbackend/common');
const { loginSchema, signupSchema, userSignupSchema, resetPasswordSchema, onlyEmailSchema, verifyOtpSchema, changePasswordSchema, sanitize } = require('@urbackend/common');
const { getConnection } = require('@urbackend/common');
const { getCompiledModel } = require('@urbackend/common');
const hasRequiredField = (usersColConfig, fieldKey) => {
const model = usersColConfig?.model || [];
return model.some((f) => f?.key === fieldKey && !!f?.required);
};
const getVerificationField = (usersColConfig) => {
const modelKeys = (usersColConfig?.model || []).map((f) => f?.key);
if (modelKeys.includes('emailVerified')) return 'emailVerified';
if (modelKeys.includes('isVerified')) return 'isVerified';
if (modelKeys.includes('isverified')) return 'isverified';
return null;
};
const buildAuthUserPayload = (usersColConfig, parsedData, hashedPassword, verifiedValue) => {
const { email, password: _password, username, ...otherData } = parsedData;
const payload = {
email,
password: hashedPassword,
...otherData,
createdAt: new Date()
};
if (username !== undefined) {
payload.username = username;
}
const verificationField = getVerificationField(usersColConfig);
if (verificationField !== null) {
payload[verificationField] = verifiedValue;
}
if (hasRequiredField(usersColConfig, 'name') && (payload.name === undefined || payload.name === null || payload.name === '')) {
payload.name = username || email.split('@')[0];
}
if (hasRequiredField(usersColConfig, 'username') && (payload.username === undefined || payload.username === null || payload.username === '')) {
payload.username = payload.name || email.split('@')[0];
}
return payload;
};
// POST REQ FOR SIGNUP
module.exports.signup = async (req, res) => {
try {
const project = req.project;
const { email, password, username, ...otherData } = userSignupSchema.parse(req.body);
// Get Mongoose Model
const usersColConfig = project.collections.find(c => c.name === 'users');
if (!usersColConfig) return res.status(404).json({ error: "Auth collection not found" });
const connection = await getConnection(project._id);
const Model = getCompiledModel(connection, usersColConfig, project._id, project.resources.db.isExternal);
const existingUser = await Model.findOne({ email });
if (existingUser) {
return res.status(400).json({ error: "User already exists with this email." });
}
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
const otp = Math.floor(100000 + Math.random() * 900000).toString();
const newUserPayload = buildAuthUserPayload(
usersColConfig,
{ email, password, username, ...otherData },
hashedPassword,
false
);
// Model.create handles validation and default values
const result = await Model.create(newUserPayload);
await redis.set(`project:${project._id}:otp:verification:${email}`, otp, 'EX', 300);
await authEmailQueue.add('send-verification-email', {
email,
otp,
type: 'verification',
pname: project.name
});
const token = jwt.sign(
{ userId: result._id, projectId: project._id },
project.jwtSecret,
{ expiresIn: '7d' }
);
res.status(201).json({
message: "User registered successfully. Please verify your email.",
token: token,
userId: result._id
});
} catch (err) {
if (err instanceof z.ZodError) {
return res.status(400).json({ error: err.issues?.[0]?.message || err.errors?.[0]?.message || "Validation failed" });
}
res.status(500).json({ error: err.message });
console.log(err)
}
}
// POST REQ FOR LOGIN
module.exports.login = async (req, res) => {
try {
const project = req.project;
const { email, password } = loginSchema.parse(req.body);
const usersColConfig = project.collections.find(c => c.name === 'users');
if (!usersColConfig) return res.status(404).json({ error: "Auth collection not found" });
const connection = await getConnection(project._id);
const Model = getCompiledModel(connection, usersColConfig, project._id, project.resources.db.isExternal);
const user = await Model.findOne({ email });
if (!user) return res.status(400).json({ error: "Invalid email or password" });
const validPass = await bcrypt.compare(password, user.password);
if (!validPass) return res.status(400).json({ error: "Invalid email or password" });
const token = jwt.sign(
{ userId: user._id, projectId: project._id },
project.jwtSecret,
{ expiresIn: '7d' }
);
res.json({ token });
} catch (err) {
if (err instanceof z.ZodError) return res.status(400).json({ error: err.errors });
res.status(500).json({ error: err.message }); // Fixed: .json()
}
}
// FUNCTION - GET CURRENT USER
module.exports.me = async (req, res) => {
try {
const project = req.project;
const tokenHeader = req.header('Authorization');
if (!tokenHeader) return res.status(401).json({ error: "Access Denied: No Token Provided" });
const token = tokenHeader.replace("Bearer ", "");
try {
const decoded = jwt.verify(token, project.jwtSecret);
const usersColConfig = project.collections.find(c => c.name === 'users');
if (!usersColConfig) return res.status(404).json({ error: "Auth collection not found" });
const connection = await getConnection(project._id);
const Model = getCompiledModel(connection, usersColConfig, project._id, project.resources.db.isExternal);
const user = await Model.findOne(
{ _id: new mongoose.Types.ObjectId(decoded.userId) },
{ password: 0 }
).lean();
if (!user) return res.status(404).json({ error: "User not found" });
res.json(user);
} catch (err) {
return res.status(401).json({ error: "Invalid or Expired Token" });
}
} catch (err) {
res.status(500).json({ error: err.message });
}
}
// POST REQ FOR ADMIN CREATE USER
module.exports.createAdminUser = async (req, res) => {
try {
const project = req.project;
const parsedData = userSignupSchema.parse(req.body);
const { email, password, username, ...otherData } = parsedData;
// Get Mongoose Model
const usersColConfig = project.collections.find(c => c.name === 'users');
if (!usersColConfig) return res.status(404).json({ error: "Auth collection not found" });
const connection = await getConnection(project._id);
const Model = getCompiledModel(connection, usersColConfig, project._id, project.resources.db.isExternal);
const existingUser = await Model.findOne({ email });
if (existingUser) {
return res.status(400).json({ error: "User already exists with this email." });
}
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
const newUserPayload = buildAuthUserPayload(
usersColConfig,
{ email, password, username, ...otherData },
hashedPassword,
true
);
const result = await Model.create(newUserPayload);
res.status(201).json({
message: "User created successfully",
user: { _id: result._id, email, username, createdAt: newUserPayload.createdAt }
});
} catch (err) {
if (err instanceof z.ZodError) {
console.error(err);
return res.status(400).json({ error: err.issues?.[0]?.message || err.errors?.[0]?.message || "Validation failed" });
}
res.status(500).json({ error: err.message });
}
}
// PATCH REQ FOR ADMIN RESET PASSWORD
module.exports.resetPassword = async (req, res) => {
try {
const project = req.project;
const { userId } = req.params;
const { newPassword } = req.body;
if (!newPassword || newPassword.length < 6) {
return res.status(400).json({ error: "Password must be at least 6 characters" });
}
const usersColConfig = project.collections.find(c => c.name === 'users');
if (!usersColConfig) return res.status(404).json({ error: "Auth collection not found" });
const connection = await getConnection(project._id);
const Model = getCompiledModel(connection, usersColConfig, project._id, project.resources.db.isExternal);
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(newPassword, salt);
const result = await Model.updateOne(
{ _id: new mongoose.Types.ObjectId(userId) },
{ $set: { password: hashedPassword } }
);
if (result.matchedCount === 0) {
return res.status(404).json({ error: "User not found" });
}
res.json({ message: "Password updated successfully" });
} catch (err) {
res.status(500).json({ error: err.message });
}
}
// POST REQ FOR EMAIL VERIFICATION
module.exports.verifyEmail = async (req, res) => {
try {
const project = req.project;
const { email, otp } = verifyOtpSchema.parse(req.body);
const redisKey = `project:${project._id}:otp:verification:${email}`;
const storedOtp = await redis.get(redisKey);
if (!storedOtp || storedOtp !== otp) {
return res.status(400).json({ error: "Invalid or expired OTP" });
}
const usersColConfig = project.collections.find(c => c.name === 'users');
if (!usersColConfig) return res.status(404).json({ error: "Auth collection not found" });
const connection = await getConnection(project._id);
const Model = getCompiledModel(connection, usersColConfig, project._id, project.resources.db.isExternal);
const verificationField = getVerificationField(usersColConfig);
if (!verificationField) {
return res.status(500).json({ error: "No verification field found in users schema" });
}
const result = await Model.updateOne(
{ email },
{ $set: { [verificationField]: true } }
);
if (result.matchedCount === 0) return res.status(404).json({ error: "User not found" });
await redis.del(redisKey);
res.json({ message: "Email verified successfully" });
} catch (err) {
if (err instanceof z.ZodError) return res.status(400).json({ error: err.issues?.[0]?.message || "Validation failed" });
res.status(500).json({ error: err.message });
}
};
// POST REQ FOR PASSWORD RESET REQUEST
module.exports.requestPasswordReset = async (req, res) => {
try {
const project = req.project;
const { email } = onlyEmailSchema.parse(req.body);
const usersColConfig = project.collections.find(c => c.name === 'users');
if (!usersColConfig) return res.status(404).json({ error: "Auth collection not found" });
const connection = await getConnection(project._id);
const Model = getCompiledModel(connection, usersColConfig, project._id, project.resources.db.isExternal);
const user = await Model.findOne({ email });
if (!user) {
return res.json({ message: "If that email exists, a reset code has been sent." });
}
const otp = Math.floor(100000 + Math.random() * 900000).toString();
await redis.set(`project:${project._id}:otp:reset:${email}`, otp, 'EX', 300);
await authEmailQueue.add('send-reset-email', { email, otp, type: 'password_reset', pname: project.name });
res.json({ message: "If that email exists, a reset code has been sent." });
} catch (err) {
if (err instanceof z.ZodError) return res.status(400).json({ error: err.issues?.[0]?.message || "Validation failed" });
res.status(500).json({ error: err.message });
}
};
// POST REQ FOR PASSWORD RESET CONFIRMATION
module.exports.resetPasswordUser = async (req, res) => {
try {
const project = req.project;
const { email, otp, newPassword } = resetPasswordSchema.parse(req.body);
const redisKey = `project:${project._id}:otp:reset:${email}`;
const storedOtp = await redis.get(redisKey);
if (!storedOtp || storedOtp !== otp) {
return res.status(400).json({ error: "Invalid or expired OTP" });
}
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(newPassword, salt);
const collection = await getAuthCollection(project);
const result = await collection.updateOne(
{ email },
{ $set: { password: hashedPassword } }
);
if (result.matchedCount === 0) return res.status(404).json({ error: "User not found" });
await redis.del(redisKey);
res.json({ message: "Password updated successfully" });
} catch (err) {
if (err instanceof z.ZodError) return res.status(400).json({ error: err.issues?.[0]?.message || "Validation failed" });
res.status(500).json({ error: err.message });
}
};
// PATCH REQ FOR UPDATE PROFILE
module.exports.updateProfile = async (req, res) => {
try {
const project = req.project;
const tokenHeader = req.header('Authorization');
if (!tokenHeader) return res.status(401).json({ error: "Access Denied: No Token Provided" });
const token = tokenHeader.replace("Bearer ", "");
let decoded;
try {
decoded = jwt.verify(token, project.jwtSecret);
} catch (err) {
return res.status(401).json({ error: "Access Denied: Invalid or expired token" });
}
const username = req.body.username;
if (!username || username.length < 3 || username.length > 50) {
return res.status(400).json({ error: "Username must be between 3 and 50 characters." });
}
const collection = await getAuthCollection(project);
const result = await collection.updateOne(
{ _id: new mongoose.Types.ObjectId(decoded.userId) },
{ $set: { username } }
);
res.json({ message: "Profile updated successfully" });
} catch (err) {
res.status(500).json({ error: err.message });
}
};
// POST REQ FOR CHANGE PASSWORD
module.exports.changePasswordUser = async (req, res) => {
try {
const project = req.project;
const tokenHeader = req.header('Authorization');
if (!tokenHeader) return res.status(401).json({ error: "Access Denied: No Token Provided" });
const token = tokenHeader.replace("Bearer ", "");
let decoded;
try {
decoded = jwt.verify(token, project.jwtSecret);
} catch (err) {
return res.status(401).json({ error: "Access Denied: Invalid or expired token" });
}
const { currentPassword, newPassword } = changePasswordSchema.parse(req.body);
const usersColConfig = project.collections.find(c => c.name === 'users');
if (!usersColConfig) return res.status(404).json({ error: "Auth collection not found" });
const connection = await getConnection(project._id);
const Model = getCompiledModel(connection, usersColConfig, project._id, project.resources.db.isExternal);
const user = await Model.findOne({ _id: new mongoose.Types.ObjectId(decoded.userId) });
if (!user) return res.status(404).json({ error: "User not found" });
const validPass = await bcrypt.compare(currentPassword, user.password);
if (!validPass) return res.status(400).json({ error: "Invalid current password" });
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(newPassword, salt);
await Model.updateOne(
{ _id: new mongoose.Types.ObjectId(decoded.userId) },
{ $set: { password: hashedPassword } }
);
res.json({ message: "Password changed successfully" });
} catch (err) {
if (err instanceof z.ZodError) return res.status(400).json({ error: err.issues?.[0]?.message || "Validation failed" });
res.status(500).json({ error: err.message });
}
};
// FUNCTION - GET USER DETAILS (ADMIN)
module.exports.getUserDetails = async (req, res) => {
try {
const project = req.project;
const { userId } = req.params;
const usersColConfig = project.collections.find(c => c.name === 'users');
if (!usersColConfig) return res.status(404).json({ error: "Auth collection not found" });
const connection = await getConnection(project._id);
const Model = getCompiledModel(connection, usersColConfig, project._id, project.resources.db.isExternal);
const user = await Model.findOne(
{ _id: new mongoose.Types.ObjectId(userId) },
{ password: 0 }
).lean();
if (!user) return res.status(404).json({ error: "User not found" });
res.json(user);
} catch (err) {
res.status(500).json({ error: err.message });
}
};
// PUT REQ FOR UPDATE ADMIN USER
module.exports.updateAdminUser = async (req, res) => {
try {
const project = req.project;
const { userId } = req.params;
const updateData = req.body;
delete updateData.password;
delete updateData._id;
const sanitizedUpdateData = sanitize(updateData);
// Get Mongoose Model
const usersColConfig = project.collections.find(c => c.name === 'users');
if (!usersColConfig) return res.status(404).json({ error: "Auth collection not found" });
const connection = await getConnection(project._id);
const Model = getCompiledModel(connection, usersColConfig, project._id, project.resources.db.isExternal);
const result = await Model.updateOne(
{ _id: new mongoose.Types.ObjectId(userId) },
{ $set: sanitizedUpdateData },
{ runValidators: true }
);
if (result.matchedCount === 0) {
return res.status(404).json({ error: "User not found" });
}
res.json({ message: "User updated successfully" });
} catch (err) {
res.status(500).json({ error: err.message });
}
};