forked from Deen-Bridge/dnb-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthController.js
More file actions
830 lines (713 loc) · 25 KB
/
Copy pathauthController.js
File metadata and controls
830 lines (713 loc) · 25 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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
// controllers/authController.js
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import crypto from "crypto";
import User from "../models/User.js";
import PendingUser from "../models/PendingUser.js";
import Session from "../models/Session.js";
import { sendOtpEmail, sendVerificationEmail } from "../../services/emails/sendMail.js";
import logger from "../config/logger.js";
import { enqueue } from "../jobs/queue.js";
import { recordAudit } from "../services/audit/auditService.js";
import { AUDIT_ACTIONS } from "../models/AuditLog.js";
import { generateOtp, hashOtp, verifyOtp } from "../utils/otp.js";
import { firstPasswordIssue } from "../utils/passwordPolicy.js";
import { catchAsync, APIError } from "../middlewares/errorHandler.js";
const JWT_SECRET = process.env.JWT_SECRET || "deenbridge-temp-secret-key-2024";
// Log JWT configuration on startup and warn if using fallback
if (!process.env.JWT_SECRET) {
logger.warn(
"⚠️ WARNING: JWT_SECRET not found in .env! Using fallback (INSECURE for production)"
);
} else {
logger.info(
`✅ JWT_SECRET loaded from .env (length: ${process.env.JWT_SECRET.length})`
);
}
// Helper: parse duration string to ms (e.g. 15m, 30d)
export const parseDurationToMs = (duration) => {
const match = duration.match(/^(\d+)([smhd])$/);
if (!match) return 30 * 24 * 60 * 60 * 1000; // default 30 days
const value = parseInt(match[1], 10);
const unit = match[2];
switch (unit) {
case "s": return value * 1000;
case "m": return value * 60 * 1000;
case "h": return value * 60 * 60 * 1000;
case "d": return value * 24 * 60 * 60 * 1000;
default: return value * 24 * 60 * 60 * 1000;
}
};
// Helper: get device label from user agent
const getDeviceLabel = (userAgent) => {
if (!userAgent) return "Unknown Device";
let os = "Unknown OS";
if (userAgent.includes("Windows")) os = "Windows";
else if (userAgent.includes("Macintosh") || userAgent.includes("Mac OS")) os = "macOS";
else if (userAgent.includes("Linux")) os = "Linux";
else if (userAgent.includes("Android")) os = "Android";
else if (userAgent.includes("iPhone") || userAgent.includes("iPad")) os = "iOS";
let browser = "Unknown Browser";
if (userAgent.includes("Firefox")) browser = "Firefox";
else if (userAgent.includes("Chrome")) browser = "Chrome";
else if (userAgent.includes("Safari")) browser = "Safari";
else if (userAgent.includes("Edge")) browser = "Edge";
else if (userAgent.includes("Opera")) browser = "Opera";
return `${browser} on ${os}`;
};
// Helper: shape the public user object returned by every auth response.
// Kept in one place so email login, register, and Stellar login stay identical.
export const shapeAuthUser = (user) => ({
id: user._id,
name: user.name,
role: user.role,
email: user.email,
avatar: user.avatar,
gender: user.gender,
age: user.age,
country: user.country,
language: user.language,
interests: user.interests,
bio: user.bio,
isVerified: user.isVerified,
});
// Helper: generate new session + refresh token + cookie + access token
export const createSessionAndTokens = async (user, req, res) => {
const rawRefreshToken = crypto.randomBytes(32).toString("hex");
const refreshTokenHash = crypto.createHash("sha256").update(rawRefreshToken).digest("hex");
const refreshTtl = process.env.REFRESH_TOKEN_TTL || "30d";
const refreshDurationMs = parseDurationToMs(refreshTtl);
const expiresAt = new Date(Date.now() + refreshDurationMs);
const family = crypto.randomUUID();
const session = await Session.create({
user: user._id,
refreshTokenHash,
family,
device: {
userAgent: req.headers["user-agent"] || "unknown",
ip: req.ip || "unknown",
label: getDeviceLabel(req.headers["user-agent"]),
},
expiresAt,
});
const accessTokenTtl = process.env.ACCESS_TOKEN_TTL || "15m";
const accessToken = jwt.sign(
{ userId: user._id, role: user.role, sessionId: session._id },
JWT_SECRET,
{ expiresIn: accessTokenTtl }
);
// Set Cookie scoped to refresh path
const isProd = process.env.NODE_ENV === "production";
res.cookie("refreshToken", rawRefreshToken, {
httpOnly: true,
secure: isProd,
sameSite: isProd ? "None" : "Lax",
path: "/api/auth/refresh",
maxAge: refreshDurationMs,
});
return { accessToken, refreshToken: rawRefreshToken };
};
export const registerUser = catchAsync(async (req, res, next) => {
const { name, email, password, role } = req.body;
logger.info(`📝 Registration attempt for: ${email}`);
// Enforce the password policy before anything else touches it. The client
// shows the same rules live, but that check is bypassable.
const passwordIssue = firstPasswordIssue(password, { name, email });
if (passwordIssue) {
logger.warn(`❌ Registration failed - weak password: ${email}`);
recordAudit({
action: AUDIT_ACTIONS.AUTH_REGISTER_FAILURE,
actor: null,
req,
targetType: "User",
targetId: email,
status: "failure",
metadata: { email, reason: "weak_password" },
});
return next(new APIError(passwordIssue, 400));
}
// Check if user already exists
const existing = await User.findOne({ email });
if (existing) {
logger.warn(`❌ Registration failed - Email already exists: ${email}`);
recordAudit({
action: AUDIT_ACTIONS.AUTH_REGISTER_FAILURE,
actor: null,
req,
targetType: "User",
targetId: email,
status: "failure",
metadata: { email, reason: "email_already_exists" },
});
return next(new APIError("Email already exists", 400));
}
// Hash password
const hashedPassword = await bcrypt.hash(password, 12);
// Users can only self-register as student or mentor. Privileged roles
// (admin) can never be self-assigned — they are granted only to accounts
// whose email is on the ADMIN_EMAILS whitelist.
const ADMIN_EMAILS = (process.env.ADMIN_EMAILS || "")
.split(",")
.map((e) => e.trim().toLowerCase())
.filter(Boolean);
const allowedSelfRegistrationRoles = ["student", "mentor"];
let assignedRole = allowedSelfRegistrationRoles.includes(role) ? role : "student";
if (ADMIN_EMAILS.includes(email.toLowerCase())) {
assignedRole = "admin";
logger.info(`👑 Whitelisted admin account registering: ${email}`);
} else if (!allowedSelfRegistrationRoles.includes(role)) {
logger.warn(
`⛔ Blocked invalid role attempt: ${email} tried to register as "${role}"`
);
assignedRole = "student";
}
// Generate verification token
const verificationToken = crypto.randomBytes(32).toString("hex");
// Store pending user (auto-deletes after 24h via TTL index)
const pendingUser = await PendingUser.findOneAndUpdate(
{ email },
{
name,
email,
password: hashedPassword,
role: assignedRole,
verificationToken,
},
{ upsert: true, new: true },
);
try {
await sendVerificationEmail(email, verificationToken);
} catch (err) {
// Email delivery failed (e.g. provider outage / disconnected sender).
// Roll back the pending record so the user can retry cleanly, and return a
// clear 503 rather than a generic 500 "Programming Error".
await PendingUser.deleteOne({ _id: pendingUser._id }).catch(() => {});
logger.error(`Verification email delivery failed for ${email}: ${err.message}`);
recordAudit({
action: AUDIT_ACTIONS.AUTH_REGISTER_FAILURE,
actor: null,
req,
targetType: "User",
targetId: email,
status: "failure",
metadata: { email, reason: "verification_email_failed" },
});
return next(
new APIError(
"We couldn't send your verification email right now. Please try again in a few minutes.",
503
)
);
}
recordAudit({
action: AUDIT_ACTIONS.AUTH_REGISTER_SUCCESS,
actor: pendingUser._id,
req,
targetType: "User",
targetId: pendingUser._id.toString(),
status: "success",
metadata: { email, assignedRole, name },
});
res.status(201).json({
success: true,
message:
"Please check your email to verify your account. The link expires in 24 hours.",
});
});
export const verifyEmail = catchAsync(async (req, res, next) => {
const { token } = req.params;
if (!token) {
return next(new APIError("Verification token is required", 400));
}
// Find the pending user by token
const pending = await PendingUser.findOne({ verificationToken: token });
if (!pending) {
return next(new APIError("Invalid or expired verification token. Please register again.", 400));
}
// Check for duplicate (e.g., if another registration happened in the meantime)
const existing = await User.findOne({ email: pending.email });
if (existing) {
await PendingUser.deleteOne({ _id: pending._id });
return next(new APIError("This email is already registered. Please log in.", 400));
}
// Create the real user
const user = await User.create({
name: pending.name,
email: pending.email,
password: pending.password,
role: pending.role,
isVerified: true,
});
// Remove the pending record
await PendingUser.deleteOne({ _id: pending._id });
// Generate session and tokens so user is logged in immediately
const { accessToken, refreshToken } = await createSessionAndTokens(user, req, res);
logger.info(`✅ Email verified & user created: ${user.email} (ID: ${user._id})`);
res.status(200).json({
success: true,
message: "Email verified successfully. Welcome to DeenBridge!",
accessToken,
refreshToken,
token: accessToken,
user: {
id: user._id,
name: user.name,
role: user.role,
email: user.email,
isVerified: true,
},
});
});
export const resendVerification = catchAsync(async (req, res, next) => {
const { email } = req.body;
if (!email) {
return next(new APIError("Email is required", 400));
}
const pending = await PendingUser.findOne({ email });
if (!pending) {
// Check if user is already fully registered
const user = await User.findOne({ email });
if (user) {
return next(new APIError("This email is already verified. Please log in.", 400));
}
return next(new APIError("No pending registration found with this email. Please register first.", 404));
}
const verificationToken = crypto.randomBytes(32).toString("hex");
pending.verificationToken = verificationToken;
await pending.save();
try {
await sendVerificationEmail(email, verificationToken);
} catch (err) {
// Provider outage / disconnected sender — return a clear 503 so the client
// can prompt a retry instead of surfacing a generic 500.
logger.error(`Verification email resend failed for ${email}: ${err.message}`);
return next(
new APIError(
"We couldn't resend your verification email right now. Please try again in a few minutes.",
503
)
);
}
logger.info(`📧 Verification email resent to: ${email}`);
res.status(200).json({
success: true,
message: "Verification email sent. Please check your inbox.",
});
});
export const loginUser = catchAsync(async (req, res, next) => {
const { email, password } = req.body;
logger.info(`🔐 Login attempt for: ${email} from IP: ${req.ip}`);
// Validate input
if (!email || !password) {
return next(new APIError("Please provide email and password", 400));
}
// Find user
const user = await User.findOne({ email }).select("+password");
if (!user) {
logger.warn(`❌ Login failed - User not found: ${email}`);
recordAudit({
action: AUDIT_ACTIONS.AUTH_LOGIN_FAILURE,
actor: null,
req,
targetType: "User",
targetId: email,
status: "failure",
metadata: { email, reason: "user_not_found" },
});
return next(new APIError("Invalid credentials", 401));
}
// Verify password
const isPasswordCorrect = await bcrypt.compare(password, user.password);
if (!isPasswordCorrect) {
logger.warn(`❌ Login failed - Incorrect password: ${email}`);
recordAudit({
action: AUDIT_ACTIONS.AUTH_LOGIN_FAILURE,
actor: user._id,
req,
targetType: "User",
targetId: user._id.toString(),
status: "failure",
metadata: { email, reason: "invalid_password" },
});
return next(new APIError("Invalid credentials", 401));
}
// Auto-promote whitelisted admin emails (self-healing for existing accounts)
const ADMIN_EMAILS = (process.env.ADMIN_EMAILS || "")
.split(",")
.map((e) => e.trim().toLowerCase())
.filter(Boolean);
if (ADMIN_EMAILS.includes(user.email.toLowerCase()) && user.role !== "admin") {
user.role = "admin";
await user.save({ validateBeforeSave: false });
logger.info(`👑 Promoted ${user.email} to admin (whitelisted account)`);
}
// Update last login
user.lastLogin = new Date();
await user.save({ validateBeforeSave: false });
// Generate session and tokens
const { accessToken, refreshToken } = await createSessionAndTokens(user, req, res);
logger.info(`✅ Login successful: ${email} (ID: ${user._id})`);
recordAudit({
action: AUDIT_ACTIONS.AUTH_LOGIN_SUCCESS,
actor: user._id,
req,
targetType: "User",
targetId: user._id.toString(),
status: "success",
metadata: { email, role: user.role },
});
res.status(200).json({
success: true,
message: "Login successful",
accessToken,
refreshToken,
token: accessToken, // legacy token field
user: {
id: user._id,
name: user.name,
role: user.role,
email: user.email,
avatar: user.avatar,
gender: user.gender,
age: user.age,
country: user.country,
language: user.language,
interests: user.interests,
bio: user.bio,
isVerified: user.isVerified,
},
});
});
// Request password reset (sends OTP)
export const requestPasswordReset = async (req, res) => {
const { email } = req.body;
try {
logger.info("🔑 Password reset requested for:", email);
if (!email || typeof email !== "string") {
return res.status(400).json({ success: false, message: "Invalid email address" });
}
const user = await User.findOne({ email });
if (!user) {
// Don't reveal if user exists or not for security
return res.status(200).json({
success: true,
message:
"If an account exists with this email, you will receive a password reset code.",
});
}
// Generate a 6-digit OTP
const otp = generateOtp();
// Store OTP hash and expiry in database (15 minutes)
const hashedOtp = await hashOtp(otp);
user.resetTokenHash = hashedOtp;
user.resetTokenExpiry = new Date(Date.now() + 15 * 60 * 1000);
await user.save();
// Send OTP via email with error handling to preserve anti-enumeration and clear orphaned tokens
try {
await sendOtpEmail(otp, email);
} catch (mailErr) {
logger.error("❌ Password reset email delivery error:", mailErr.message);
user.resetTokenHash = undefined;
user.resetTokenExpiry = undefined;
await user.save();
}
recordAudit({
action: AUDIT_ACTIONS.AUTH_PASSWORD_RESET_REQUEST,
actor: user._id,
req,
targetType: "User",
targetId: user._id.toString(),
status: "success",
metadata: { email },
});
res.status(200).json({
success: true,
message:
"If an account exists with this email, you will receive a password reset code.",
});
} catch (err) {
logger.error("❌ Password reset request error:", err.message);
res.status(500).json({ success: false, message: err.message });
}
};
// Reset password with OTP
export const resetPassword = async (req, res) => {
const { email, otp, newPassword } = req.body;
try {
logger.info("🔐 Password reset attempt for:", email);
if (!email || !otp || !newPassword) {
return res.status(400).json({ success: false, message: "Email, OTP, and new password are required" });
}
// Same policy as registration — a reset must not be a way around it.
const newPasswordIssue = firstPasswordIssue(newPassword, { email });
if (newPasswordIssue) {
logger.warn(`❌ Password reset failed - weak password: ${email}`);
return res.status(400).json({ success: false, message: newPasswordIssue });
}
const user = await User.findOne({ email }).select("+password");
if (!user) {
return res.status(400).json({ success: false, message: "Invalid or expired OTP" });
}
// Verify OTP presence and expiration
if (
!user.resetTokenHash ||
!user.resetTokenExpiry ||
new Date(user.resetTokenExpiry) < new Date()
) {
return res.status(400).json({ success: false, message: "Invalid or expired OTP" });
}
const isValidOtp = await verifyOtp(otp.toString(), user.resetTokenHash);
if (!isValidOtp) {
return res.status(400).json({ success: false, message: "Invalid or expired OTP" });
}
// Hash new password using cost factor 12 (aligned with registerUser)
const hashedPassword = await bcrypt.hash(newPassword, 12);
user.password = hashedPassword;
// Clear reset token fields (single use)
user.resetTokenHash = undefined;
user.resetTokenExpiry = undefined;
await user.save();
logger.info("✅ Password reset successful for:", email);
recordAudit({
action: AUDIT_ACTIONS.AUTH_PASSWORD_RESET_COMPLETE,
actor: user._id,
req,
targetType: "User",
targetId: user._id.toString(),
status: "success",
metadata: { email },
});
res.status(200).json({
success: true,
message:
"Password reset successful. You can now login with your new password.",
});
} catch (err) {
logger.error("❌ Password reset error:", err.message);
res.status(500).json({ success: false, message: err.message });
}
};
export const refreshSession = catchAsync(async (req, res, next) => {
const rawToken = req.cookies.refreshToken || req.body.refreshToken;
if (!rawToken) {
return next(new APIError("No refresh token provided", 401));
}
const hash = crypto.createHash("sha256").update(rawToken).digest("hex");
const session = await Session.findOne({ refreshTokenHash: hash }).populate("user");
if (!session) {
return next(new APIError("Invalid refresh token", 401));
}
// Expired-but-honest check
if (session.expiresAt < new Date()) {
return next(new APIError("Refresh token expired", 401));
}
// Reuse detection
if (session.revokedAt || session.replacedBy) {
await Session.updateMany(
{ family: session.family },
{ $set: { revokedAt: new Date() } }
);
logger.warn(
`🚨 Refresh token reuse detected! Revoked entire token family. Family: ${session.family}, IP: ${req.ip}, UA: ${req.headers["user-agent"]}`
);
return next(new APIError("Refresh token has been reused", 401));
}
// Perform rotation
const newRawToken = crypto.randomBytes(32).toString("hex");
const newHash = crypto.createHash("sha256").update(newRawToken).digest("hex");
const refreshTtl = process.env.REFRESH_TOKEN_TTL || "30d";
const refreshDurationMs = parseDurationToMs(refreshTtl);
const newExpiresAt = new Date(Date.now() + refreshDurationMs);
const newSession = await Session.create({
user: session.user._id,
refreshTokenHash: newHash,
family: session.family,
device: {
userAgent: req.headers["user-agent"] || "unknown",
ip: req.ip || "unknown",
label: getDeviceLabel(req.headers["user-agent"]),
},
expiresAt: newExpiresAt,
});
session.revokedAt = new Date();
session.replacedBy = newSession._id;
session.lastUsedAt = new Date();
await session.save();
const accessTokenTtl = process.env.ACCESS_TOKEN_TTL || "15m";
const accessToken = jwt.sign(
{ userId: session.user._id, role: session.user.role, sessionId: newSession._id },
JWT_SECRET,
{ expiresIn: accessTokenTtl }
);
const isProd = process.env.NODE_ENV === "production";
res.cookie("refreshToken", newRawToken, {
httpOnly: true,
secure: isProd,
sameSite: isProd ? "None" : "Lax",
path: "/api/auth/refresh",
maxAge: refreshDurationMs,
});
res.status(200).json({
success: true,
accessToken,
refreshToken: newRawToken,
token: accessToken, // legacy token field
user: {
id: session.user._id,
name: session.user.name,
role: session.user.role,
email: session.user.email,
avatar: session.user.avatar,
gender: session.user.gender,
age: session.user.age,
country: session.user.country,
language: session.user.language,
interests: session.user.interests,
bio: session.user.bio,
isVerified: session.user.isVerified,
},
});
});
export const getSessions = catchAsync(async (req, res, next) => {
const activeSessions = await Session.find({
user: req.user._id,
revokedAt: null,
expiresAt: { $gt: new Date() },
});
const formattedSessions = activeSessions.map((session) => ({
id: session._id,
device: session.device,
lastUsedAt: session.lastUsedAt,
isCurrent: req.sessionId ? session._id.toString() === req.sessionId.toString() : false,
}));
res.status(200).json({
success: true,
sessions: formattedSessions,
});
});
export const revokeSession = catchAsync(async (req, res, next) => {
const session = await Session.findOne({
_id: req.params.sessionId,
user: req.user._id,
});
if (!session) {
return next(new APIError("Session not found", 404));
}
session.revokedAt = new Date();
await session.save();
res.status(200).json({
success: true,
message: "Session revoked successfully",
});
});
export const revokeAllOtherSessions = catchAsync(async (req, res, next) => {
if (!req.sessionId) {
return next(new APIError("Cannot revoke other sessions from a legacy session. Please re-login.", 400));
}
await Session.updateMany(
{
user: req.user._id,
_id: { $ne: req.sessionId },
revokedAt: null,
},
{
$set: { revokedAt: new Date() }
}
);
res.status(200).json({
success: true,
message: "All other sessions revoked successfully",
});
});
export const logoutUser = catchAsync(async (req, res, next) => {
if (req.sessionId) {
await Session.updateOne(
{ _id: req.sessionId },
{ $set: { revokedAt: new Date() } }
);
}
const rawToken = req.cookies.refreshToken || req.body.refreshToken;
if (rawToken) {
const hash = crypto.createHash("sha256").update(rawToken).digest("hex");
await Session.updateOne(
{ refreshTokenHash: hash },
{ $set: { revokedAt: new Date() } }
);
}
recordAudit({
action: AUDIT_ACTIONS.AUTH_LOGOUT,
actor: req.user?._id ?? null,
req,
targetType: "User",
targetId: req.user?._id?.toString() ?? null,
status: "success",
metadata: null,
});
const isProd = process.env.NODE_ENV === "production";
res.clearCookie("refreshToken", {
httpOnly: true,
secure: isProd,
sameSite: isProd ? "None" : "Lax",
path: "/api/auth/refresh",
});
res.status(200).json({
success: true,
message: "Logged out successfully",
});
});
// Change password for an authenticated user. Verifies the current password,
// enforces the password policy on the new one, and signs out all OTHER sessions.
export const changePassword = catchAsync(async (req, res, next) => {
const { currentPassword, newPassword } = req.body;
if (!currentPassword || !newPassword) {
return next(new APIError("Current and new password are required", 400));
}
const passwordIssue = firstPasswordIssue(newPassword, {
name: req.user?.name,
email: req.user?.email,
});
if (passwordIssue) {
return next(new APIError(passwordIssue, 400));
}
const user = await User.findById(req.user._id).select("+password");
if (!user || !user.password) {
return next(new APIError("User not found", 404));
}
const isCurrentCorrect = await bcrypt.compare(currentPassword, user.password);
if (!isCurrentCorrect) {
recordAudit({
action: AUDIT_ACTIONS.AUTH_PASSWORD_CHANGE,
actor: user._id,
req,
targetType: "User",
targetId: user._id.toString(),
status: "failure",
metadata: { reason: "invalid_current_password" },
});
return next(new APIError("Current password is incorrect", 401));
}
const isSameAsOld = await bcrypt.compare(newPassword, user.password);
if (isSameAsOld) {
return next(
new APIError("New password must be different from the current one", 400)
);
}
user.password = await bcrypt.hash(newPassword, 12);
await user.save();
// Sign out every OTHER session so a password change kicks other devices.
await Session.deleteMany({ user: user._id, _id: { $ne: req.sessionId } });
recordAudit({
action: AUDIT_ACTIONS.AUTH_PASSWORD_CHANGE,
actor: user._id,
req,
targetType: "User",
targetId: user._id.toString(),
status: "success",
metadata: {},
});
res.status(200).json({
success: true,
message:
"Password changed successfully. Other devices have been signed out.",
});
});