UNPKG

jsm-core

Version:
50 lines (49 loc) 2 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()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const jsm_exceptions_1 = __importDefault(require("jsm-exceptions")); /** * Attach user to req.currentUser * @param {*} req Express req Object * @param {*} res Express res Object * @param {*} next Express next Function */ const requireUser = (req, res, next) => __awaiter(void 0, void 0, void 0, function* () { var _a; try { /** * Always pass if another service is authenticated */ if (req.attached_entities.service) return next(); /** * Handle JWT token expired */ if (req.jwt_expired) throw new jsm_exceptions_1.default.JWTTokenExpired('JWT token expired'); /** * The condition logic */ if (!((_a = req.attached_entities.user) === null || _a === void 0 ? void 0 : _a._id)) throw new jsm_exceptions_1.default.UnauthorizedException('You must be logged in to access this resource'); /** * Condition fulfilled */ return next(); } catch (error) { return next(error); } }); exports.default = requireUser;