You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
34 lines
1.2 KiB
34 lines
1.2 KiB
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<ScopeRequiredMiddleware> => {
|
|
return new Pipeline<Container, ScopeRequiredMiddleware>(
|
|
container => container.make(ScopeRequiredMiddleware, container, name),
|
|
)
|
|
}
|