route.test.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. /* @vitest-environment node */
  2. import { describe, it, expect, vi, beforeEach } from "vitest";
  3. vi.mock("@/lib/auth/session", () => ({
  4. getSession: vi.fn(),
  5. createSession: vi.fn(),
  6. }));
  7. vi.mock("@/lib/db", () => ({
  8. getDb: vi.fn(),
  9. }));
  10. vi.mock("@/models/user", () => ({
  11. default: {
  12. findById: vi.fn(),
  13. },
  14. }));
  15. vi.mock("bcryptjs", () => {
  16. const compare = vi.fn();
  17. const hash = vi.fn();
  18. return {
  19. default: { compare, hash },
  20. compare,
  21. hash,
  22. };
  23. });
  24. import { getSession, createSession } from "@/lib/auth/session";
  25. import { getDb } from "@/lib/db";
  26. import User from "@/models/user";
  27. import { compare as bcryptCompare, hash as bcryptHash } from "bcryptjs";
  28. import { POST, dynamic } from "./route.js";
  29. function createRequestStub(body) {
  30. return {
  31. async json() {
  32. return body;
  33. },
  34. };
  35. }
  36. describe("POST /api/auth/change-password", () => {
  37. beforeEach(() => {
  38. vi.clearAllMocks();
  39. getDb.mockResolvedValue({});
  40. });
  41. it('exports dynamic="force-dynamic"', () => {
  42. expect(dynamic).toBe("force-dynamic");
  43. });
  44. it("returns 401 when unauthenticated", async () => {
  45. getSession.mockResolvedValue(null);
  46. const res = await POST(createRequestStub({}));
  47. expect(res.status).toBe(401);
  48. expect(await res.json()).toEqual({
  49. error: { message: "Unauthorized", code: "AUTH_UNAUTHENTICATED" },
  50. });
  51. });
  52. it("returns 400 when JSON parsing fails", async () => {
  53. getSession.mockResolvedValue({
  54. userId: "u1",
  55. role: "branch",
  56. branchId: "NL01",
  57. });
  58. const req = {
  59. json: vi.fn().mockRejectedValue(new Error("invalid json")),
  60. };
  61. const res = await POST(req);
  62. expect(res.status).toBe(400);
  63. expect(await res.json()).toEqual({
  64. error: {
  65. message: "Invalid request body",
  66. code: "VALIDATION_INVALID_JSON",
  67. },
  68. });
  69. });
  70. it("returns 400 when body is not an object", async () => {
  71. getSession.mockResolvedValue({
  72. userId: "u1",
  73. role: "branch",
  74. branchId: "NL01",
  75. });
  76. const res = await POST(createRequestStub("nope"));
  77. expect(res.status).toBe(400);
  78. expect(await res.json()).toEqual({
  79. error: {
  80. message: "Invalid request body",
  81. code: "VALIDATION_INVALID_BODY",
  82. },
  83. });
  84. });
  85. it("returns 400 when fields are missing", async () => {
  86. getSession.mockResolvedValue({
  87. userId: "u1",
  88. role: "branch",
  89. branchId: "NL01",
  90. });
  91. const res = await POST(createRequestStub({ currentPassword: "x" }));
  92. expect(res.status).toBe(400);
  93. expect(await res.json()).toEqual({
  94. error: {
  95. message: "Missing currentPassword or newPassword",
  96. code: "VALIDATION_MISSING_FIELD",
  97. details: { fields: ["newPassword"] },
  98. },
  99. });
  100. expect(User.findById).not.toHaveBeenCalled();
  101. });
  102. it("returns 401 when user is not found (treat as invalid session)", async () => {
  103. getSession.mockResolvedValue({
  104. userId: "u1",
  105. role: "branch",
  106. branchId: "NL01",
  107. });
  108. User.findById.mockReturnValue({
  109. exec: vi.fn().mockResolvedValue(null),
  110. });
  111. const res = await POST(
  112. createRequestStub({
  113. currentPassword: "OldPassword123",
  114. newPassword: "StrongPassword123",
  115. }),
  116. );
  117. expect(res.status).toBe(401);
  118. expect(await res.json()).toEqual({
  119. error: { message: "Unauthorized", code: "AUTH_UNAUTHENTICATED" },
  120. });
  121. });
  122. it("returns 401 when current password is wrong", async () => {
  123. getSession.mockResolvedValue({
  124. userId: "u1",
  125. role: "branch",
  126. branchId: "NL01",
  127. });
  128. const user = {
  129. _id: "507f1f77bcf86cd799439011",
  130. passwordHash: "hash",
  131. mustChangePassword: true,
  132. passwordResetToken: "tok",
  133. passwordResetExpiresAt: new Date(),
  134. save: vi.fn().mockResolvedValue(true),
  135. };
  136. User.findById.mockReturnValue({
  137. exec: vi.fn().mockResolvedValue(user),
  138. });
  139. bcryptCompare.mockResolvedValue(false);
  140. const res = await POST(
  141. createRequestStub({
  142. currentPassword: "wrong",
  143. newPassword: "StrongPassword123",
  144. }),
  145. );
  146. expect(res.status).toBe(401);
  147. expect(await res.json()).toEqual({
  148. error: {
  149. message: "Invalid credentials",
  150. code: "AUTH_INVALID_CREDENTIALS",
  151. },
  152. });
  153. expect(bcryptHash).not.toHaveBeenCalled();
  154. expect(user.save).not.toHaveBeenCalled();
  155. expect(createSession).not.toHaveBeenCalled();
  156. });
  157. it("returns 400 when new password is weak", async () => {
  158. getSession.mockResolvedValue({
  159. userId: "u1",
  160. role: "branch",
  161. branchId: "NL01",
  162. });
  163. const user = {
  164. _id: "507f1f77bcf86cd799439011",
  165. passwordHash: "hash",
  166. mustChangePassword: true,
  167. passwordResetToken: "tok",
  168. passwordResetExpiresAt: new Date(),
  169. save: vi.fn().mockResolvedValue(true),
  170. };
  171. User.findById.mockReturnValue({
  172. exec: vi.fn().mockResolvedValue(user),
  173. });
  174. bcryptCompare.mockResolvedValue(true);
  175. const res = await POST(
  176. createRequestStub({
  177. currentPassword: "OldPassword123",
  178. newPassword: "short",
  179. }),
  180. );
  181. expect(res.status).toBe(400);
  182. const body = await res.json();
  183. expect(body.error.code).toBe("VALIDATION_WEAK_PASSWORD");
  184. expect(body.error.details).toMatchObject({
  185. minLength: 8,
  186. requireLetter: true,
  187. requireNumber: true,
  188. });
  189. expect(Array.isArray(body.error.details.reasons)).toBe(true);
  190. expect(bcryptHash).not.toHaveBeenCalled();
  191. expect(user.save).not.toHaveBeenCalled();
  192. expect(createSession).not.toHaveBeenCalled();
  193. });
  194. it("returns 200 and updates passwordHash + clears flags on success", async () => {
  195. getSession.mockResolvedValue({
  196. userId: "u1",
  197. role: "branch",
  198. branchId: "NL01",
  199. email: "branch@example.com",
  200. });
  201. const user = {
  202. _id: "507f1f77bcf86cd799439011",
  203. passwordHash: "old-hash",
  204. role: "branch",
  205. branchId: "NL01",
  206. email: "branch@example.com",
  207. mustChangePassword: true,
  208. passwordResetToken: "tok",
  209. passwordResetExpiresAt: new Date("2030-01-01"),
  210. save: vi.fn().mockResolvedValue(true),
  211. };
  212. User.findById.mockReturnValue({
  213. exec: vi.fn().mockResolvedValue(user),
  214. });
  215. bcryptCompare.mockResolvedValue(true);
  216. bcryptHash.mockResolvedValue("new-hash");
  217. const res = await POST(
  218. createRequestStub({
  219. currentPassword: "OldPassword123",
  220. newPassword: "StrongPassword123",
  221. }),
  222. );
  223. expect(res.status).toBe(200);
  224. expect(await res.json()).toEqual({ ok: true });
  225. expect(bcryptHash).toHaveBeenCalledWith("StrongPassword123", 12);
  226. expect(user.passwordHash).toBe("new-hash");
  227. expect(user.mustChangePassword).toBe(false);
  228. expect(user.passwordResetToken).toBe(null);
  229. expect(user.passwordResetExpiresAt).toBe(null);
  230. expect(user.save).toHaveBeenCalledTimes(1);
  231. expect(createSession).toHaveBeenCalledWith({
  232. userId: "507f1f77bcf86cd799439011",
  233. role: "branch",
  234. branchId: "NL01",
  235. email: "branch@example.com",
  236. mustChangePassword: false,
  237. });
  238. });
  239. });