feat: remove dev_session, add Drizzle schema + RLS + real auth
BREAKING: dev_session cookie bypass removed. Admin access now requires a real Auth.js v5 session (Google OAuth in production). Provision users by inserting into users + tenant_users tables. New in this commit: - db/migrations/0001_init.sql: 18-table SaaS schema with RLS (tenants, users, tenant_users, plans, add_ons, subscriptions, tenant_add_ons, products, product_images, stops, customers, orders, order_items, brand_settings, email_templates, campaigns, files, audit_log) - db/schema/: Drizzle TypeScript mirror of every table - db/client.ts: withTenant() / withPlatformAdmin() query wrappers that set Postgres GUCs (app.current_tenant_id, app.platform_admin) for RLS enforcement. Never query a tenant-scoped table without one. - db/seed.ts: seeds 3 plans, 6 add-ons, 2 tenants (Tuxedo, Indian River Direct), brand_settings, sample products/stops/customers - scripts/migrate.js: applies migrations in lexical order with tracking - scripts/db-reset.js: drops + recreates DB, runs migrate + seed - DATABASE_URL now uses rc_app (non-superuser, NOBYPASSRLS). RLS is enforced even for the app user. DATABASE_ADMIN_URL for migrations. - src/lib/admin-permissions.ts: getAdminUser() reads Auth.js session, looks up user + tenant in Postgres. brand_id kept as alias for backward compat. - src/middleware.ts: Auth.js-only route protection, dev_session gone - src/app/login/LoginClient.tsx: Google OAuth only, no demo mode - src/components/admin/AdminSidebar.tsx + AdminHeader.tsx: signOutAction replaces supabase signout - @/db/* path aliases in tsconfig.json + vitest.config.ts - drizzle.config.ts added - db/auth_schema.sql removed (was a stub; replaced by real schema) - src/app/api/dev-login/route.ts deleted - tests: updated to remove dev_session coverage
This commit is contained in:
+9
-71
@@ -11,9 +11,8 @@ test.describe("Auth.js v5 endpoints", () => {
|
||||
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");
|
||||
// The Google provider is only present when AUTH_GOOGLE_ID +
|
||||
// AUTH_GOOGLE_SECRET are set.
|
||||
if (process.env.AUTH_GOOGLE_ID && process.env.AUTH_GOOGLE_SECRET) {
|
||||
expect(providers).toHaveProperty("google");
|
||||
}
|
||||
@@ -35,7 +34,6 @@ test.describe("Auth.js v5 endpoints", () => {
|
||||
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();
|
||||
});
|
||||
@@ -48,76 +46,16 @@ 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();
|
||||
await expect(page.locator("body")).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("unauthed /admin redirects to /login", async ({ page }) => {
|
||||
await page.goto(`${BASE}/admin`, { waitUntil: "domcontentloaded" });
|
||||
expect(page.url()).toMatch(/\/login/);
|
||||
});
|
||||
|
||||
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).
|
||||
test("unauthed /wholesale redirects to /login", async ({ page }) => {
|
||||
await page.goto(`${BASE}/wholesale`, { waitUntil: "domcontentloaded" });
|
||||
expect(page.url()).toMatch(/\/login/);
|
||||
});
|
||||
});
|
||||
|
||||
+23
-104
@@ -3,115 +3,34 @@ import { test, expect } from "@playwright/test";
|
||||
const BASE = process.env.PLAYWRIGHT_URL ?? "http://localhost:3000";
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// Login form renders the right affordances
|
||||
// Login page — Google OAuth is the only login path
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
test.describe("Login form rendering", () => {
|
||||
test("renders Google button, email + password fields, and Sign in button", async ({ page }) => {
|
||||
test.describe("Login page", () => {
|
||||
test("renders the Google sign-in button", async ({ page }) => {
|
||||
await page.goto(`${BASE}/login`);
|
||||
|
||||
// The Google button is the primary CTA at the top of the form.
|
||||
await expect(page.getByRole("button", { name: /continue with google/i })).toBeVisible();
|
||||
|
||||
// Email + password inputs
|
||||
await expect(page.locator("#email")).toBeVisible();
|
||||
await expect(page.locator("#password")).toBeVisible();
|
||||
|
||||
// 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 }) => {
|
||||
test("shows a friendly 'not configured' message when Google OAuth env is missing", async ({ page }) => {
|
||||
// The page either shows the Google button (when AUTH_GOOGLE_ID/SECRET
|
||||
// are set) or a setup message (when they aren't). We accept both as
|
||||
// correct renderings.
|
||||
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", "");
|
||||
});
|
||||
});
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// 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();
|
||||
|
||||
// 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");
|
||||
});
|
||||
|
||||
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");
|
||||
});
|
||||
|
||||
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");
|
||||
});
|
||||
});
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// 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.",
|
||||
);
|
||||
|
||||
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!);
|
||||
|
||||
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 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");
|
||||
const hasGoogle = await page
|
||||
.getByRole("button", { name: /continue with google/i })
|
||||
.isVisible()
|
||||
.catch(() => false);
|
||||
const hasSetup = await page
|
||||
.getByText(/Google sign-in is not configured/i)
|
||||
.isVisible()
|
||||
.catch(() => false);
|
||||
expect(hasGoogle || hasSetup).toBe(true);
|
||||
});
|
||||
|
||||
test("/admin redirects to /login when not authenticated", async ({ page }) => {
|
||||
const res = await page.goto(`${BASE}/admin`, { waitUntil: "domcontentloaded" });
|
||||
// After redirect, the URL should be /login (with ?redirect=/admin).
|
||||
expect(page.url()).toMatch(/\/login(\?|$)/);
|
||||
expect(res?.status()).toBeLessThan(500);
|
||||
});
|
||||
});
|
||||
|
||||
+30
-43
@@ -3,39 +3,9 @@ import { test, expect } from "@playwright/test";
|
||||
const BASE = process.env.PLAYWRIGHT_URL ?? "http://localhost:3000";
|
||||
|
||||
test.describe("Smoke Tests", () => {
|
||||
test("Login — dev_session platform_admin lands on admin dashboard", async ({ page }) => {
|
||||
await page.context().addCookies([
|
||||
{ name: "dev_session", value: "platform_admin", domain: "localhost", path: "/" },
|
||||
]);
|
||||
|
||||
await page.goto(`${BASE}/admin`);
|
||||
await expect(page).toHaveURL(/\/admin/, { timeout: 5000 });
|
||||
|
||||
// Admin sidebar nav should be loaded (sidebar is rendered by layout)
|
||||
await expect(page.locator("aside").first()).toBeVisible({ timeout: 5000 });
|
||||
});
|
||||
|
||||
test("Admin Settings — page loads", async ({ page }) => {
|
||||
await page.context().addCookies([
|
||||
{ name: "dev_session", value: "platform_admin", domain: "localhost", path: "/" },
|
||||
]);
|
||||
|
||||
await page.goto(`${BASE}/admin/settings`);
|
||||
|
||||
// Wait for redirect to complete (may go to /login first)
|
||||
await page.waitForURL(/\/admin\/settings/, { timeout: 10000 });
|
||||
|
||||
// Page renders without crash — main content area should exist
|
||||
await expect(page.locator("main").first()).toBeVisible({ timeout: 8000 });
|
||||
});
|
||||
|
||||
test("Time Tracking — page loads", async ({ page }) => {
|
||||
await page.context().addCookies([
|
||||
{ name: "dev_session", value: "platform_admin", domain: "localhost", path: "/" },
|
||||
]);
|
||||
|
||||
await page.goto(`${BASE}/admin/time-tracking`);
|
||||
await expect(page).toHaveURL(/\/admin\/time-tracking/, { timeout: 5000 });
|
||||
test("Homepage loads", async ({ page }) => {
|
||||
const res = await page.goto(`${BASE}/`);
|
||||
expect(res?.status()).toBeLessThan(500);
|
||||
await expect(page.locator("body")).toBeVisible();
|
||||
});
|
||||
|
||||
@@ -46,17 +16,34 @@ test.describe("Smoke Tests", () => {
|
||||
});
|
||||
|
||||
await page.goto(`${BASE}/tuxedo`);
|
||||
|
||||
// Hero brand name — use a more stable anchor
|
||||
await expect(page.locator("h1").first()).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// "Why Choose" section heading is a strong signal the page rendered correctly
|
||||
await expect(page.getByRole("heading", { name: /why choose/i })).toBeVisible({ timeout: 5000 });
|
||||
|
||||
// No console errors (filter known non-critical)
|
||||
await expect(page.locator("h1").first()).toBeVisible({ timeout: 10_000 });
|
||||
const criticalErrors = errors.filter(
|
||||
(e) => !e.includes("favicon") && !e.includes("Warning:")
|
||||
(e) => !e.includes("favicon") && !e.includes("Warning:"),
|
||||
);
|
||||
expect(criticalErrors).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
test("Indian River Direct storefront — homepage loads", async ({ page }) => {
|
||||
const res = await page.goto(`${BASE}/indian-river-direct`);
|
||||
expect(res?.status()).toBeLessThan(500);
|
||||
await expect(page.locator("body")).toBeVisible();
|
||||
});
|
||||
|
||||
test("/admin redirects to /login when unauthenticated", async ({ page }) => {
|
||||
await page.goto(`${BASE}/admin`, { waitUntil: "domcontentloaded" });
|
||||
expect(page.url()).toMatch(/\/login(\?|$)/);
|
||||
});
|
||||
|
||||
test("Login page renders the Google CTA (or 'not configured' notice)", async ({ page }) => {
|
||||
await page.goto(`${BASE}/login`);
|
||||
const hasGoogle = await page
|
||||
.getByRole("button", { name: /continue with google/i })
|
||||
.isVisible()
|
||||
.catch(() => false);
|
||||
const hasSetup = await page
|
||||
.getByText(/Google sign-in is not configured/i)
|
||||
.isVisible()
|
||||
.catch(() => false);
|
||||
expect(hasGoogle || hasSetup).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* 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.
|
||||
* Mocks `@/lib/auth` to test the action wrappers in isolation from the
|
||||
* network and the Auth.js runtime.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
@@ -15,19 +15,12 @@ vi.mock("@/lib/auth", () => ({
|
||||
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 });
|
||||
}
|
||||
},
|
||||
}));
|
||||
// `server-only` is a runtime guard that throws if imported outside a
|
||||
// server context. Vitest is a Node env, so the guard fires — stub it.
|
||||
vi.mock("server-only", () => ({}));
|
||||
|
||||
// Import after mocks.
|
||||
const { signInWithPassword, signInWithGoogle, signOutAction } = await import(
|
||||
const { signInWithGoogle, signOutAction } = await import(
|
||||
"@/actions/auth-actions"
|
||||
);
|
||||
|
||||
@@ -36,60 +29,6 @@ beforeEach(() => {
|
||||
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);
|
||||
|
||||
+165
-311
@@ -1,338 +1,192 @@
|
||||
/**
|
||||
* @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.
|
||||
* Unit tests for `getAdminUser()`. The dev_session cookie bypass has been
|
||||
* removed; the only path into the admin is through a real Auth.js
|
||||
* session. These tests mock the `auth()` function and the DB layer
|
||||
* to exercise the lookup.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
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.
|
||||
// Stub the server-only guard so the module can be imported under vitest.
|
||||
vi.mock("server-only", () => ({}));
|
||||
|
||||
// Import AFTER the mocks.
|
||||
const { getAdminUser, buildDevAdmin } = await import("@/lib/admin-permissions");
|
||||
// Mock the Drizzle client wrapper so we don't need a real DB.
|
||||
const mockSelect = vi.fn();
|
||||
const mockWithPlatformAdmin = vi.fn(async (fn: any) => fn({ select: mockSelect }));
|
||||
vi.mock("@/db/client", () => ({
|
||||
withPlatformAdmin: (fn: any) => mockWithPlatformAdmin(fn),
|
||||
}));
|
||||
|
||||
// ── Test helpers ───────────────────────────────────────────────────
|
||||
// Mock the auth() function. The default mock returns null (no session).
|
||||
const authMock = vi.fn();
|
||||
vi.mock("@/lib/auth", () => ({
|
||||
auth: () => authMock(),
|
||||
}));
|
||||
|
||||
const UUID = "00000000-0000-0000-0000-000000000001";
|
||||
const NON_UUID = "google-sub-1234567890";
|
||||
// Mock cookies() so we don't read a real cookie store.
|
||||
const cookieStoreGet = vi.fn();
|
||||
vi.mock("next/headers", () => ({
|
||||
cookies: () =>
|
||||
Promise.resolve({
|
||||
get: (name: string) => cookieStoreGet(name),
|
||||
}),
|
||||
}));
|
||||
|
||||
function mockCookies(value: string | undefined) {
|
||||
cookiesMock.mockResolvedValue({
|
||||
get: (name: string) =>
|
||||
name === "dev_session" && value ? { name, value } : undefined,
|
||||
});
|
||||
}
|
||||
import { getAdminUser, buildDevAdmin, permissionsForRole } from "@/lib/admin-permissions";
|
||||
|
||||
function mockAuthSession(session: { user?: { id?: string; email?: string } } | null) {
|
||||
authMock.mockResolvedValue(session);
|
||||
}
|
||||
beforeEach(() => {
|
||||
mockSelect.mockReset();
|
||||
authMock.mockReset();
|
||||
cookieStoreGet.mockReset();
|
||||
});
|
||||
|
||||
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();
|
||||
describe("getAdminUser()", () => {
|
||||
it("returns null when there is no Auth.js session", async () => {
|
||||
authMock.mockResolvedValue(null);
|
||||
cookieStoreGet.mockReturnValue(undefined);
|
||||
const u = await getAdminUser();
|
||||
expect(u).toBeNull();
|
||||
});
|
||||
|
||||
it("returns platform_admin shim for dev_session=platform_admin", async () => {
|
||||
mockCookies("platform_admin");
|
||||
it("returns null when the session has no email", async () => {
|
||||
authMock.mockResolvedValue({ user: { name: "no-email" } });
|
||||
const u = await getAdminUser();
|
||||
expect(u).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when the email is not in the users table", async () => {
|
||||
authMock.mockResolvedValue({ user: { email: "unknown@example.com" } });
|
||||
// First select: users. Returns empty.
|
||||
mockSelect.mockReturnValueOnce({
|
||||
from: () => ({
|
||||
where: () => ({
|
||||
limit: async () => [],
|
||||
}),
|
||||
}),
|
||||
});
|
||||
const u = await getAdminUser();
|
||||
expect(u).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when the user exists but has no tenant_users row", async () => {
|
||||
authMock.mockResolvedValue({ user: { email: "no-tenant@example.com" } });
|
||||
// First select: users — returns the user
|
||||
mockSelect
|
||||
.mockReturnValueOnce({
|
||||
from: () => ({
|
||||
where: () => ({
|
||||
limit: async () => [
|
||||
{
|
||||
id: "user-1",
|
||||
email: "no-tenant@example.com",
|
||||
name: "No Tenant",
|
||||
authProvider: "google",
|
||||
authSubject: "google-sub",
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
})
|
||||
// Second select: tenantUsers — returns empty
|
||||
.mockReturnValueOnce({
|
||||
from: () => ({
|
||||
innerJoin: () => ({
|
||||
where: () => ({
|
||||
limit: async () => [],
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
const u = await getAdminUser();
|
||||
expect(u).toBeNull();
|
||||
});
|
||||
|
||||
it("returns a fully-populated AdminUser for a provisioned brand_admin", async () => {
|
||||
authMock.mockResolvedValue({ user: { email: "admin@tuxedo.example" } });
|
||||
mockSelect
|
||||
.mockReturnValueOnce({
|
||||
from: () => ({
|
||||
where: () => ({
|
||||
limit: async () => [
|
||||
{
|
||||
id: "user-tux",
|
||||
email: "admin@tuxedo.example",
|
||||
name: "Tux Admin",
|
||||
authProvider: "google",
|
||||
authSubject: "google-tux",
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.mockReturnValueOnce({
|
||||
from: () => ({
|
||||
innerJoin: () => ({
|
||||
where: () => ({
|
||||
limit: async () => [
|
||||
{
|
||||
tenantId: "tenant-tux",
|
||||
tenantName: "Tuxedo Citrus",
|
||||
tenantSlug: "tuxedo",
|
||||
tenantStatus: "active",
|
||||
role: "brand_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?.email).toBe("admin@tuxedo.example");
|
||||
expect(u?.tenant_id).toBe("tenant-tux");
|
||||
expect(u?.tenant_slug).toBe("tuxedo");
|
||||
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);
|
||||
expect(u?.can_manage_products).toBe(true);
|
||||
expect(u?.can_manage_team).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
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", () => {
|
||||
describe("buildDevAdmin()", () => {
|
||||
it("returns a platform_admin with no tenant", () => {
|
||||
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);
|
||||
expect(u.tenant_id).toBeNull();
|
||||
expect(u.tenant_slug).toBeNull();
|
||||
expect(u.can_manage_billing).toBe(true);
|
||||
});
|
||||
|
||||
it("store_employee is restricted to orders + pickup", () => {
|
||||
it("returns a brand_admin tied to the tuxedo tenant", () => {
|
||||
const u = buildDevAdmin("brand_admin");
|
||||
expect(u.role).toBe("brand_admin");
|
||||
expect(u.tenant_slug).toBe("tuxedo");
|
||||
expect(u.can_manage_users).toBe(false);
|
||||
});
|
||||
|
||||
it("returns a store_employee with limited permissions", () => {
|
||||
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);
|
||||
expect(u.can_manage_orders).toBe(true);
|
||||
expect(u.can_manage_billing).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("permissionsForRole()", () => {
|
||||
it("platform_admin can do everything", () => {
|
||||
const p = permissionsForRole("platform_admin");
|
||||
expect(Object.values(p).every((v) => v === true)).toBe(true);
|
||||
});
|
||||
it("brand_admin can manage most things but not users", () => {
|
||||
const p = permissionsForRole("brand_admin");
|
||||
expect(p.can_manage_users).toBe(false);
|
||||
expect(p.can_manage_billing).toBe(true);
|
||||
});
|
||||
it("store_employee is restricted to orders + pickup", () => {
|
||||
const p = permissionsForRole("store_employee");
|
||||
expect(p.can_manage_orders).toBe(true);
|
||||
expect(p.can_manage_pickup).toBe(true);
|
||||
expect(p.can_manage_products).toBe(false);
|
||||
expect(p.can_manage_billing).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user