-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathloginController.js
More file actions
596 lines (526 loc) · 16.5 KB
/
Copy pathloginController.js
File metadata and controls
596 lines (526 loc) · 16.5 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
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const getUserCredentials = require("../model/getUserCredentials.js");
const { addMfaToken, verifyMfaToken } = require("../model/addMfaToken.js");
const logLoginEvent = require("../Monitor_&_Logging/loginLogger");
const getUserCredentials = require("../model/getUserCredentials.js");
const {
addMfaToken,
invalidateMfaTokens,
verifyMfaToken,
} = require("../model/addMfaToken.js");
const crypto = require("crypto");
const { validationResult } = require("express-validator");
const { logSecurityEvent } = require("../services/securityEventService");
const logger = require("../utils/logger");
// Access token helper
function createAccessToken(user) {
return jwt.sign(
{
userId: user.user_id,
role: user.user_roles?.role_name || "unknown",
},
process.env.JWT_TOKEN,
{ expiresIn: "1h" }
);
const { createLog, log } = require("../services/securityLogger");
const logger = require("../utils/logger");
const nodemailer = require("nodemailer");
const {
authOk,
authFail,
authValidationError,
AUTH_ERROR_CODES,
} = require("../services/authResponse");
const { msg } = require("../utils/messages");
const { sessionHookOnLoginSuccess } = require("../services/sessionLogService");
const authService = require("../services/authService");
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: process.env.GMAIL_USER,
pass: process.env.GMAIL_APP_PASSWORD,
},
});
function sanitizeUserForResponse(user) {
if (!user) return user;
const { password, ...safeUser } = user;
return safeUser;
}
function getDeviceInfo(req) {
return {
ip: req.ip,
userAgent: req.get("User-Agent") || "Unknown",
deviceId: req.get("X-Device-Id") || null,
clientType: req.get("X-Client-Type") || "web",
};
}
const login = async (req, res) => {
console.log("LOGIN CONTROLLER HIT");
const errors = validationResult(req);
if (!errors.isEmpty()) {
return authValidationError(res, errors.array());
}
const email = req.body.email?.trim().toLowerCase();
const password = req.body.password;
let clientIp =
req.headers["x-forwarded-for"] || req.socket.remoteAddress || req.ip;
clientIp = clientIp === "::1" ? "127.0.0.1" : clientIp;
if (!email || !password) {
return res.status(400).json({ error: "Email and password are required" });
log(
createLog({
event_type: "AUTH_LOGIN_FAILED",
severity_level: "MEDIUM",
user_id: null,
source_service: "login-controller",
ip_address: clientIp,
endpoint: req.originalUrl,
method: req.method,
status: "FAILED",
message: "Missing email or password",
})
);
return authFail(res, {
message: msg("auth.login.failed_missing_fields"),
code: AUTH_ERROR_CODES.MISSING_FIELDS,
status: 400,
});
}
const tenMinutesAgoISO = new Date(Date.now() - 10 * 60 * 1000).toISOString();
try {
const { data: failuresByEmail } = await supabase
.from("brute_force_logs")
.select("id")
.eq("email", email)
.eq("success", false)
.gte("created_at", tenMinutesAgoISO);
const failureCount = failuresByEmail?.length || 0;
if (failureCount >= 10) {
return authFail(res, {
message:
"Too many failed login attempts. Please try again after 10 minutes.",
code: AUTH_ERROR_CODES.RATE_LIMITED,
status: 429,
});
}
const user = await getUserCredentials(email);
// User not found
if (!user) {
if (!user) {
await supabase.from("brute_force_logs").insert([
{
email,
ip_address: clientIp,
success: false,
created_at: new Date().toISOString(),
},
]);
await logSecurityEvent({
event_type: "LOGIN_FAILED",
severity: "medium",
user_id: null,
ip_address: clientIp,
user_agent: req.headers["user-agent"],
resource: "/api/auth/login",
metadata: {
email,
reason: "user_not_found",
},
});
reason: "account_not_found",
},
});
log(
createLog({
event_type: "AUTH_LOGIN_FAILED",
severity_level: "MEDIUM",
user_id: null,
source_service: "login-controller",
ip_address: clientIp,
endpoint: req.originalUrl,
method: req.method,
status: "FAILED",
message: "User not found",
})
);
await sendFailedLoginAlert(email, clientIp);
// Privacy-preserving: surface the same shape as invalid credentials so
// attackers can't enumerate accounts. Code stays distinct for ops/logs.
return authFail(res, {
message: msg("auth.login.failed_credentials"),
code: AUTH_ERROR_CODES.INVALID_CREDENTIALS,
status: 401,
});
}
const isPasswordValid = await bcrypt.compare(password, user.password);
// Wrong password
if (!isPasswordValid) {
if (!isPasswordValid) {
await supabase.from("brute_force_logs").insert([
{
email,
ip_address: clientIp,
success: false,
created_at: new Date().toISOString(),
},
]);
await logSecurityEvent({
event_type: "LOGIN_FAILED",
severity: "medium",
user_id: user.user_id,
ip_address: clientIp,
user_agent: req.headers["user-agent"],
resource: "/api/auth/login",
metadata: {
email,
reason: "invalid_password",
},
});
log(
createLog({
event_type: "AUTH_LOGIN_FAILED",
severity_level: "MEDIUM",
user_id: user.user_id,
source_service: "login-controller",
ip_address: clientIp,
endpoint: req.originalUrl,
method: req.method,
status: "FAILED",
message: "Invalid password",
})
);
if (failureCount === 4) {
return authFail(res, {
message:
"You have one attempt left before your account is temporarily locked.",
code: AUTH_ERROR_CODES.RATE_LIMITED,
status: 429,
details: { attemptsRemaining: 1 },
});
}
await sendFailedLoginAlert(email, clientIp);
return authFail(res, {
message: msg("auth.login.failed_credentials"),
code: AUTH_ERROR_CODES.INVALID_CREDENTIALS,
status: 401,
});
}
// MFA enabled
if (user.mfa_enabled) {
const token = crypto.randomInt(100000, 999999);
await addMfaToken(user.user_id, token);
await logSecurityEvent({
event_type: "MFA_CHALLENGE_ISSUED",
severity: "low",
await supabase.from("brute_force_logs").insert([
{
email,
success: true,
created_at: new Date().toISOString(),
},
]);
await supabase
.from("brute_force_logs")
.delete()
.eq("email", email)
.eq("success", false);
log(
createLog({
event_type: "AUTH_LOGIN_SUCCESS",
severity_level: "LOW",
user_id: user.user_id,
ip_address: clientIp,
user_agent: req.headers["user-agent"],
resource: "/api/auth/login",
metadata: {
email,
},
});
return res.status(202).json({
message: "An MFA Token has been generated for this login attempt",
});
}
// Successful login
await logSecurityEvent({
event_type: "LOGIN_SUCCESS",
severity: "low",
user_id: user.user_id,
ip_address: clientIp,
user_agent: req.headers["user-agent"],
resource: "/api/auth/login",
metadata: {
email,
},
endpoint: req.originalUrl,
method: req.method,
status: "SUCCESS",
message: "User logged in successfully",
})
);
if (user.mfa_enabled) {
const mfaToken = crypto.randomInt(100000, 999999);
await addMfaToken(user.user_id, mfaToken);
await sendOtpEmail(user.email, mfaToken);
return authOk(
res,
{ mfaRequired: true, mfaChannel: "email" },
{
status: 202,
message: "An MFA token has been sent to your email address.",
meta: { nextStep: "POST /api/login/mfa" },
}
);
}
await logLoginEvent({
userId: user.user_id,
eventType: "LOGIN_SUCCESS",
ip: clientIp,
userAgent: req.headers["user-agent"],
});
await logSecurityEvent({
event_type: "LOGIN_SUCCESS",
severity: "low",
user_id: user.user_id,
session_id: null,
ip_address: clientIp,
user_agent: req.headers["user-agent"],
resource: "/api/auth/login",
metadata: {
email,
},
});
const session = await authService.generateTokenPair(user, getDeviceInfo(req));
// CT-004 Week 6: Log session for alert A6 (geo-impossible travel detection)
try {
await sessionHookOnLoginSuccess(req, user);
} catch (hookErr) {
logger.warn('[loginController] sessionHookOnLoginSuccess failed:', hookErr.message);
// Don't block login if hook fails
}
return authOk(res, {
user: sanitizeUserForResponse(user),
token: session.accessToken,
accessToken: session.accessToken,
refreshToken: session.refreshToken,
expiresIn: session.expiresIn,
tokenType: session.tokenType,
session,
});
} catch (err) {
console.error("Login error:", err);
if (logger && logger.error) {
logger.error("Login error", err);
}
return res.status(500).json({ error: "Internal server error" });
}
};
// ================= MFA LOGIN =================
=======
log(
createLog({
event_type: "SYSTEM_ERROR",
severity_level: "HIGH",
user_id: null,
source_service: "login-controller",
ip_address: clientIp,
endpoint: req.originalUrl,
method: req.method,
status: "ERROR",
message: err.message,
})
);
logger.error("Login error", err);
return authFail(res, {
message: msg("general.internal_error"),
code: AUTH_ERROR_CODES.INTERNAL_ERROR,
status: 500,
});
}
};
const loginMfa = async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return authValidationError(res, errors.array());
}
const email = req.body.email?.trim().toLowerCase();
const password = req.body.password;
const mfa_token = req.body.mfa_token;
let clientIp =
req.headers["x-forwarded-for"] || req.socket.remoteAddress || req.ip;
clientIp = clientIp === "::1" ? "127.0.0.1" : clientIp;
if (!email || !password || !mfa_token) {
return res.status(400).json({
error: "Email, password, and token are required",
return authFail(res, {
message: msg("auth.login.mfa_required"),
code: AUTH_ERROR_CODES.MFA_REQUIRED,
status: 400,
});
}
try {
const user = await getUserCredentials(email);
if (!user) {
await logSecurityEvent({
event_type: "MFA_FAILED",
severity: "medium",
user_id: null,
ip_address: clientIp,
user_agent: req.headers["user-agent"],
resource: "/api/auth/login-mfa",
metadata: {
email,
reason: "user_not_found",
},
});
return res.status(401).json({ error: "Invalid credentials" });
return authFail(res, {
message: msg("auth.login.failed_credentials"),
code: AUTH_ERROR_CODES.INVALID_CREDENTIALS,
status: 401,
});
}
const validPassword = await bcrypt.compare(password, user.password);
const validToken = await verifyMfaToken(user.user_id, mfa_token);
if (!validPassword || !validToken) {
await logSecurityEvent({
event_type: "MFA_FAILED",
severity: "medium",
user_id: user.user_id,
ip_address: clientIp,
user_agent: req.headers["user-agent"],
resource: "/api/auth/login-mfa",
metadata: {
email,
reason: "invalid_password_or_mfa_token",
},
});
return res.status(401).json({ error: "Invalid credentials" });
}
await logSecurityEvent({
event_type: "MFA_SUCCESS",
severity: "low",
user_id: user.user_id,
ip_address: clientIp,
user_agent: req.headers["user-agent"],
resource: "/api/auth/login-mfa",
metadata: {
email,
},
});
const token = createAccessToken(user);
return res.status(200).json({ user, token });
} catch (err) {
console.error("MFA error:", err);
if (logger && logger.error) {
logger.error("MFA error", err);
}
return res.status(500).json({ error: "Internal server error" });
return authFail(res, {
message: msg("auth.login.mfa_invalid"),
code: AUTH_ERROR_CODES.MFA_INVALID,
status: 401,
});
}
const session = await authService.generateTokenPair(user, getDeviceInfo(req));
return authOk(res, {
user: sanitizeUserForResponse(user),
token: session.accessToken,
accessToken: session.accessToken,
refreshToken: session.refreshToken,
expiresIn: session.expiresIn,
tokenType: session.tokenType,
session,
});
} catch (err) {
logger.error("MFA error", err);
return authFail(res, {
message: msg("general.internal_error"),
code: AUTH_ERROR_CODES.INTERNAL_ERROR,
status: 500,
});
}
};
async function sendOtpEmail(email, token) {
try {
if (!process.env.GMAIL_USER || !process.env.GMAIL_APP_PASSWORD) {
console.log(`📨 [DEV] MFA code for ${email}: ${token}`);
return;
}
await transporter.sendMail({
from: `"NutriHelp Security" <${process.env.GMAIL_USER}>`,
to: email,
subject: "NutriHelp Login Token",
text: `Your one-time login token is: ${token}\n\nThis token expires in 10 minutes.\n\nIf you did not request this, please ignore this email.\n\n- NutriHelp Security Team`,
html: `
<p>Your one-time login token is:</p>
<h2>${token}</h2>
<p>This token expires in <strong>10 minutes</strong>.</p>
<p>If you did not request this, please ignore this email.</p>
<br/>
<p>- NutriHelp Security Team</p>
`,
});
console.log("OTP email sent successfully to", email);
} catch (err) {
console.error("Error sending OTP email:", err.message);
}
}
const resendMfa = async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return authValidationError(res, errors.array());
}
const email = req.body.email?.trim().toLowerCase();
try {
const user = await getUserCredentials(email);
if (!user || !user.mfa_enabled) {
return authFail(res, {
message: "MFA is not enabled for this account",
code: AUTH_ERROR_CODES.MFA_DISABLED,
status: 404,
});
}
await invalidateMfaTokens(user.user_id);
const token = crypto.randomInt(100000, 999999);
await addMfaToken(user.user_id, token);
await sendOtpEmail(user.email, token);
return authOk(
res,
{ mfaChannel: "email" },
{ message: "A new MFA token has been sent to your email address." }
);
} catch (err) {
logger.error("MFA resend error", err);
return authFail(res, {
message: "Unable to resend MFA token",
code: AUTH_ERROR_CODES.MFA_RESEND_FAILED,
status: 500,
});
}
};
async function sendFailedLoginAlert(email, ip) {
try {
if (!process.env.GMAIL_USER || !process.env.GMAIL_APP_PASSWORD) {
console.log(`[DEV] Failed login alert for ${email} from IP ${ip}`);
return;
}
await transporter.sendMail({
from: `"NutriHelp Security" <${process.env.GMAIL_USER}>`,
to: email,
subject: "Failed Login Attempt on NutriHelp",
text: `Hi,\n\nSomeone tried to log in to NutriHelp using your email address from IP: ${ip}.\n\nIf this wasn't you, please ignore this message. If you're concerned, consider resetting your password or contacting support.\n\n- NutriHelp Security Team`,
html: `
<p>Hi,</p>
<p>Someone tried to log in to <strong>NutriHelp</strong> using your email address from IP: <code>${ip}</code>.</p>
<p>If this wasn't you, please ignore this message. If you're concerned, consider resetting your password or contacting support.</p>
<br/>
<p>- NutriHelp Security Team</p>
`,
});
console.log(`Failed login alert sent to ${email}`);
} catch (err) {
console.error("Failed to send alert email:", err.message);
}
}
module.exports = { login, loginMfa, resendMfa };