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.
46 lines
1.6 KiB
46 lines
1.6 KiB
2 years ago
|
import {Middleware} from '../../http/routing/Middleware'
|
||
|
import {Inject, Injectable} from '../../di'
|
||
|
import {Config} from '../../service/Config'
|
||
|
import {Logging} from '../../service/Logging'
|
||
|
import {AuthenticatableRepository} from '../types'
|
||
|
import {ResponseObject} from '../../http/routing/Route'
|
||
|
import {SecurityContext} from '../context/SecurityContext'
|
||
|
import {TokenSecurityContext} from '../context/TokenSecurityContext'
|
||
|
import {OAuth2Token, oauth2TokenString, TokenRepository} from '../server/types'
|
||
|
|
||
|
/**
|
||
|
* Injects a TokenSecurityContext into the request and attempts to
|
||
|
* resume the user's authentication.
|
||
|
*/
|
||
|
@Injectable()
|
||
|
export class TokenAuthMiddleware extends Middleware {
|
||
|
@Inject()
|
||
|
protected readonly config!: Config
|
||
|
|
||
|
@Inject()
|
||
|
protected readonly logging!: Logging
|
||
|
|
||
|
@Inject()
|
||
|
protected readonly tokens!: TokenRepository
|
||
|
|
||
|
async apply(): Promise<ResponseObject> {
|
||
|
this.logging.debug('Applying token auth middleware.')
|
||
|
let tokenString = this.request.getHeader('Authorization')
|
||
|
if ( Array.isArray(tokenString) ) {
|
||
|
tokenString = tokenString[0]
|
||
|
}
|
||
|
|
||
|
if ( tokenString ) {
|
||
|
const token = await this.tokens.decode(oauth2TokenString(tokenString))
|
||
|
if ( token ) {
|
||
|
this.request.registerSingletonInstance(OAuth2Token, token)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
const repo = <AuthenticatableRepository> this.make(AuthenticatableRepository)
|
||
|
const context = <TokenSecurityContext> this.make(TokenSecurityContext, repo)
|
||
|
this.request.registerSingletonInstance(SecurityContext, context)
|
||
|
await context.resume()
|
||
|
}
|
||
|
}
|