Files
co-lite/solvway-admin-portal/app/lib/AdminAuthContext.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session,
api-gateway, mobile-api, services-auth, services-system,
services-counter, services-member, services-log, services-email.
solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal
from tastefully 8bd93d15. Copied as tracked files only.

Literal secrets replaced with environment placeholders:
- services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY,
  MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default)
- services-system: JUMIO_TOKEN, JUMIO_SECRET (optional)
- services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed
- core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default
  removed, ipgeolocation key read from IPGEOLOCATION_API_KEY
- services-system EkycAppConfig: commented Jumio credentials removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 15:55:45 +08:00

141 lines
5.2 KiB
TypeScript

"use client";
import { ADMIN_REFUNDS_ENABLED } from "@/app/lib/features";
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 {
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;
/** Countries the admin may see; null = all. */
countryScope: string[] | null;
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>({
name: null,
roles: [],
aclMenu: null,
branch: null,
countryScope: null,
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;
}
/** The aclMenu tree without the refund requests module while ADMIN_REFUNDS_ENABLED is off. */
function withoutRefunds(node: AdminModule): AdminModule {
if (ADMIN_REFUNDS_ENABLED) return node;
return { ...node, children: node.children?.filter((c) => c.name !== "BO_REFUND_REQUESTS").map(withoutRefunds) };
}
export function AdminAuthProvider({ children }: { children: ReactNode }) {
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 [countryScope, setCountryScope] = useState<string[] | null>(null);
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) {
setName(null);
setRoles([]);
setAclMenu(null);
setGrantedMenu(null);
setBranch(null);
setCountryScope(null);
return;
}
const data = (await res.json()) as {
name: string;
roles: AdminRole[];
aclMenu: AdminModule;
branch?: AdminBranchRef | null;
countryScope?: string[] | null;
};
setName(data.name);
setRoles(data.roles ?? []);
setAclMenu(data.aclMenu ? withoutRefunds(data.aclMenu) : null);
setGrantedMenu(data.aclMenu ?? null);
setBranch(data.branch ?? null);
setCountryScope(data.countryScope ?? null);
} catch {
setName(null);
setRoles([]);
setAclMenu(null);
setGrantedMenu(null);
setBranch(null);
setCountryScope(null);
} 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={{ name, roles, aclMenu, branch, countryScope, loading, refresh: load, hasRole, hasModule, hasGrantedModule }}
>
{children}
</AdminAuthContext.Provider>
);
}
export const useAdminAuth = () => useContext(AdminAuthContext);