2021-06-05 18:24:12 +00:00
|
|
|
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'
|
2021-06-18 00:35:31 +00:00
|
|
|
import {AuthConfig, AuthenticatableRepositories} from '../config'
|
2021-06-29 05:34:05 +00:00
|
|
|
import {Logging} from '../../service/Logging'
|
2021-06-05 18:24:12 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 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
|
|
|
|
|
2021-06-29 05:34:05 +00:00
|
|
|
@Inject()
|
|
|
|
protected readonly logging!: Logging
|
|
|
|
|
2021-06-05 18:24:12 +00:00
|
|
|
async apply(): Promise<ResponseObject> {
|
2021-06-29 05:34:05 +00:00
|
|
|
this.logging.debug('Applying session auth middleware...')
|
2021-06-05 18:24:12 +00:00
|
|
|
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')
|
2021-06-18 00:35:31 +00:00
|
|
|
const repo: typeof AuthenticatableRepository = AuthenticatableRepositories[config?.repositories?.session ?? 'orm']
|
|
|
|
return this.make<AuthenticatableRepository>(repo ?? ORMUserRepository)
|
2021-06-05 18:24:12 +00:00
|
|
|
}
|
|
|
|
}
|