import { useEffect, useState } from "react";
|
import { queryUserInfo } from "@/api/auth";
|
|
let authoritySetPromise = null;
|
|
/** 登出后清空,避免换账号仍用旧权限集 */
|
export function clearUserAuthorityCache() {
|
authoritySetPromise = null;
|
}
|
|
function flattenAuthorities(menus) {
|
const keys = [];
|
const walk = (list) => {
|
if (!list) return;
|
for (const m of list) {
|
if (m.authority) keys.push(m.authority);
|
if (m.children?.length) walk(m.children);
|
}
|
};
|
walk(menus);
|
return keys;
|
}
|
|
function getAuthoritySet() {
|
if (!authoritySetPromise) {
|
authoritySetPromise = queryUserInfo()
|
.then((u) => new Set(flattenAuthorities(u?.authorities)))
|
.catch(() => new Set());
|
}
|
return authoritySetPromise;
|
}
|
|
/**
|
* 是否拥有后端权限标识(与 @PreAuthorize hasAuthority 一致)
|
* @param {string} permission 如 manager:asnOrderLog:cloudWmsResend
|
*/
|
export function useHasAuthority(permission) {
|
const [ok, setOk] = useState(false);
|
useEffect(() => {
|
let cancelled = false;
|
getAuthoritySet().then((set) => {
|
if (!cancelled) setOk(permission ? set.has(permission) : false);
|
});
|
return () => {
|
cancelled = true;
|
};
|
}, [permission]);
|
return ok;
|
}
|