AccessProvider.tsx 3.99 KB
import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
import { defaultMatrix, type PermissionMatrix, type ResourceKey, type RoleKey } from '../model';
import { normalizePermissions, matrixToPoints } from '../backend/adapter';
import { auth } from '../../api/modules/auth';
import { getToken } from '../../api/core/token';

/** 登录/info 返回的会话数据(仅取权限相关字段,解耦 access 与具体后端响应结构) */
export interface LoginSession {
  roleCodes?: string[];
  permCodes?: string[];
}

interface AccessContextValue {
  role: RoleKey;
  roleCodes: string[];
  setRole: (r: RoleKey) => void;
  matrix: PermissionMatrix;
  /** 页面级权限:统一以 points 为准(页面资源裸码 = 可见,:manage = 完全权) */
  can: (resource: ResourceKey, required?: 'view' | 'full') => boolean;
  /** 当前账号持有的权限点集合(后端返回,经适配器归一化) */
  points: Set<string>;
  /** 按钮/操作级权限判定:是否拥有某个权限点 */
  canPoint: (point: string) => boolean;
  /** 用后端返回的原始权限数据刷新权限点(经 adapter 归一化) */
  loadPermissions: (raw: unknown) => void;
  /** 用登录/info 返回的真实权限码注入(后端为权限真源) */
  applyLogin: (session: LoginSession) => void;
}

const AccessContext = createContext<AccessContextValue | null>(null);

export function AccessProvider({ children }: { children: ReactNode }) {
  const [role, setRoleState] = useState<RoleKey>('SYS_ADMIN');
  const [roleCodes, setRoleCodes] = useState<string[]>([]);
  const [matrix] = useState<PermissionMatrix>(defaultMatrix);
  // 默认按超级管理员矩阵给一份(无后端时的开发兜底,避免首屏权限全空)
  const [points, setPoints] = useState<Set<string>>(
    () => new Set(matrixToPoints(matrix, 'SYS_ADMIN')),
  );

  // 开发兜底:按角色矩阵推导权限点(无后端时本地演示用)
  const setRole = (r: RoleKey) => {
    setRoleState(r);
    setPoints(new Set(matrixToPoints(matrix, r)));
  };

  // 真实登录:直接用后端返回的权限码(页面/按钮级统一以 points 为准)
  const applyLogin = (session: LoginSession) => {
    const codes = session.roleCodes ?? [];
    setRoleCodes(codes);
    const next = new Set(normalizePermissions(session.permCodes));
    // 后端未下发 dashboard 权限码,前端按约定补齐:
    // 工作台是所有角色的落地页,登录即可见,不该被权限挡住。
    //(原 access.manage 权限矩阵调试页已下线:后端菜单树与 permCodes 均无该权限点)
    next.add('dashboard');
    setPoints(next);
  };

  const loadPermissions = (raw: unknown) => {
    setPoints(new Set(normalizePermissions(raw)));
  };

  // 刷新/重进:若本地已有令牌,拉取当前用户信息恢复权限(令牌失效由 http 401 处理)
  useEffect(() => {
    if (!getToken()) return;
    auth
      .info()
      .then((info) => applyLogin(info))
      .catch(() => {
        /* 忽略:令牌失效时 http 拦截器会清除本地令牌,登录态由路由守卫兜底 */
      });
  }, []);

  const value = useMemo<AccessContextValue>(
    () => ({
      role,
      roleCodes,
      setRole,
      matrix,
      can: (resource, required = 'view') => {
        if (points.has(resource)) return true;
        if (required === 'full') return points.has(`${resource}:manage`);
        // 后端若只下发叶子权限码(如 store:list:export),亦视为该资源可见
        return [...points].some((p) => p.startsWith(`${resource}:`));
      },
      points,
      canPoint: (p: string) => points.has(p),
      loadPermissions,
      applyLogin,
    }),
    [role, roleCodes, matrix, points],
  );

  return <AccessContext.Provider value={value}>{children}</AccessContext.Provider>;
}

export function useAccess(): AccessContextValue {
  const ctx = useContext(AccessContext);
  if (!ctx) throw new Error('useAccess 必须在 <AccessProvider> 内使用');
  return ctx;
}