/* Copyright (C) 2025 QuantumNous This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, } from 'react'; import { useLocation } from 'react-router-dom'; import { Modal } from 'antd'; import { useTranslation } from 'react-i18next'; import { API } from '../helpers/api'; import { clearUserData, isOrgLoginSession, ORG_LOGIN_SESSION_KEY, USER_STORAGE_KEY, } from '../helpers/data'; import { clearProxyExpired, getCurrentOrgId, getProxySession, } from '../helpers/orgContext'; import { UserContext } from '../context/User'; import { normalizeView } from './permLogic'; // 权限上下文(权限重构 §9 GET /api/authz/me):同时持有平台视图与当前企业视图。 // 企业视图随当前企业(或代理会话)切换重新加载。有已切换模块、处于代理会话或上一次加载失败时,页面重新获得焦点 // (10 秒内不重复)、或每 60 秒刷新一次;否则(未切换,视图只用于判断是否已切换)每 10 分钟刷新一次、获得焦点时 // 2 分钟内不重复,不挤占按 IP 计数的全局限流,同时切换后用户切回窗口即可较快跟上。 // 当前视图的有效内容(权限点、菜单、数据范围)发生变化且涉及已切换模块时,按 Q12 要求重新登录。 export const AuthzContext = createContext({ platform: null, org: null, orgLoadedKey: null, platformLoadedFor: 0, platformLoadFailed: false, reload: () => {}, }); const REFRESH_MS = 60 * 1000; // 未切换时的刷新间隔 const IDLE_REFRESH_MS = 10 * 60 * 1000; // 窗口 focus 触发刷新的节流间隔:频繁切换窗口时不重复拉取 const FOCUS_THROTTLE_MS = 10 * 1000; // 未切换时 focus 触发刷新的节流间隔 const IDLE_FOCUS_THROTTLE_MS = 2 * 60 * 1000; // 未登录(会话失效、其他标签页已登出):不算"加载失败",不因此转入高频刷新 const UNAUTHORIZED = Symbol('unauthorized'); // 拉取视图;接口 success:false 或网络错误返回 null(调用方按"加载失败"处理),401 返回 UNAUTHORIZED const fetchView = async (headers) => { try { const res = await API.get('/api/authz/me', { headers, skipErrorHandler: true, disableDuplicate: true, }); return res.data?.success ? normalizeView(res.data.data) : null; } catch (e) { return e?.response?.status === 401 ? UNAUTHORIZED : null; } }; // 当前企业视图的标识(企业 ID + 代理会话):企业中心据此判断企业视图是否已按当前企业加载过 export const currentOrgViewKey = () => `${getCurrentOrgId()}:${getProxySession()?.id || ''}`; const orgHeaders = () => { const proxy = getProxySession(); const orgId = getCurrentOrgId(); if (!orgId) return null; const h = { 'X-Org-Id': String(orgId) }; if (proxy) h['X-Proxy-Session'] = proxy.id; return h; }; // 视图有效内容的指纹:只取已切换模块(前后两次 enforced_modules 的并集)内的权限点、 // 菜单(code 与 visible)与数据范围类型(全部 / 部门 / 本人);未切换模块的变化不影响页面行为,不纳入。 // 部门个数不纳入:它是按部门树展开后的个数,新增子部门就会变化,而页面行为不变。 // 已切换模块列表本身不纳入:模块切换(或回退)只是把页面从旧判断改为按权限点判断,界面就地更新, // 不属于 Q12 所说的撤权,不要求重新登录;切换前后权限点本身的变化仍会按上面的并集比较提示。 // 不用 version:它包含目录与企业版本,改任意菜单名、角色名都会变化,会误弹重新登录。 const viewSignature = (v, inScope) => JSON.stringify([ (v.perms || []).filter(inScope).sort(), (v.menus || []) .filter((m) => inScope(m.code)) .map((m) => `${m.code}:${m.visible ? 1 : 0}`) .sort(), Object.entries(v.scopes || {}) .filter(([code]) => inScope(code)) .map( ([code, sc]) => `${code}:${sc?.all ? 1 : 0}:${sc?.depts ? 1 : 0}:${sc?.self ? 1 : 0}`, ) .sort(), ]); // 有效内容变化且涉及已切换模块:权限确实影响到页面行为,需要重新登录 const changedUnderEnforce = (prev, next) => { if (!prev || !next) return false; // 用户、企业或登录域不同都是换了会话(如个人会话改用企业入口登录),不是权限变更 if ( prev.user_id !== next.user_id || prev.org_id !== next.org_id || prev.domain !== next.domain || (prev.session_domain || '') !== (next.session_domain || '') ) { return false; } const modules = new Set([ ...(prev.enforced_modules || []), ...(next.enforced_modules || []), ]); if (modules.size === 0) return false; const moduleOf = { ...(prev.module_of || {}), ...(next.module_of || {}) }; const inScope = (code) => modules.has(moduleOf[code]); return viewSignature(prev, inScope) !== viewSignature(next, inScope); }; // 视图是否涉及已切换模块(需要高频刷新以及时发现权限变更;代理会话另由调用方判断) const isActiveView = (v) => !!v && (v.enforced_modules || []).length > 0; // 内容相同的视图不重新写入状态,避免每次刷新都让订阅方(企业中心等)重渲染 const sameView = (a, b) => { if (a === b) return true; if (!a || !b) return false; try { return JSON.stringify(a) === JSON.stringify(b); } catch { return false; } }; export const AuthzProvider = ({ children }) => { const { t } = useTranslation(); const [userState, userDispatch] = useContext(UserContext); const userId = userState?.user?.id || 0; const location = useLocation(); const [platform, setPlatform] = useState(null); const [org, setOrg] = useState(null); // 最近一次企业视图加载(无论成败)对应的 currentOrgViewKey;未加载过为 null const [orgLoadedKey, setOrgLoadedKey] = useState(null); // 平台视图已为哪个用户加载过(成败均算);路由守卫据此等待视图到达,避免先按旧判断误拦 const [platformLoadedFor, setPlatformLoadedFor] = useState(0); // 最近一次平台视图加载是否失败(配合 platformLoadedFor 使用):路由守卫据此显示可重试提示 const [platformLoadFailed, setPlatformLoadFailed] = useState(false); const prevRef = useRef({ platform: null, org: null }); const promptedRef = useRef(false); // 已弹出的"权限已变更"提示实例:其他标签页换了会话时关闭它 const modalRef = useRef(null); // 最近一次开始拉取视图的时间,用于 focus 刷新节流 const lastFetchRef = useRef(0); // 最近一次加载是否有视图失败:失败后按高频刷新重试,否则已切换企业首次加载失败时会按旧判断渲染最长 10 分钟 const failedRef = useRef(false); // 最新的 reload:storage 事件处理里主动重新加载(事件处理只注册一次) const reloadRef = useRef(null); // 企业会话(企业域登录、或仅企业资源账号)重新登录回 /org/login,否则回 /login const orgOnlyRef = useRef(false); orgOnlyRef.current = userState?.user?.org_only_mode === true; const onOrgPage = location.pathname.startsWith('/org'); const orgKey = onOrgPage ? currentOrgViewKey() : ''; const promptRelogin = useCallback(() => { if (promptedRef.current) return; promptedRef.current = true; // 只能点"重新登录":不提供关闭按钮,点遮罩与按 Esc 都不关闭 modalRef.current = Modal.warning({ title: t('权限已变更'), content: t('你的权限已变更,请重新登录。'), okText: t('重新登录'), centered: true, closable: false, keyboard: false, mask: { closable: false }, onOk: async () => { modalRef.current = null; // 先判断会话域,再登出清理(清理会移除企业登录标记) // 以后端返回的登录域为准;老版本后端没有该字段时退回本地标记 const view = prevRef.current.org || prevRef.current.platform; const orgSession = view?.session_domain ? view.session_domain === 'org' : isOrgLoginSession() || orgOnlyRef.current; const target = orgSession ? '/org/login' : '/login'; try { await API.get('/api/user/logout', { skipErrorHandler: true, disableDuplicate: true, }); } catch { // 登出失败也继续清理本地数据并跳转登录页 } clearUserData(); userDispatch({ type: 'logout' }); window.location.href = target; }, }); }, [t, userDispatch]); const reload = useCallback(async () => { lastFetchRef.current = Date.now(); const loadingKey = currentOrgViewKey(); if (!userId) { setPlatform(null); setOrg(null); prevRef.current = { platform: null, org: null }; setOrgLoadedKey(loadingKey); setPlatformLoadedFor(0); setPlatformLoadFailed(false); return; } const headers = onOrgPage ? orgHeaders() : null; const [pr, or] = await Promise.all([ fetchView(undefined), headers ? fetchView(headers) : Promise.resolve(null), ]); const unauthorized = pr === UNAUTHORIZED || or === UNAUTHORIZED; const p = pr === UNAUTHORIZED ? null : pr; const o = or === UNAUTHORIZED ? null : or; if (p) { if (changedUnderEnforce(prevRef.current.platform, p)) promptRelogin(); const same = sameView(prevRef.current.platform, p); prevRef.current.platform = p; if (!same) setPlatform(p); } else { // 加载失败:保留上一份视图作比较基准;不属于当前用户的旧视图不能再用 const kept = prevRef.current.platform; if (kept && kept.user_id !== userId) { prevRef.current.platform = null; setPlatform(null); } } setPlatformLoadFailed(!p); setPlatformLoadedFor(userId); failedRef.current = !unauthorized && (!p || (!!headers && !o)); if (!headers) { prevRef.current.org = null; setOrg(null); // 不在企业页时并未加载企业视图,不能标记为已就绪(否则进入企业中心时会按旧判断先行守卫) setOrgLoadedKey(onOrgPage ? loadingKey : null); return; } if (o) { if (changedUnderEnforce(prevRef.current.org, o)) promptRelogin(); const same = sameView(prevRef.current.org, o); prevRef.current.org = o; if (!same) setOrg(o); } else { // 加载失败:保留上一份视图作比较基准;只有仍属于当前用户与当前企业时才继续使用 const kept = prevRef.current.org; if ( kept && (kept.user_id !== userId || kept.org_id !== getCurrentOrgId()) ) { prevRef.current.org = null; setOrg(null); } } setOrgLoadedKey(loadingKey); }, [userId, onOrgPage, promptRelogin]); // 换账号、换企业(含进入 / 退出代理)都要重新加载:企业键不参与 reload 本身的计算,单独作为触发条件 useEffect(() => { reloadRef.current = reload; }, [reload]); useEffect(() => { reload(); }, [reload, orgKey]); // 换账号(含登出):允许对新账号重新提示 useEffect(() => { promptedRef.current = false; }, [userId]); // 离开企业中心:清除本标签页的"代理已失效"标记,之后再进入 /org 按正常企业上下文解析 useEffect(() => { if (!onOrgPage) clearProxyExpired(); }, [onOrgPage]); // 多标签页:其他标签页重新登录或登出(localStorage 用户数据变化)时,关闭本页已弹出的提示, // 避免在旧标签页点"重新登录"把新会话注销;同时丢弃旧的比较基准,下一次加载按新会话重新建立 useEffect(() => { // 只看用户身份:登出(键被删)或换成另一个用户才算换会话;额度等字段刷新不算, // 否则会关掉仍然有效的提示并丢弃比较基准,本标签页就再也不会提示了 const userIdOf = (raw) => { try { return raw ? JSON.parse(raw)?.id || 0 : 0; } catch { return 0; } }; const onStorage = (e) => { if ( e.key !== USER_STORAGE_KEY && e.key !== ORG_LOGIN_SESSION_KEY && e.key !== null ) { return; } // 企业登录标记变化:同一用户在其他标签页改用企业入口(或个人入口)登录,登录域变了,按换会话处理 if ( e.key === USER_STORAGE_KEY && e.newValue !== null && userIdOf(e.oldValue) === userIdOf(e.newValue) ) { return; } if (modalRef.current) { modalRef.current.destroy(); modalRef.current = null; } promptedRef.current = false; prevRef.current = { platform: null, org: null }; // 立即按新会话重新加载:本标签页的 UserContext 不跨标签同步,不会自己触发加载; // 清空基准后也不再算"有已切换模块",不主动加载就要等最长 10 分钟 if (reloadRef.current) reloadRef.current(); }; window.addEventListener('storage', onStorage); return () => window.removeEventListener('storage', onStorage); }, []); useEffect(() => { if (!userId) return undefined; const active = () => failedRef.current || isActiveView(prevRef.current.platform) || isActiveView(prevRef.current.org) || !!getProxySession(); const timer = setInterval(() => { if ( active() || Date.now() - lastFetchRef.current >= IDLE_REFRESH_MS - 1000 ) { reload(); } }, REFRESH_MS); const onFocus = () => { const throttle = active() ? FOCUS_THROTTLE_MS : IDLE_FOCUS_THROTTLE_MS; if (Date.now() - lastFetchRef.current < throttle) return; reload(); }; window.addEventListener('focus', onFocus); return () => { clearInterval(timer); window.removeEventListener('focus', onFocus); }; }, [userId, reload]); const value = useMemo( () => ({ platform, org, orgLoadedKey, platformLoadedFor, platformLoadFailed, reload, }), [ platform, org, orgLoadedKey, platformLoadedFor, platformLoadFailed, reload, ], ); return ( {children} ); };