import {Middleware} from '../../http/routing/Middleware' import {ResponseObject} from '../../http/routing/Route' import {OAuth2Token} from '../server/types' import {HTTPError} from '../../http/HTTPError' import {HTTPStatus, Pipeline} from '../../util' import {Request} from '../../http/lifecycle/Request' import {Constructable, Container} from '../../di' export class ScopeRequiredMiddleware extends Middleware { constructor( protected readonly request: Request, protected readonly scope: string, ) { super(request) } apply(): ResponseObject { if ( !this.request.hasInstance(OAuth2Token) ) { throw new HTTPError(HTTPStatus.UNAUTHORIZED, 'Must specify an OAuth2 token.') } const token: OAuth2Token = this.request.getExistingInstance(OAuth2Token) if ( typeof token.scope !== 'undefined' && token.scope !== this.scope ) { throw new HTTPError(HTTPStatus.UNAUTHORIZED, 'Insufficient token permissions (requires: ' + this.scope + ')') } } } export const scope = (name: string): Constructable => { return new Pipeline( container => container.make(ScopeRequiredMiddleware, container, name), ) }