UNPKG

@inv2/common

Version:

A common module for v2

66 lines (65 loc) 2.94 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Authentication = void 0; const unauthorized_error_1 = require("../errors/unauthorized-error"); const services_1 = require("../services"); const errors_1 = require("../errors"); class Authentication { static authorize(roles = []) { if (!Array.isArray(roles) || roles.length <= 0) throw new unauthorized_error_1.UnauthorizedError(); if (roles.length === 1 && roles.includes('*')) { roles = ['TENANT_ADMIN', 'SUPER_ADMIN', 'USER', 'CUSTOMER']; } return (req, res, next) => __awaiter(this, void 0, void 0, function* () { const userTenantRole = req === null || req === void 0 ? void 0 : req.currentUser; if (!userTenantRole || !userTenantRole.Tenant[0]) throw new unauthorized_error_1.UnauthorizedError(); const tenant = userTenantRole.Tenant[0]; // const roles = tenant.Roles as RoleDto[]; let allowed = false; for (const role of tenant.Roles) { if (roles.includes(role.name)) allowed = true; } if (allowed) return next(); // if(!roles.includes(userTenantRole!.Tenant![0]?.Role![0] || '')) throw new UnauthorizedError(); throw new unauthorized_error_1.UnauthorizedError(); }); } } exports.Authentication = Authentication; Authentication.currentUser = (req, res, next) => { if (!req.headers['authorization']) { return next(); } try { let token = req.headers['authorization']; if (token.startsWith('Bearer ') || token.startsWith('bearer ')) { token = token.slice(7, token.length); } const jwtToken = services_1.JWTService.verifyJWTToken(token, process.env.ACCESS_TOKEN_SECRET); if (!jwtToken || !jwtToken.success) throw new errors_1.Exception(jwtToken); const payload = jwtToken.data; req.currentUser = payload; } catch (error) { } next(); }; Authentication.requireAuth = (req, res, next) => { if (!req.currentUser) { throw new unauthorized_error_1.UnauthorizedError(); } next(); };