vue-app-sdk
Version:
99 lines (98 loc) • 2.85 kB
JavaScript
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
import { logger } from "../../utils/index2.js";
import "../../vendors/nice-fns/dist/compactObject.js";
import "../../vendors/nice-fns/dist/pascalCase.js";
import { ref } from "vue";
import castArray from "../../vendors/lodash-es/castArray.js";
const AUTH_ID = Symbol("auth");
class Auth {
constructor(options = {}) {
__publicField(this, "id", AUTH_ID);
/**
* 授权指令
*/
__publicField(this, "directive");
/**
* 授权列表
*/
__publicField(this, "_list", ref([]));
/**
* 未授权时是否允许提示
*/
__publicField(this, "_allowTip", true);
/**
* 授权
* @param list 授权列表
*
* @example
* ```ts
* // 设置用户权限编码列表
* fetchUser().then((user) => auth.empower(user.permissions))
*
* function fetchUser() {
* return Promise.resolve({ id: 1, name: 'admin', permissions: ['list:add', 'list:edit'] })
* }
* ```
*/
__publicField(this, "empower", (list) => {
this._list.value = list;
if (this._allowTip)
this._allowTip = false;
});
/**
* 验证功能权限
* @param codes 功能列表
* @param op 操作符
*
* @example
* ```ts
* // 单功能鉴权
* auth.verify('list:add')
*
* // 多功能鉴权,满足单一功能编码
* auth.verify(['list:add', 'list:edit'], 'or')
*
* // 多功能鉴权,需同时满足所有功能编码
* auth.verify(['list:add', 'list:edit'], 'and')
* ```
*/
__publicField(this, "verify", (codes, op = "or") => {
if (this.list === "*")
return true;
codes = castArray(codes);
if (codes.length === 0)
return false;
if (this.list.length === 0 && this._allowTip)
logger.warn("暂未设置授权列表!");
const set = new Set(this.list);
return codes[op === "and" ? "every" : "some"](set.has.bind(set));
});
__publicField(this, "install", (sdk) => {
const { directiveName = "auth" } = this.options;
sdk.app.directive(directiveName, this.directive);
sdk.hook("sdk:cleanup", () => this.empower([]));
});
this.options = options;
const auth = this;
this.directive = {
mounted(el, binding) {
const { value, arg } = binding;
if (!auth.verify(value, arg))
el.remove();
}
};
}
/**
* 授权列表
* @readonly
*/
get list() {
return this._list.value;
}
}
export {
AUTH_ID,
Auth
};