feat(db+auth): add pg pool, admin_users email/provider migration, refactor auth lookup

- Create src/lib/db.ts (shared pg.Pool, query/withTx helpers, server-only)
- Add @types/pg devDep
- Migration 204: add email, auth_provider, auth_subject columns to
  admin_users; backfill from auth.users; new upsert_admin_user accepts
  multi-provider args; new get_admin_user_for_session RPC resolves
  Auth.js session id (UUID or Google sub) to an admin row
- Refactor getAdminUser() to use pg + new RPC; auto-provisions on first
  Google sign-in using session.user.email
- Refactor updatePasswordAction to call update_user_password via pg
  (drops the Supabase REST hop)
- Delete orphaned src/actions/login.ts (replaced by auth-actions.ts)
- Drop remaining DEV_FORCE_UID references in users.ts; dev path now
  uses dev_session cookie (the only cookie the dev flow can set)
- Update AdminUser type: user_id is now string | null (Google users
  have no Supabase auth id); add email + auth_provider fields
- Fix downstream type errors: StopProductAssignment.callerUid accepts
  null; pickup.ts performedBy widens to string | null
- Bump vitest config, tests/, and other earlier cleanup changes
This commit is contained in:
2026-06-06 23:41:41 +00:00
parent 9374e63ae6
commit f96dcd01f2
53 changed files with 1837 additions and 1656 deletions
+123
View File
@@ -0,0 +1,123 @@
import { test, expect, request } from "@playwright/test";
const BASE = process.env.PLAYWRIGHT_URL ?? "http://localhost:3000";
// ─────────────────────────────────────────────────────────────────────
// Auth.js v5 API endpoints
// ─────────────────────────────────────────────────────────────────────
test.describe("Auth.js v5 endpoints", () => {
test("/api/auth/providers returns the configured providers", async () => {
const ctx = await request.newContext({ baseURL: BASE });
const res = await ctx.get("/api/auth/providers");
expect(res.status()).toBe(200);
const providers = (await res.json()) as Record<string, unknown>;
// The Credentials provider is always present. The Google provider is
// only present when AUTH_GOOGLE_ID + AUTH_GOOGLE_SECRET are set.
expect(providers).toHaveProperty("supabase-password");
if (process.env.AUTH_GOOGLE_ID && process.env.AUTH_GOOGLE_SECRET) {
expect(providers).toHaveProperty("google");
}
await ctx.dispose();
});
test("/api/auth/csrf returns a valid CSRF token", async () => {
const ctx = await request.newContext({ baseURL: BASE });
const res = await ctx.get("/api/auth/csrf");
expect(res.status()).toBe(200);
const body = (await res.json()) as { csrfToken?: string };
expect(typeof body.csrfToken).toBe("string");
expect(body.csrfToken!.length).toBeGreaterThan(20);
await ctx.dispose();
});
test("/api/auth/session returns null when there is no session", async () => {
const ctx = await request.newContext({ baseURL: BASE });
const res = await ctx.get("/api/auth/session");
expect(res.status()).toBe(200);
const body = await res.json();
// Auth.js returns `null` (not `{}`) when no session is active.
expect(body).toBeNull();
await ctx.dispose();
});
});
// ─────────────────────────────────────────────────────────────────────
// Middleware — protected route gating
// ─────────────────────────────────────────────────────────────────────
test.describe("Middleware — protected route gating", () => {
test("unauthed /login renders the login form (200)", async ({ page }) => {
const res = await page.goto(`${BASE}/login`);
expect(res?.status()).toBe(200);
// The login form has an aria-label of "Sign in form"
await expect(page.getByRole("form", { name: /sign in form/i })).toBeVisible();
});
test("dev_session=platform_admin lets /admin render (200)", async ({ page, context }) => {
await context.addCookies([
{ name: "dev_session", value: "platform_admin", domain: "localhost", path: "/" },
]);
const res = await page.goto(`${BASE}/admin`);
expect(res?.status()).toBe(200);
await expect(page).toHaveURL(/\/admin/);
// The admin layout renders a sidebar (aside element)
await expect(page.locator("aside").first()).toBeVisible({ timeout: 5_000 });
});
test("authed user hitting /login is redirected to /admin", async ({ page, context }) => {
await context.addCookies([
{ name: "dev_session", value: "platform_admin", domain: "localhost", path: "/" },
]);
await page.goto(`${BASE}/login`);
// Middleware redirects authed users from /login to /admin
await page.waitForURL(/\/admin/, { timeout: 5_000 });
});
});
// ─────────────────────────────────────────────────────────────────────
// Admin pages — load cleanly with dev_session
// ─────────────────────────────────────────────────────────────────────
test.describe("Admin pages — load with dev_session", () => {
test.beforeEach(async ({ context }) => {
await context.addCookies([
{ name: "dev_session", value: "platform_admin", domain: "localhost", path: "/" },
]);
});
for (const path of ["/admin", "/admin/products", "/admin/orders", "/admin/settings"]) {
test(`${path} renders without crashing`, async ({ page }) => {
const res = await page.goto(`${BASE}${path}`);
expect(res?.status()).toBe(200);
await expect(page.locator("body")).toBeVisible();
// The admin layout renders the sidebar; this confirms the auth
// gate didn't bounce us back to /login.
await expect(page.locator("aside").first()).toBeVisible({ timeout: 8_000 });
await expect(page.locator("body")).not.toContainText("Access Denied");
});
}
});
// ─────────────────────────────────────────────────────────────────────
// Logout flow
// ─────────────────────────────────────────────────────────────────────
test.describe("Logout", () => {
test("/logout clears the dev_session cookie and redirects to /login", async ({ page, context }) => {
await context.addCookies([
{ name: "dev_session", value: "platform_admin", domain: "localhost", path: "/" },
]);
// /logout is a server component that calls signOut and redirects.
await page.goto(`${BASE}/logout`);
// The Auth.js signOut flow sets a callback URL in the URL, or the
// custom /logout page redirects to /login directly. Either way we
// should land on /login (or near it).
await page.waitForURL(/\/login/, { timeout: 8_000 });
// The dev_session cookie should be cleared (or Auth.js session
// cookie cleared). At minimum, navigating to /admin again should
// require re-auth — we can verify by hitting /admin and checking
// that we don't have a 200 with the sidebar (the dev session may
// be re-issued by the demo flow middleware, so we don't assert
// strict denial here; just that logout *did* go to /login).
});
});
+100 -62
View File
@@ -1,79 +1,117 @@
import { test, expect } from "@playwright/test";
// ─────────────────────────────────────────────────────────────
// Login flow: credentials → /api/login JSON → redirect to /admin
// ─────────────────────────────────────────────────────────────
test("login with valid credentials redirects to /admin and shows admin dashboard", async ({
page,
}) => {
// Navigate to login page
await page.goto("/login");
const BASE = process.env.PLAYWRIGHT_URL ?? "http://localhost:3000";
// Fill credentials
await page.fill("#email", process.env.TEST_ADMIN_EMAIL!);
await page.fill("#password", process.env.TEST_ADMIN_PASSWORD!);
// ─────────────────────────────────────────────────────────────────────
// Login form renders the right affordances
// ─────────────────────────────────────────────────────────────────────
test.describe("Login form rendering", () => {
test("renders Google button, email + password fields, and Sign in button", async ({ page }) => {
await page.goto(`${BASE}/login`);
// Submit form
await page.click('button[type="submit"]');
// The Google button is the primary CTA at the top of the form.
await expect(page.getByRole("button", { name: /continue with google/i })).toBeVisible();
// Wait for navigation to /admin — the JSON response + client nav must happen
await page.waitForURL("**/admin", { timeout: 10000 });
// Email + password inputs
await expect(page.locator("#email")).toBeVisible();
await expect(page.locator("#password")).toBeVisible();
// Admin dashboard must be rendered (Control Center heading or admin layout)
await expect(page.locator("body")).not.toContainText("Access Denied");
await expect(page.locator("body")).not.toContainText("Login failed");
// The "Sign in" submit button is on the email/password form (not on the
// Google one). Use the form's aria-label to scope the lookup.
const signInForm = page.getByRole("form", { name: /sign in form/i });
await expect(signInForm.getByRole("button", { name: /^sign in$/i })).toBeVisible();
});
test("missing email surfaces browser required validation", async ({ page }) => {
await page.goto(`${BASE}/login`);
await page.locator("#password").fill("something");
// Don't fill email
const signInForm = page.getByRole("form", { name: /sign in form/i });
await signInForm.getByRole("button", { name: /^sign in$/i }).click();
// The email input has `required` — the browser should block submission
// and the email field remains focused. We don't assert on URL change.
await expect(page.locator("#email")).toHaveAttribute("required", "");
});
});
// ─────────────────────────────────────────────────────────────
// Login failure: bad password shows error, stays on /login
// ─────────────────────────────────────────────────────────────
test("login with wrong password shows error and stays on /login", async ({
page,
}) => {
await page.goto("/login");
// ─────────────────────────────────────────────────────────────────────
// Demo mode (?demo=1) — the path that works without a Supabase backend
// ─────────────────────────────────────────────────────────────────────
test.describe("Demo mode (?demo=1)", () => {
test("Platform Admin button sets dev_session and lands on /admin", async ({ page, context }) => {
await page.goto(`${BASE}/login?demo=1`);
await page.getByRole("button", { name: /platform admin/i }).click();
await page.fill("#email", process.env.TEST_ADMIN_EMAIL!);
await page.fill("#password", "wrongpassword123!");
// The click sets the cookie client-side and navigates. We should land
// on the admin dashboard.
await page.waitForURL(/\/admin/, { timeout: 10_000 });
const cookies = await context.cookies();
expect(cookies.find((c) => c.name === "dev_session")?.value).toBe("platform_admin");
});
await page.click('button[type="submit"]');
test("Brand Admin button sets dev_session=brand_admin", async ({ page, context }) => {
await page.goto(`${BASE}/login?demo=1`);
await page.getByRole("button", { name: /brand admin/i }).click();
await page.waitForURL(/\/admin/, { timeout: 10_000 });
const cookies = await context.cookies();
expect(cookies.find((c) => c.name === "dev_session")?.value).toBe("brand_admin");
});
// Error message should appear
await expect(page.locator('[role="alert"]')).toBeVisible({ timeout: 5000 });
// Should NOT navigate away from login
await expect(page).toHaveURL(/\/login/);
test("Store Employee button sets dev_session=store_employee", async ({ page, context }) => {
await page.goto(`${BASE}/login?demo=1`);
await page.getByRole("button", { name: /store employee/i }).click();
await page.waitForURL(/\/admin/, { timeout: 10_000 });
const cookies = await context.cookies();
expect(cookies.find((c) => c.name === "dev_session")?.value).toBe("store_employee");
});
});
// ─────────────────────────────────────────────────────────────
// Login with missing fields shows validation error
// ─────────────────────────────────────────────────────────────
test("login with missing email shows validation error", async ({ page }) => {
await page.goto("/login");
// ─────────────────────────────────────────────────────────────────────
// Credentials sign-in (skipped if env vars aren't set — needs a real
// Supabase auth user to actually succeed)
// ─────────────────────────────────────────────────────────────────────
test.describe("Credentials sign-in", () => {
test.skip(
!process.env.TEST_ADMIN_EMAIL || !process.env.TEST_ADMIN_PASSWORD,
"Set TEST_ADMIN_EMAIL and TEST_ADMIN_PASSWORD to run the credentials flow against a real Supabase backend.",
);
// Don't fill email, only password
await page.fill("#password", "something");
test("valid credentials redirect to /admin", async ({ page }) => {
await page.goto(`${BASE}/login`);
await page.locator("#email").fill(process.env.TEST_ADMIN_EMAIL!);
await page.locator("#password").fill(process.env.TEST_ADMIN_PASSWORD!);
await page.click('button[type="submit"]');
const signInForm = page.getByRole("form", { name: /sign in form/i });
await signInForm.getByRole("button", { name: /^sign in$/i }).click();
// Browser validation should fire (email required)
await expect(page.locator("#email")).toHaveAttribute("required", "");
});
// ─────────────────────────────────────────────────────────────
// Session persistence: after login, navigating to /admin
// should load without re-authenticating
// ─────────────────────────────────────────────────────────────
test("admin session persists across page reloads", async ({ page }) => {
// Login first
await page.goto("/login");
await page.fill("#email", process.env.TEST_ADMIN_EMAIL!);
await page.fill("#password", process.env.TEST_ADMIN_PASSWORD!);
await page.click('button[type="submit"]');
await page.waitForURL("**/admin", { timeout: 10000 });
// Reload the page
await page.reload();
// Should still be on /admin (session cookie keeps user logged in)
await expect(page).toHaveURL(/\/admin/);
await expect(page.locator("body")).not.toContainText("Access Denied");
await page.waitForURL(/\/admin/, { timeout: 15_000 });
await expect(page.locator("body")).not.toContainText("Access Denied");
});
test("wrong password shows an error and stays on /login", async ({ page }) => {
await page.goto(`${BASE}/login`);
await page.locator("#email").fill(process.env.TEST_ADMIN_EMAIL!);
await page.locator("#password").fill("definitely-wrong-password");
const signInForm = page.getByRole("form", { name: /sign in form/i });
await signInForm.getByRole("button", { name: /^sign in$/i }).click();
// The error banner uses role="alert"
await expect(page.locator('[role="alert"]')).toBeVisible({ timeout: 8_000 });
await expect(page).toHaveURL(/\/login/);
});
test("session persists across reload", async ({ page }) => {
await page.goto(`${BASE}/login`);
await page.locator("#email").fill(process.env.TEST_ADMIN_EMAIL!);
await page.locator("#password").fill(process.env.TEST_ADMIN_PASSWORD!);
const signInForm = page.getByRole("form", { name: /sign in form/i });
await signInForm.getByRole("button", { name: /^sign in$/i }).click();
await page.waitForURL(/\/admin/, { timeout: 15_000 });
await page.reload();
await expect(page).toHaveURL(/\/admin/);
await expect(page.locator("body")).not.toContainText("Access Denied");
});
});
+107
View File
@@ -0,0 +1,107 @@
/**
* Unit tests for the auth server actions in src/actions/auth-actions.ts.
*
* Mocks `@/lib/auth` and `next-auth` to test the action wrappers in
* isolation from the network and the Auth.js runtime.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
const signInMock = vi.fn();
const signOutMock = vi.fn();
vi.mock("@/lib/auth", () => ({
signIn: signInMock,
signOut: signOutMock,
}));
const authErrors: Array<{ name: string; message?: string }> = [];
vi.mock("next-auth", () => ({
AuthError: class AuthError extends Error {
override name = "AuthError";
constructor(message?: string) {
super(message);
authErrors.push({ name: this.name, message });
}
},
}));
// Import after mocks.
const { signInWithPassword, signInWithGoogle, signOutAction } = await import(
"@/actions/auth-actions"
);
beforeEach(() => {
signInMock.mockReset();
signOutMock.mockReset();
});
describe("signInWithPassword", () => {
it("returns ok:false when email is missing", async () => {
const fd = new FormData();
fd.set("password", "x");
const result = await signInWithPassword(null, fd);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toMatch(/email/i);
expect(signInMock).not.toHaveBeenCalled();
});
it("returns ok:false when password is missing", async () => {
const fd = new FormData();
fd.set("email", "a@b.com");
const result = await signInWithPassword(null, fd);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toMatch(/password/i);
expect(signInMock).not.toHaveBeenCalled();
});
it("trims email and passes credentials to signIn", async () => {
signInMock.mockResolvedValue(undefined);
const fd = new FormData();
fd.set("email", " admin@brand.test ");
fd.set("password", "secret");
const result = await signInWithPassword(null, fd);
expect(result).toEqual({ ok: true });
expect(signInMock).toHaveBeenCalledWith("supabase-password", {
email: "admin@brand.test",
password: "secret",
redirect: false,
});
});
it("returns ok:false with a friendly message on AuthError", async () => {
signInMock.mockRejectedValue(new Error("auth failed")); // not an AuthError
const fd = new FormData();
fd.set("email", "a@b.com");
fd.set("password", "wrong");
await expect(signInWithPassword(null, fd)).rejects.toThrow("auth failed");
});
it("catches AuthError and returns ok:false", async () => {
// The mocked AuthError is registered as a real class via the mock
// factory above, so we can construct one here.
const { AuthError } = await import("next-auth");
signInMock.mockRejectedValue(new AuthError("invalid credentials"));
const fd = new FormData();
fd.set("email", "a@b.com");
fd.set("password", "wrong");
const result = await signInWithPassword(null, fd);
expect(result).toEqual({ ok: false, error: "Invalid email or password." });
});
});
describe("signInWithGoogle", () => {
it("calls signIn with the google provider and /admin redirect", async () => {
signInMock.mockResolvedValue(undefined);
await signInWithGoogle();
expect(signInMock).toHaveBeenCalledWith("google", { redirectTo: "/admin" });
});
});
describe("signOutAction", () => {
it("calls signOut with the login redirect", async () => {
signOutMock.mockResolvedValue(undefined);
await signOutAction();
expect(signOutMock).toHaveBeenCalledWith({ redirectTo: "/login" });
});
});
+338
View File
@@ -0,0 +1,338 @@
/**
* @vitest-environment node
*
* Unit tests for `getAdminUser()` in src/lib/admin-permissions.ts.
*
* Exercises the three auth sources and the two lookup paths:
* - dev_session cookie → buildDevAdmin shim
* - NEXT_PUBLIC_USE_MOCK_DATA → buildDevAdmin shim
* - Auth.js session → REST RPC (preferred) or REST query (fallback)
* + upsert_admin_user auto-provisioning for first-time sign-ins.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
// ── Module mocks ────────────────────────────────────────────────────
//
// vi.mock is hoisted, so all factory bodies must avoid closure over
// outer-scope imports. The actual implementations are stubbed and
// re-configured in `beforeEach`.
const cookiesMock = vi.fn();
vi.mock("next/headers", () => ({ cookies: cookiesMock }));
const authMock = vi.fn();
vi.mock("@/lib/auth", () => ({ auth: authMock }));
// `server-only` is a runtime guard that throws if imported outside a
// server context. Vitest is a Node env, so the guard fires and breaks
// the test setup — stub it.
vi.mock("server-only", () => ({}));
// Import AFTER the mocks.
const { getAdminUser, buildDevAdmin } = await import("@/lib/admin-permissions");
// ── Test helpers ───────────────────────────────────────────────────
const UUID = "00000000-0000-0000-0000-000000000001";
const NON_UUID = "google-sub-1234567890";
function mockCookies(value: string | undefined) {
cookiesMock.mockResolvedValue({
get: (name: string) =>
name === "dev_session" && value ? { name, value } : undefined,
});
}
function mockAuthSession(session: { user?: { id?: string; email?: string } } | null) {
authMock.mockResolvedValue(session);
}
function jsonResponse(body: unknown, init: ResponseInit = {}) {
return new Response(JSON.stringify(body), {
status: 200,
headers: { "content-type": "application/json" },
...init,
});
}
function adminRow(overrides: Record<string, unknown> = {}) {
return {
id: "row-1",
user_id: UUID,
brand_id: null,
role: "platform_admin",
active: true,
must_change_password: false,
...overrides,
};
}
// ── Tests ──────────────────────────────────────────────────────────
describe("getAdminUser — dev_session bypass", () => {
beforeEach(() => {
cookiesMock.mockReset();
authMock.mockReset();
vi.stubGlobal("fetch", vi.fn());
});
afterEach(() => {
vi.unstubAllGlobals();
});
it("returns platform_admin shim for dev_session=platform_admin", async () => {
mockCookies("platform_admin");
const u = await getAdminUser();
expect(u).not.toBeNull();
expect(u?.role).toBe("platform_admin");
expect(u?.can_manage_users).toBe(true);
expect(authMock).not.toHaveBeenCalled();
});
it("returns brand_admin shim for dev_session=brand_admin", async () => {
mockCookies("brand_admin");
const u = await getAdminUser();
expect(u?.role).toBe("brand_admin");
expect(u?.can_manage_users).toBe(true);
});
it("returns store_employee shim for dev_session=store_employee", async () => {
mockCookies("store_employee");
const u = await getAdminUser();
expect(u?.role).toBe("store_employee");
expect(u?.can_manage_users).toBe(false);
expect(u?.can_manage_orders).toBe(true);
expect(u?.can_manage_pickup).toBe(true);
});
it("falls through to auth() for an unrecognized dev_session value", async () => {
mockCookies("hacker");
mockAuthSession(null);
const u = await getAdminUser();
expect(u).toBeNull();
expect(authMock).toHaveBeenCalledTimes(1);
});
});
describe("getAdminUser — mock data mode", () => {
beforeEach(() => {
cookiesMock.mockReset();
authMock.mockReset();
vi.stubGlobal("fetch", vi.fn());
});
afterEach(() => {
vi.unstubAllGlobals();
delete process.env.NEXT_PUBLIC_USE_MOCK_DATA;
});
it("returns platform_admin shim when NEXT_PUBLIC_USE_MOCK_DATA=true", async () => {
process.env.NEXT_PUBLIC_USE_MOCK_DATA = "true";
mockCookies(undefined);
const u = await getAdminUser();
expect(u?.role).toBe("platform_admin");
expect(authMock).not.toHaveBeenCalled();
});
});
describe("getAdminUser — Auth.js v5 session", () => {
const SUPABASE_URL = "https://example.supabase.co";
const SERVICE_KEY = "service-role-key";
beforeEach(() => {
cookiesMock.mockReset();
authMock.mockReset();
process.env.NEXT_PUBLIC_SUPABASE_URL = SUPABASE_URL;
process.env.SUPABASE_SERVICE_ROLE_KEY = SERVICE_KEY;
delete process.env.NEXT_PUBLIC_USE_MOCK_DATA;
});
afterEach(() => {
vi.unstubAllGlobals();
delete process.env.NEXT_PUBLIC_SUPABASE_URL;
delete process.env.SUPABASE_SERVICE_ROLE_KEY;
});
it("returns null when auth() returns no session", async () => {
mockCookies(undefined);
mockAuthSession(null);
const u = await getAdminUser();
expect(u).toBeNull();
});
it("returns null when env vars are missing", async () => {
mockCookies(undefined);
mockAuthSession({ user: { id: UUID, email: "a@b.com" } });
delete process.env.NEXT_PUBLIC_SUPABASE_URL;
delete process.env.SUPABASE_SERVICE_ROLE_KEY;
const u = await getAdminUser();
expect(u).toBeNull();
});
it("calls the new get_admin_user_for_session RPC first and returns the row", async () => {
mockCookies(undefined);
mockAuthSession({ user: { id: UUID, email: "admin@brand.test" } });
const fetchMock = vi.fn()
.mockResolvedValueOnce(jsonResponse(adminRow()));
vi.stubGlobal("fetch", fetchMock);
const u = await getAdminUser();
expect(u?.role).toBe("platform_admin");
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0][0]).toBe(
`${SUPABASE_URL}/rest/v1/rpc/get_admin_user_for_session`,
);
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
p_session_id: UUID,
});
});
it("falls back to the legacy user_id REST query when the RPC is missing (404)", async () => {
mockCookies(undefined);
mockAuthSession({ user: { id: UUID, email: "admin@brand.test" } });
const fetchMock = vi.fn()
// RPC returns 404 (migration 204 not applied yet)
.mockResolvedValueOnce(new Response("not found", { status: 404 }))
// Legacy query succeeds
.mockResolvedValueOnce(jsonResponse([adminRow()]));
vi.stubGlobal("fetch", fetchMock);
const u = await getAdminUser();
expect(u?.role).toBe("platform_admin");
expect(fetchMock).toHaveBeenCalledTimes(2);
const secondUrl = fetchMock.mock.calls[1][0] as string;
expect(secondUrl).toContain("/rest/v1/admin_users?");
expect(secondUrl).toContain(`user_id=eq.${UUID}`);
});
it("falls back to the email REST query for a non-UUID Google subject when the RPC is missing", async () => {
mockCookies(undefined);
mockAuthSession({ user: { id: NON_UUID, email: "Admin@Brand.Test" } });
const fetchMock = vi.fn()
.mockResolvedValueOnce(new Response("not found", { status: 404 }))
.mockResolvedValueOnce(jsonResponse([adminRow({ user_id: NON_UUID })]));
vi.stubGlobal("fetch", fetchMock);
const u = await getAdminUser();
expect(u).not.toBeNull();
const secondUrl = fetchMock.mock.calls[1][0] as string;
expect(secondUrl).toContain("email=ilike.admin%40brand.test");
});
it("returns null when the admin_users row is inactive", async () => {
mockCookies(undefined);
mockAuthSession({ user: { id: UUID, email: "a@b.com" } });
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValueOnce(jsonResponse([adminRow({ active: false })])),
);
const u = await getAdminUser();
expect(u).toBeNull();
});
it("returns null when no row exists and auto-provisioning is unavailable", async () => {
mockCookies(undefined);
mockAuthSession({ user: { id: UUID, email: "a@b.com" } });
const fetchMock = vi.fn()
// 1. RPC returns []
.mockResolvedValueOnce(jsonResponse([]))
// 2. legacy REST also returns []
.mockResolvedValueOnce(jsonResponse([]))
// 3. upsert_admin_user also returns []
.mockResolvedValueOnce(jsonResponse([]));
vi.stubGlobal("fetch", fetchMock);
const u = await getAdminUser();
expect(u).toBeNull();
});
it("auto-provisions a first-time sign-in via upsert_admin_user", async () => {
mockCookies(undefined);
mockAuthSession({ user: { id: UUID, email: "new@brand.test" } });
const fetchMock = vi.fn()
// 1. RPC returns []
.mockResolvedValueOnce(jsonResponse([]))
// 2. legacy REST also returns []
.mockResolvedValueOnce(jsonResponse([]))
// 3. upsert returns the freshly-minted platform_admin row
.mockResolvedValueOnce(
jsonResponse([adminRow({ email: "new@brand.test" })]),
);
vi.stubGlobal("fetch", fetchMock);
const u = await getAdminUser();
expect(u).not.toBeNull();
expect(u?.role).toBe("platform_admin");
const upsertCall = fetchMock.mock.calls[2];
expect(upsertCall[0]).toBe(`${SUPABASE_URL}/rest/v1/rpc/upsert_admin_user`);
expect(JSON.parse(upsertCall[1].body)).toEqual({
p_user_id: UUID,
p_email: "new@brand.test",
p_auth_provider: "supabase",
p_auth_subject: null,
});
});
it("auto-provisions a Google sign-in with p_auth_provider=google and no p_user_id", async () => {
mockCookies(undefined);
mockAuthSession({ user: { id: NON_UUID, email: "new@brand.test" } });
const fetchMock = vi.fn()
.mockResolvedValueOnce(jsonResponse([])) // RPC miss
.mockResolvedValueOnce(jsonResponse([])) // legacy miss
.mockResolvedValueOnce(jsonResponse([adminRow({ user_id: null, auth_subject: NON_UUID })]));
vi.stubGlobal("fetch", fetchMock);
const u = await getAdminUser();
expect(u).not.toBeNull();
const upsertCall = fetchMock.mock.calls[2];
expect(JSON.parse(upsertCall[1].body)).toEqual({
p_user_id: null,
p_email: "new@brand.test",
p_auth_provider: "google",
p_auth_subject: NON_UUID,
});
});
it("returns null when cookies() throws (defensive)", async () => {
cookiesMock.mockRejectedValue(new Error("cookies unavailable"));
const u = await getAdminUser();
expect(u).toBeNull();
});
it("returns null when auth() throws (defensive)", async () => {
mockCookies(undefined);
authMock.mockRejectedValue(new Error("auth blew up"));
const u = await getAdminUser();
expect(u).toBeNull();
});
});
describe("buildDevAdmin", () => {
it("platform_admin has all permissions", () => {
const u = buildDevAdmin("platform_admin");
expect(u.role).toBe("platform_admin");
expect(u.can_manage_users).toBe(true);
expect(u.can_manage_settings).toBe(true);
expect(u.can_manage_products).toBe(true);
});
it("store_employee is restricted to orders + pickup", () => {
const u = buildDevAdmin("store_employee");
expect(u.role).toBe("store_employee");
expect(u.can_manage_orders).toBe(true);
expect(u.can_manage_pickup).toBe(true);
expect(u.can_manage_users).toBe(false);
expect(u.can_manage_settings).toBe(false);
expect(u.can_manage_products).toBe(false);
});
it("returns shim with brand_id=null", () => {
const u = buildDevAdmin("platform_admin");
expect(u.brand_id).toBeNull();
expect(u.must_change_password).toBe(false);
expect(u.active).toBe(true);
});
});