#
cl
18 小时以前 217ed5c65b7f72359c241bb35180c0a861a05f52
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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;
}