import SDK_RBAC from '@sdp.nd/rbac' import One from '..' /** * 初始化 RBAC */ export default function pluginRBAC ($: One) { addProps($) const options = initOptions($) if (options) { $.RBAC = initRBAC(options) } const { rbacCallback } = $.options if (rbacCallback) { rbacCallback($) } } export async function asyncPluginRBAC ($: One) { addProps($) const options = initOptions($) if (options) { // 使用 getToken 替换 isLogin,避免重复发起服务端请求 const token = await $.getTokenAsync() if (token) { $.RBAC = await initRBAC(options, true) } else { $.RBAC = initRBAC(options) } const { rbacCallback } = $.options if (rbacCallback) { await rbacCallback($) } } } function initOptions ($: One) { const { request, storage, options: { rbac = {}, env } } = $ // 如果主动禁用 RBAC if (rbac === false) { return null } return { request, storage, env, ...rbac } } function initRBAC (options: object, async?: boolean) { if (async) { return SDK_RBAC.init(options) } return new SDK_RBAC(options) } function addProps ($: One) { // 向外暴露类 $.__RBAC = SDK_RBAC /** * 判断权限 * @param {string} resourceCode - 资源代码 * @returns {boolean} * @example * hasAuth('x') // has x * hasAuth('x;y;z') // has x or y or z * hasAuth('x,y,z') // has x and y and z * hasAuth('x;y,z') // has x or (y and z) */ $.hasAuth = (resourceCode: string): boolean => { // 没有启用 RBAC,则默认为 true if (!$.RBAC) { return true } return resourceCode.split(';') .some(P => P.split(',').every(p => $.RBAC.hasAuth(p))) } }