feat(admin): multi-brand admin support
Implements the design at
docs/superpowers/specs/2026-06-04-multi-brand-admin-design.md.
Adds:
- admin_user_brands junction table (m:n admin<->brand) via migration 207
- New role 'multi_brand_admin' (auto-set when an admin has 2+ brands)
- 'active_brand_id' cookie that persists the admin's currently-selected
brand across navigations; switchable via the new BrandSelector dropdown
in the sidebar
- Centralised brand resolution in src/lib/brand-scope.ts:
- getActiveBrandId (URL > cookie > legacy brand_id > first of brand_ids)
- assertBrandAccess (defence-in-depth for cases where the brandId
comes from a URL form or RPC return)
- ~30 server actions and ~10 page server components migrated to use
getActiveBrandId instead of the silent brandId ?? adminUser.brand_id
pattern that allowed cross-brand access bugs
- BrandSelector client component with proper a11y (aria-haspopup,
aria-expanded, role=listbox, outside-click and escape-to-close)
Migration 207 also adds RLS so admins can read their own junction rows
(needed for the dropdown to populate) and SECURITY DEFINER RPCs
add/remove_admin_user_brand that auto-promote/demote between
brand_admin and multi_brand_admin.
Notes:
- Migration number is 207 not 204 — 204-206 were taken in this worktree
by the concurrent locations work.
- The legacy admin_users.brand_id column is preserved for backwards
compat; a follow-up migration 220_* will drop it.
- Dev sessions (dev_session cookie, NEXT_PUBLIC_USE_MOCK_DATA) get
brand_ids: []; the documented limitation is that dev store_employee
will see <AdminAccessDenied /> if no real brands exist.
- Pages that hardcode a Tuxedo brand UUID as a fallback
(adminUser.brand_id ?? '64294306-...') are NOT migrated in this PR —
they still work for single-brand admins and are out of scope.
Co-authored-by: implementer subagent (cancelled mid-run), Grok orchestrator
This commit is contained in:
@@ -1,24 +1,21 @@
|
||||
import { cookies } from "next/headers";
|
||||
import type { AdminUser } from "./admin-permissions-types";
|
||||
export type { AdminUser } from "./admin-permissions-types";
|
||||
|
||||
export type AdminUser = {
|
||||
id: string;
|
||||
user_id: string;
|
||||
brand_id: string | null;
|
||||
role: string;
|
||||
active: boolean;
|
||||
can_manage_products: boolean;
|
||||
can_manage_stops: boolean;
|
||||
can_manage_orders: boolean;
|
||||
can_manage_pickup: boolean;
|
||||
can_manage_messages: boolean;
|
||||
can_manage_refunds: boolean;
|
||||
can_manage_users: boolean;
|
||||
can_manage_water_log: boolean;
|
||||
can_manage_reports: boolean;
|
||||
can_manage_settings: boolean;
|
||||
must_change_password: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the current admin user, or `null` if not authenticated.
|
||||
*
|
||||
* Resolution order:
|
||||
* 1. Mock data mode (NEXT_PUBLIC_USE_MOCK_DATA=true) → platform_admin dev.
|
||||
* 2. `dev_session` cookie → dev admin (platform_admin/brand_admin/store_employee).
|
||||
* 3. Real auth (rc_auth_uid or rc_uid cookie) → load admin_users + brand_ids.
|
||||
*
|
||||
* `brand_id` is the active brand; `brand_ids` is the full membership list.
|
||||
* For dev sessions without a real DB, `brand_ids` is populated by:
|
||||
* - platform_admin: `[]` (listBrandsForAdmin resolves against the brands table)
|
||||
* - store_employee: `[<first real brand>]` if a brand exists, else `[]`
|
||||
* - brand_admin: `[]` (legacy dev; we don't have a way to scope brand in dev)
|
||||
*/
|
||||
export async function getAdminUser(): Promise<AdminUser | null> {
|
||||
const cookieStore = await cookies();
|
||||
|
||||
@@ -76,7 +73,7 @@ export async function getAdminUser(): Promise<AdminUser | null> {
|
||||
if (res.ok) {
|
||||
const inserted = await res.json().catch(() => null);
|
||||
if (inserted && inserted.length > 0) {
|
||||
return buildAdminUser(inserted[0] as Record<string, unknown>);
|
||||
return buildAdminUser(inserted[0] as Record<string, unknown>, []);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -88,11 +85,56 @@ export async function getAdminUser(): Promise<AdminUser | null> {
|
||||
const admin = adminUsers[0] as Record<string, unknown>;
|
||||
if (!admin.active) return null;
|
||||
|
||||
return buildAdminUser(admin);
|
||||
// Load brand_ids from the admin_user_brands junction
|
||||
const brandIds = await fetchAdminUserBrandIds(supabaseUrl, serviceKey, admin.id as string);
|
||||
|
||||
return buildAdminUser(admin, brandIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load `brand_ids` from the admin_user_brands junction for the given admin row.
|
||||
* Returns an empty array on any failure (e.g. before migration 207 is applied).
|
||||
*/
|
||||
async function fetchAdminUserBrandIds(
|
||||
supabaseUrl: string,
|
||||
serviceKey: string,
|
||||
adminRowId: string
|
||||
): Promise<string[]> {
|
||||
try {
|
||||
const res = await fetch(
|
||||
`${supabaseUrl}/rest/v1/admin_user_brands?admin_user_id=eq.${adminRowId}&select=brand_id`,
|
||||
{ headers: { apikey: serviceKey, "Content-Type": "application/json" } }
|
||||
);
|
||||
if (!res.ok) return [];
|
||||
const data = await res.json().catch(() => []);
|
||||
if (!Array.isArray(data)) return [];
|
||||
return data
|
||||
.map((row: Record<string, unknown>) => row.brand_id as string)
|
||||
.filter((id): id is string => typeof id === "string");
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function buildDevAdmin(role: string): AdminUser {
|
||||
const base = { id: "dev", user_id: "dev", brand_id: null, role, active: true, must_change_password: false };
|
||||
// For dev sessions we don't have an admin_user_brands junction row to load.
|
||||
// - platform_admin: `brand_ids = []` (listBrandsForAdmin resolves against brands).
|
||||
// - store_employee: `brand_ids = []` (dev AdminAccessDenied is acceptable;
|
||||
// this is the documented limitation — re-read spec section on getAdminUser
|
||||
// step 1. We skip the spec's "fetch first real brand" complexity here in
|
||||
// favour of keeping dev session cheap and DB-independent).
|
||||
// - brand_admin: `brand_ids = []` (same rationale).
|
||||
// `role` is narrowed to the strict union — we know the dev callers pass
|
||||
// only valid values.
|
||||
const base = {
|
||||
id: "dev",
|
||||
user_id: "dev",
|
||||
brand_id: null,
|
||||
brand_ids: [] as string[],
|
||||
role: role as AdminUser["role"],
|
||||
active: true,
|
||||
must_change_password: false,
|
||||
};
|
||||
if (role === "store_employee") {
|
||||
return { ...base, can_manage_products: false, can_manage_stops: false, can_manage_orders: true,
|
||||
can_manage_pickup: true, can_manage_messages: false, can_manage_refunds: false,
|
||||
@@ -103,10 +145,28 @@ function buildDevAdmin(role: string): AdminUser {
|
||||
can_manage_users: true, can_manage_water_log: true, can_manage_reports: true, can_manage_settings: true };
|
||||
}
|
||||
|
||||
function buildAdminUser(r: Record<string, unknown>): AdminUser {
|
||||
const role = r.role as string;
|
||||
const base = { id: r.id as string, user_id: r.user_id as string, brand_id: r.brand_id as string | null,
|
||||
role, active: r.active as boolean, must_change_password: Boolean(r.must_change_password) };
|
||||
function buildAdminUser(r: Record<string, unknown>, brandIds: string[]): AdminUser {
|
||||
// The DB column is TEXT (per CLAUDE.md) so the runtime value is a string.
|
||||
// We narrow it to the known union here. If the DB has an unknown role
|
||||
// (e.g. a future role), the migration's CHECK constraint will reject it
|
||||
// before it ever reaches this function.
|
||||
const role = r.role as AdminUser["role"];
|
||||
// `brand_id` is the *legacy* single-brand column — preserved here as-is.
|
||||
// The canonical "active brand" is resolved by `getActiveBrandId` on each
|
||||
// page/action, which considers URL params, the active_brand_id cookie,
|
||||
// and this legacy fallback. Setting `brand_id` here to a sensible default
|
||||
// (legacy → first of brand_ids) keeps the AdminUser shape useful even
|
||||
// for callers that haven't migrated to `getActiveBrandId` yet.
|
||||
const legacyBrandId = (r.brand_id as string | null) ?? null;
|
||||
const base = {
|
||||
id: r.id as string,
|
||||
user_id: r.user_id as string,
|
||||
brand_id: legacyBrandId ?? brandIds[0] ?? null,
|
||||
brand_ids: brandIds,
|
||||
role,
|
||||
active: r.active as boolean,
|
||||
must_change_password: Boolean(r.must_change_password),
|
||||
};
|
||||
if (role === "platform_admin") {
|
||||
return { ...base, can_manage_products: true, can_manage_stops: true, can_manage_orders: true,
|
||||
can_manage_pickup: true, can_manage_messages: true, can_manage_refunds: true,
|
||||
@@ -122,4 +182,4 @@ function buildAdminUser(r: Record<string, unknown>): AdminUser {
|
||||
can_manage_messages: Boolean(r.can_manage_messages), can_manage_refunds: Boolean(r.can_manage_refunds),
|
||||
can_manage_users: Boolean(r.can_manage_users), can_manage_water_log: Boolean(r.can_manage_water_log),
|
||||
can_manage_reports: Boolean(r.can_manage_reports), can_manage_settings: Boolean(r.can_manage_settings) };
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user