35 lines
1.3 KiB
TypeScript
35 lines
1.3 KiB
TypeScript
|
import {Middleware} from '../../http/routing/Middleware'
|
||
|
import {Inject, Injectable} from '../../di'
|
||
|
import {ResponseObject} from '../../http/routing/Route'
|
||
|
import {Config} from '../../service/Config'
|
||
|
import {AuthenticatableRepository} from '../types'
|
||
|
import {SessionSecurityContext} from '../contexts/SessionSecurityContext'
|
||
|
import {SecurityContext} from '../SecurityContext'
|
||
|
import {ORMUserRepository} from '../orm/ORMUserRepository'
|
||
|
import {AuthConfig} from '../config'
|
||
|
|
||
|
/**
|
||
|
* Injects a SessionSecurityContext into the request and attempts to
|
||
|
* resume the user's authentication.
|
||
|
*/
|
||
|
@Injectable()
|
||
|
export class SessionAuthMiddleware extends Middleware {
|
||
|
@Inject()
|
||
|
protected readonly config!: Config
|
||
|
|
||
|
async apply(): Promise<ResponseObject> {
|
||
|
const context = <SessionSecurityContext> this.make(SessionSecurityContext, this.getRepository())
|
||
|
this.request.registerSingletonInstance(SecurityContext, context)
|
||
|
await context.resume()
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Build the correct AuthenticatableRepository based on the auth config.
|
||
|
* @protected
|
||
|
*/
|
||
|
protected getRepository(): AuthenticatableRepository {
|
||
|
const config: AuthConfig | undefined = this.config.get('auth')
|
||
|
return this.make<AuthenticatableRepository>(config?.repositories?.session ?? ORMUserRepository)
|
||
|
}
|
||
|
}
|