@avonjs/avonjs
Version:
A fluent Node.js API generator.
97 lines (96 loc) • 3.27 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const Exceptions_1 = require("../Exceptions");
exports.default = (Parent) => {
class Authorizable extends Parent {
/**
* Determine if the current user has a given ability or throw exception.
* @throws {ForbiddenException}
*/
async authorizeTo(request, ability, args = []) {
Exceptions_1.ForbiddenException.unless(await this.authorizedTo(request, ability, args));
}
/**
* Determine if the current user has a given ability.
*/
async authorizedTo(request, ability, args = []) {
const authorizationCallback = this[this.makeAuthorizationCallback(ability)];
return this.authorizable() && typeof authorizationCallback === 'function'
? authorizationCallback.apply(this, [request, ...args])
: Promise.resolve(true);
}
/**
* Determine if need to perform authorization.
*/
authorizable() {
return true;
}
/**
* Guess custom authorization callback name for the given ability.
*/
makeAuthorizationCallback(ability) {
return `authorizedTo${ability[0].toUpperCase()}${ability.substring(1)}`;
}
/**
* Determine if the current user has ability to `viewAny` a resource.
*/
async authorizedToViewAny(request) {
return true;
}
/**
* Determine if the current user has ability to `view` a resource.
*/
async authorizedToView(request) {
return true;
}
/**
* Determine if the current user has ability to `create` a resource.
*/
async authorizedToCreate(request) {
return true;
}
/**
* Determine if the current user has ability to `update` a resource.
*/
async authorizedToUpdate(request) {
return true;
}
/**
* Determine if the current user has ability to `delete` a resource.
*/
async authorizedToDelete(request) {
return true;
}
/**
* Determine if the current user has ability to `forceDelete` a resource.
*/
async authorizedToForceDelete(request) {
return true;
}
/**
* Determine if the current user has ability to `restore` a resource.
*/
async authorizedToRestore(request) {
return true;
}
/**
* Determine if the current user has ability to `add` a resource to the current resource.
*/
async authorizedToAdd(request, resource) {
return true;
}
/**
* Determine if the current user has ability to `attach` a resource to the current resource.
*/
async authorizedToAttach(request, resource) {
return true;
}
/**
* Determine if the current user has ability to `detach` a resource from the current resource.
*/
async authorizedToDetach(request, resource) {
return true;
}
}
return Authorizable;
};