UNPKG

@powership/server

Version:
52 lines 1.41 kB
import httpErrors from 'http-errors'; import { BaseRequestHandler } from "./BaseRequestHandler.mjs"; import { ServerLogs } from "./ServerLogs.mjs"; const { Unauthorized } = httpErrors; export let __LOCAL_DEV_USERID__ = process.env.NODE_ENV === 'development' ? '__LOCAL_DEV_USERID__' : null; export class ServerRequest extends BaseRequestHandler { constructor(input) { super(input); this.input = input; const { locals = {}, userId, permissions = [] } = input; this.locals = locals; this._userId = userId; this._permissions = new Set(permissions); } getPermissions = () => { return [...this._permissions.values()]; }; userIdOptional() { return this._userId || __LOCAL_DEV_USERID__ || undefined; } assertPermission(permission) { const userId = this.userId(); if (this.hasPermission(permission)) return true; ServerLogs.error('Unauthorized', { userId, permission }); throw new Unauthorized(); } hasPermission(permission) { if (__LOCAL_DEV_USERID__) return true; return this._permissions.has(permission); } userId(strict = true) { const userId = this.userIdOptional(); if (userId) return userId; if (strict) { throw new Unauthorized(); } return ''; } static create = input => { return new ServerRequest(input); }; } //# sourceMappingURL=ServerRequest.mjs.map