|
| 1 | +import type { NextRequest } from "next/server"; |
| 2 | +import { beforeEach, describe, expect, it, vi } from "vitest"; |
| 3 | + |
| 4 | +const { mockGetToken } = vi.hoisted(() => ({ |
| 5 | + mockGetToken: vi.fn(), |
| 6 | +})); |
| 7 | + |
| 8 | +vi.mock("next-auth/jwt", () => ({ getToken: mockGetToken })); |
| 9 | +vi.mock("~/env", () => ({ env: { AUTH_SECRET: "test-secret" } })); |
| 10 | + |
| 11 | +import { middleware } from "~/middleware"; |
| 12 | + |
| 13 | +function makeRequest(pathname = "/admin"): NextRequest { |
| 14 | + const url = `http://localhost${pathname}`; |
| 15 | + return { |
| 16 | + url, |
| 17 | + nextUrl: { pathname }, |
| 18 | + } as unknown as NextRequest; |
| 19 | +} |
| 20 | + |
| 21 | +describe("admin middleware", () => { |
| 22 | + beforeEach(() => { |
| 23 | + mockGetToken.mockReset(); |
| 24 | + }); |
| 25 | + |
| 26 | + it("redirects to /login with callbackUrl when there is no token", async () => { |
| 27 | + mockGetToken.mockResolvedValue(null); |
| 28 | + const res = await middleware(makeRequest("/admin/users")); |
| 29 | + expect(res.headers.get("location")).toBe( |
| 30 | + "http://localhost/login?callbackUrl=%2Fadmin%2Fusers", |
| 31 | + ); |
| 32 | + }); |
| 33 | + |
| 34 | + it("forces re-login when the token has no isAdmin field (pre-PR token)", async () => { |
| 35 | + mockGetToken.mockResolvedValue({ id: "u1" }); |
| 36 | + const res = await middleware(makeRequest("/admin")); |
| 37 | + expect(res.headers.get("location")).toBe( |
| 38 | + "http://localhost/login?callbackUrl=%2Fadmin", |
| 39 | + ); |
| 40 | + }); |
| 41 | + |
| 42 | + it("redirects non-admin users to /mon-espace", async () => { |
| 43 | + mockGetToken.mockResolvedValue({ id: "u1", isAdmin: false }); |
| 44 | + const res = await middleware(makeRequest("/admin")); |
| 45 | + expect(res.headers.get("location")).toBe("http://localhost/mon-espace"); |
| 46 | + }); |
| 47 | + |
| 48 | + it("lets admin users through", async () => { |
| 49 | + mockGetToken.mockResolvedValue({ id: "u1", isAdmin: true }); |
| 50 | + const res = await middleware(makeRequest("/admin")); |
| 51 | + // NextResponse.next() does not set a redirect location |
| 52 | + expect(res.headers.get("location")).toBeNull(); |
| 53 | + }); |
| 54 | +}); |
0 commit comments