Files
co-lite/solvway-admin-portal/app/lib/AdminAuthContext.tsx
T

163 lines
5.7 KiB
TypeScript

"use client";
import { createContext, useContext, useEffect, useState, useCallback, useMemo, ReactNode } from "react";
import type { AdminBranchRef, AdminModule, AdminRole } from "@/app/lib/types";
// Ported from solvway-customer-portal's app/lib/MemberContext.tsx, extended
// with hasRole/hasModule over the ACL tree (spec: "Access Is Gated By Role
// And Module, As UX Only"). Session hydration is the single source of truth
// for roles/aclMenu — the login response is minimal (see Task 4 interface
// note) and the httpOnly cookie never carries them (spec: "The ACL tree is
// not stored in the cookie").
interface AdminAuthCtx {
/** The signed-in admin's user id and username (null until the session loads). */
id: number | null;
username: string | null;
name: string | null;
roles: AdminRole[];
aclMenu: AdminModule | null;
/** The signed-in admin's assigned branch (add-branch-counter-sale). Null when unassigned —
* the Branch Counter POS page must show an empty state and suppress Place-sale. */
branch: AdminBranchRef | null;
/** The signed-in admin's company; null for a super admin. */
companyId: number | null;
companyCode: string | null;
isSuper: boolean;
loading: boolean;
refresh: () => Promise<void>;
/** Matches over roles[].name, e.g. hasRole("ROLE_ADMIN"). */
hasRole: (roleName: string) => boolean;
/** Matches a flattened aclMenu node by its `name` OR its `url`. */
hasModule: (nameOrUrl: string) => boolean;
/** Like hasModule but over the unfiltered tree: for actions the backend authorises that a feature switch must not hide, currently only Cancel shipment. */
hasGrantedModule: (nameOrUrl: string) => boolean;
}
const AdminAuthContext = createContext<AdminAuthCtx>({
id: null,
username: null,
name: null,
roles: [],
aclMenu: null,
branch: null,
companyId: null,
companyCode: null,
isSuper: false,
loading: true,
refresh: async () => {},
hasRole: () => false,
hasModule: () => false,
hasGrantedModule: () => false,
});
/** Every node of the aclMenu tree — root plus all descendants, any type (R/M/A). */
export function flattenModules(root: AdminModule | null | undefined): AdminModule[] {
if (!root) return [];
const out: AdminModule[] = [];
const walk = (node: AdminModule) => {
out.push(node);
for (const child of node.children ?? []) walk(child);
};
walk(root);
return out;
}
export function AdminAuthProvider({ children }: { children: ReactNode }) {
const [id, setId] = useState<number | null>(null);
const [username, setUsername] = useState<string | null>(null);
const [name, setName] = useState<string | null>(null);
const [roles, setRoles] = useState<AdminRole[]>([]);
const [aclMenu, setAclMenu] = useState<AdminModule | null>(null);
const [grantedMenu, setGrantedMenu] = useState<AdminModule | null>(null);
const [branch, setBranch] = useState<AdminBranchRef | null>(null);
const [companyId, setCompanyId] = useState<number | null>(null);
const [companyCode, setCompanyCode] = useState<string | null>(null);
const [isSuper, setIsSuper] = useState(false);
const [loading, setLoading] = useState(true);
const load = useCallback(async () => {
try {
// Raw fetch (not a client wrapper that redirects on 401) — a legitimate
// 401 on a public page (e.g. /login) must not throw or redirect-loop.
const res = await fetch("/api/auth/session");
if (!res.ok) {
setId(null);
setUsername(null);
setName(null);
setRoles([]);
setAclMenu(null);
setGrantedMenu(null);
setBranch(null);
setCompanyId(null);
setCompanyCode(null);
setIsSuper(false);
return;
}
const data = (await res.json()) as {
id?: number;
username?: string;
name: string;
roles: AdminRole[];
aclMenu: AdminModule;
branch?: AdminBranchRef | null;
companyId?: number | null;
companyCode?: string | null;
isSuper?: boolean;
};
setId(data.id ?? null);
setUsername(data.username ?? null);
setName(data.name);
setRoles(data.roles ?? []);
setAclMenu(data.aclMenu ?? null);
setGrantedMenu(data.aclMenu ?? null);
setBranch(data.branch ?? null);
setCompanyId(data.companyId ?? null);
setCompanyCode(data.companyCode ?? null);
setIsSuper(data.isSuper === true);
} catch {
setId(null);
setUsername(null);
setName(null);
setRoles([]);
setAclMenu(null);
setGrantedMenu(null);
setBranch(null);
setCompanyId(null);
setCompanyCode(null);
setIsSuper(false);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect -- mount-time session fetch; setState runs in the async callback after the await, not synchronously.
void load();
}, [load]);
const hasRole = useCallback((roleName: string) => roles.some((r) => r.name === roleName), [roles]);
const flatModules = useMemo(() => flattenModules(aclMenu), [aclMenu]);
const hasModule = useCallback(
(nameOrUrl: string) => flatModules.some((m) => m.name === nameOrUrl || m.url === nameOrUrl),
[flatModules],
);
const flatGranted = useMemo(() => flattenModules(grantedMenu), [grantedMenu]);
const hasGrantedModule = useCallback(
(nameOrUrl: string) => flatGranted.some((m) => m.name === nameOrUrl || m.url === nameOrUrl),
[flatGranted],
);
return (
<AdminAuthContext.Provider
value={{ id, username, name, roles, aclMenu, branch, companyId, companyCode, isSuper, loading, refresh: load, hasRole, hasModule, hasGrantedModule }}
>
{children}
</AdminAuthContext.Provider>
);
}
export const useAdminAuth = () => useContext(AdminAuthContext);