forked from Deen-Bridge/dnb-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpasswordReset.test.js
More file actions
280 lines (238 loc) · 9.22 KB
/
Copy pathpasswordReset.test.js
File metadata and controls
280 lines (238 loc) · 9.22 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
import { jest } from "@jest/globals";
import request from "supertest";
import mongoose from "mongoose";
import bcrypt from "bcrypt";
import app from "../app.js";
import User from "../src/models/User.js";
import PendingUser from "../src/models/PendingUser.js";
import Session from "../src/models/Session.js";
import logger from "../src/config/logger.js";
const testUser = {
name: "Reset User",
email: "reset_user@example.com",
password: "oldPassword123",
role: "student",
};
describe("Password Reset Flow", () => {
jest.setTimeout(30000);
let usersStore = [];
let sessionsStore = [];
let loggerInfoSpy;
beforeAll(() => {
// Capture the OTP code from the [EMAIL LOG] fallback (SMTP is unset in tests)
loggerInfoSpy = jest.spyOn(logger, "info");
// Mock User methods
jest.spyOn(User, "findOne").mockImplementation((query) => {
const email = query?.email;
const found = usersStore.find((u) => u.email === email);
return {
select: () => found || null,
then: (resolve) => resolve(found || null),
};
});
jest.spyOn(User, "findById").mockImplementation((id) => {
const found = usersStore.find((u) => u._id.toString() === id.toString());
return {
select: () => found || null,
then: (resolve) => resolve(found || null),
};
});
jest.spyOn(User, "create").mockImplementation(async (data) => {
const _id = new mongoose.Types.ObjectId().toString();
const newUser = {
_id,
...data,
save: async function () { return this; },
};
usersStore.push(newUser);
return newUser;
});
jest.spyOn(User, "deleteMany").mockImplementation(async () => {
usersStore = [];
return { acknowledged: true };
});
// Registration stores a pending user awaiting email verification
jest.spyOn(PendingUser, "findOneAndUpdate").mockImplementation(async (query, update) => {
const _id = new mongoose.Types.ObjectId().toString();
const newUser = {
_id,
...update,
save: async function () { return this; },
};
usersStore.push(newUser);
return newUser;
});
// Mock Session methods
jest.spyOn(Session, "create").mockImplementation(async (data) => {
const _id = new mongoose.Types.ObjectId().toString();
const newSession = {
_id,
revokedAt: null,
replacedBy: null,
lastUsedAt: new Date(),
...data,
save: async function () { return this; },
};
sessionsStore.push(newSession);
return newSession;
});
jest.spyOn(Session, "findOne").mockImplementation((query) => {
let found = null;
if (query.refreshTokenHash) {
found = sessionsStore.find((s) => s.refreshTokenHash === query.refreshTokenHash);
} else if (query._id) {
found = sessionsStore.find((s) => s._id.toString() === query._id.toString());
}
return {
populate: () => found || null,
then: (resolve) => resolve(found || null),
};
});
});
beforeEach(() => {
usersStore = [];
sessionsStore = [];
if (loggerInfoSpy) loggerInfoSpy.mockClear();
});
afterAll(() => {
jest.restoreAllMocks();
});
const getSentOtp = () => {
// Registration now also sends a verification email, so multiple [EMAIL LOG]
// entries exist. Pick the most recent one that actually carries an OTP span.
const otpLog = loggerInfoSpy.mock.calls
.map((call) => call[0])
.filter((msg) => typeof msg === "string" && msg.includes("[EMAIL LOG]"))
.reverse()
.find((msg) => /#166534;">(\d+)<\/span>/.test(msg));
const match = otpLog && otpLog.match(/#166534;">(\d+)<\/span>/);
return match ? match[1] : null;
};
it("should request password reset without exposing OTP in response body and include success: true", async () => {
await request(app).post("/api/auth/register").send(testUser);
const res = await request(app)
.post("/api/auth/request-password-reset")
.send({ email: testUser.email });
expect(res.statusCode).toBe(200);
expect(res.body.success).toBe(true);
expect(res.body.message).toContain("If an account exists");
expect(res.body).not.toHaveProperty("otp");
const sentOtp = getSentOtp();
expect(sentOtp).toBeDefined();
expect(typeof sentOtp).toBe("string");
// Verify resetTokenHash and resetTokenExpiry stored on user
const dbUser = usersStore.find((u) => u.email === testUser.email);
expect(dbUser.resetTokenHash).toBeDefined();
expect(dbUser.resetTokenExpiry).toBeDefined();
});
it("should return generic message when requesting reset for non-existent email (anti-enumeration)", async () => {
const res = await request(app)
.post("/api/auth/request-password-reset")
.send({ email: "nonexistent@example.com" });
expect(res.statusCode).toBe(200);
expect(res.body.success).toBe(true);
expect(res.body.message).toContain("If an account exists");
expect(res.body).not.toHaveProperty("otp");
});
it("should handle sendMail delivery failure by rolling back token fields and returning generic 200 (anti-enumeration)", async () => {
await request(app).post("/api/auth/register").send(testUser);
// Force the OTP email to fail: point SendLib at a closed local port so the
// connection is refused and sendOtpEmail throws.
process.env.SENDLIB_API_URL = "http://127.0.0.1:2525";
process.env.SENDLIB_API_KEY = "invalid_test_key";
try {
const res = await request(app)
.post("/api/auth/request-password-reset")
.send({ email: testUser.email });
expect(res.statusCode).toBe(200);
expect(res.body.success).toBe(true);
expect(res.body.message).toContain("If an account exists");
} finally {
delete process.env.SENDLIB_API_URL;
delete process.env.SENDLIB_API_KEY;
}
// Token fields should be rolled back to undefined so orphaned tokens aren't left active
const dbUser = usersStore.find((u) => u.email === testUser.email);
expect(dbUser.resetTokenHash).toBeUndefined();
expect(dbUser.resetTokenExpiry).toBeUndefined();
});
it("should reject password reset with wrong OTP and return success: false", async () => {
await request(app).post("/api/auth/register").send(testUser);
await request(app)
.post("/api/auth/request-password-reset")
.send({ email: testUser.email });
const res = await request(app)
.post("/api/auth/reset-password")
.send({
email: testUser.email,
otp: "000000",
newPassword: "newSecurePassword123",
});
expect(res.statusCode).toBe(400);
expect(res.body.success).toBe(false);
expect(res.body.message).toContain("Invalid or expired OTP");
});
it("should reject password reset with expired OTP", async () => {
await request(app).post("/api/auth/register").send(testUser);
await request(app)
.post("/api/auth/request-password-reset")
.send({ email: testUser.email });
const sentOtp = getSentOtp();
const dbUser = usersStore.find((u) => u.email === testUser.email);
// Artificially expire the token
dbUser.resetTokenExpiry = new Date(Date.now() - 1000);
const res = await request(app)
.post("/api/auth/reset-password")
.send({
email: testUser.email,
otp: sentOtp,
newPassword: "newSecurePassword123",
});
expect(res.statusCode).toBe(400);
expect(res.body.success).toBe(false);
expect(res.body.message).toContain("Invalid or expired OTP");
});
it("should successfully reset password with valid OTP and clear token (single use)", async () => {
await request(app).post("/api/auth/register").send(testUser);
await request(app)
.post("/api/auth/request-password-reset")
.send({ email: testUser.email });
const sentOtp = getSentOtp();
const newPassword = "newSecurePassword123";
// Successful reset
const res = await request(app)
.post("/api/auth/reset-password")
.send({
email: testUser.email,
otp: sentOtp,
newPassword,
});
expect(res.statusCode).toBe(200);
expect(res.body.success).toBe(true);
expect(res.body.message).toContain("Password reset successful");
// Token fields cleared from user
const dbUser = usersStore.find((u) => u.email === testUser.email);
expect(dbUser.resetTokenHash).toBeUndefined();
expect(dbUser.resetTokenExpiry).toBeUndefined();
// Verify bcrypt cost factor 12 was used
const passwordHash = dbUser.password;
expect(passwordHash.startsWith("$2b$12$") || passwordHash.startsWith("$2a$12$")).toBe(true);
// Verify user can now login with new password
const loginRes = await request(app)
.post("/api/auth/login")
.send({ email: testUser.email, password: newPassword });
expect(loginRes.statusCode).toBe(200);
expect(loginRes.body.success).toBe(true);
// Reused OTP attempt should be rejected
const reuseRes = await request(app)
.post("/api/auth/reset-password")
.send({
email: testUser.email,
otp: sentOtp,
newPassword: "anotherPassword123",
});
expect(reuseRes.statusCode).toBe(400);
expect(reuseRes.body.success).toBe(false);
expect(reuseRes.body.message).toContain("Invalid or expired OTP");
});
});