UNPKG

nestjs-roles

Version:

Create custom roles guard and decorator

44 lines 1.4 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.checkRoles = checkRoles; const common_1 = require("@nestjs/common"); function checkRoles(requiredRoles, role) { // handler is allowed only for not authorized if (requiredRoles[0] === false) { // but there is some role if (role) { throw new common_1.ForbiddenException(); } return true; } // handler is allowed for any authorized if (requiredRoles[0] === true) { // but there is not any role if (!role) { throw new common_1.UnauthorizedException(); } return true; } // handler is allowed for certain roles // there is no any role if (!role) { throw new common_1.UnauthorizedException(); } // check if role is not one of requireds // if role is array of roles // guard will pass if one of roles is in required roles if (Array.isArray(role)) { if (!requiredRoles.some((requiredRole) => role.includes(requiredRole))) { throw new common_1.ForbiddenException(); } } else { // if role is single role // guard will pass if role is in required roles if (!requiredRoles.includes(role)) { throw new common_1.ForbiddenException(); } } return true; } //# sourceMappingURL=check-roles.js.map