UNPKG

nralcm

Version:

This is a framework based on NodeJs to manage rest api request lifecycle

49 lines (48 loc) 2.06 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); require("reflect-metadata/Reflect"); const exceptions_1 = require("../../exceptions"); const __1 = require(".."); /** * Handler to process authentication * and authorization */ class AuthHandler { constructor(restApiConfiguration) { this.restApiConfiguration = restApiConfiguration; } /** * Method to process authentication * and authorization * @param context HttpContext Object */ handle(context) { let authorize = Reflect.getMetadata(__1.Constants.metadata.authorize, context.controller); if (!authorize) { authorize = Reflect.getMetadata(__1.Constants.metadata.authorize, context.controller, context.routeDescriptor.methodName); } if (authorize && this.restApiConfiguration.AuthenticationFilter) { const authResult = this.restApiConfiguration.AuthenticationFilter.authenticate(context); if (!authResult) { if (!context.response.headersSent) { throw new exceptions_1.UnAuthenticateException(); } } else { if (authorize.roles && authorize.roles.length > 0 && this.restApiConfiguration.AuthorizeFilter) { if (context.user && context.user.isAuthenticated) { const isAuthorized = this.restApiConfiguration.AuthorizeFilter.authorize(context, authorize.roles); if (!isAuthorized && !context.response.headersSent) { throw new exceptions_1.UnAuthorizeException(); } } else { context.response.type("application/json").status(500).send({ message: "HttpContext.user is null. Create a new class and extend AuthPrinciple. Inject object of class in HttpContext.user." }); } } } } return true; } } exports.AuthHandler = AuthHandler;