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:
@@ -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