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
|
import { describe, test, expect, vi } from "vitest";
import { Request, Response, NextFunction } from "express";
import { authParent } from "../src/middleware/auth";
import { verifyJwt } from "../src/account/jwt";
vi.mock("../src/account/jwt", () => ({
verifyJwt: vi.fn(),
}));
describe("Auth Middleware", () => {
test("should authenticate valid parent token", async () => {
vi.mocked(verifyJwt).mockResolvedValueOnce({
id: 1,
type: "parent" as const,
});
const req = {
headers: {
authorization: "Bearer valid-token",
},
} as Request;
const res = {
status: vi.fn().mockReturnThis(),
json: vi.fn(),
} as unknown as Response;
const next = vi.fn() as NextFunction;
await authParent(req, res, next);
expect(req.user).toEqual({
id: 1,
type: "parent",
});
expect(next).toHaveBeenCalled();
expect(res.status).not.toHaveBeenCalled();
});
test("should reject missing authorization header", async () => {
const req = {
headers: {},
path: "/test",
} as Request;
const res = {
status: vi.fn().mockReturnThis(),
json: vi.fn(),
} as unknown as Response;
const next = vi.fn() as NextFunction;
await authParent(req, res, next);
expect(res.status).toHaveBeenCalledWith(401);
expect(res.json).toHaveBeenCalledWith({
success: false,
reason: "Missing or invalid authorization header",
});
expect(next).not.toHaveBeenCalled();
});
test("should reject invalid token format", async () => {
const req = {
headers: {
authorization: "InvalidFormat token",
},
path: "/test",
} as Request;
const res = {
status: vi.fn().mockReturnThis(),
json: vi.fn(),
} as unknown as Response;
const next = vi.fn() as NextFunction;
await authParent(req, res, next);
expect(res.status).toHaveBeenCalledWith(401);
expect(res.json).toHaveBeenCalledWith({
success: false,
reason: "Missing or invalid authorization header",
});
expect(next).not.toHaveBeenCalled();
});
test("should reject invalid JWT", async () => {
vi.mocked(verifyJwt).mockRejectedValueOnce(new Error("Invalid token"));
const req = {
headers: {
authorization: "Bearer invalid-token",
},
path: "/test",
} as Request;
const res = {
status: vi.fn().mockReturnThis(),
json: vi.fn(),
} as unknown as Response;
const next = vi.fn() as NextFunction;
await authParent(req, res, next);
expect(res.status).toHaveBeenCalledWith(401);
expect(res.json).toHaveBeenCalledWith({
success: false,
reason: "Invalid or expired token",
});
expect(next).not.toHaveBeenCalled();
});
});
|