citeright-sdk-js
Version:
An SDK to connect to the CiteRight API.
105 lines (104 loc) • 3.51 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var ACL = /** @class */ (function () {
function ACL() {
this.rules = {};
}
/**
* This will get a string of abilities as a JSON encoded object. You can safely store this and use it later
* in "importAbilities" to reconstitute an ACL with abilities.
*
* @returns {string}
*/
ACL.prototype.exportAbilities = function () {
return JSON.stringify(this.rules);
};
/**
* Use this to reconstitute a users abilities from a string that was exported from "exportAbilities".
*
* @param {string} abilities
*/
ACL.prototype.importAbilities = function (abilities) {
this.rules = JSON.parse(abilities);
};
/**
* Use this to verify that a use has an ability.
*
* @param {string} action
* @param {string} subject
* @param filter
* @returns {boolean}
*/
ACL.prototype.can = function (action, subject, filter) {
if (!this.rules[action] || !this.rules[action][subject]) {
return false;
}
var oneMatch = false;
var result;
for (var _i = 0, _a = this.rules[action][subject]; _i < _a.length; _i++) {
var rule = _a[_i];
if (!oneMatch) {
if (rule.filter === "*") {
oneMatch = true;
result = rule.can;
}
else if (typeof rule.filter === "string") {
if (rule.filter === filter) {
oneMatch = true;
result = rule.can;
}
}
else if (typeof rule.filter === "object") {
for (var _b = 0, _c = Object.keys(rule.filter); _b < _c.length; _b++) {
var key = _c[_b];
if (rule.filter[key] === filter[key]) {
oneMatch = true;
result = rule.can;
}
}
}
}
}
if (oneMatch) {
return result;
}
else {
return false;
}
};
/**
* Use this to get an array of security roles available to the connected user.
*
* @returns {string[]}
*/
ACL.prototype.getManagableRoles = function () {
var manageableRoles = [];
var abilities = this.rules;
if (abilities && abilities.ASSIGN) {
for (var _i = 0, _a = abilities.ASSIGN.ROLE; _i < _a.length; _i++) {
var role = _a[_i];
if (role.can) {
manageableRoles.push(role.filter);
}
}
}
return manageableRoles;
};
/**
* Use this if you want to throw an error upon failure of a ACL ability check. You can optionally provide a custom
* message. In any case, an Error is thrown.
*
* @param {string} action
* @param {string} subject
* @param filter
* @param {string} message
*/
ACL.prototype.throwUnless = function (action, subject, filter, message) {
message = message ? message : "Permission Error";
if (!this.can(action, subject, filter)) {
throw new Error(message);
}
};
return ACL;
}());
exports.ACL = ACL;