import {Middleware} from '../../http/routing/Middleware' import {Inject, Injectable, Instantiable} from '../../di' import {Config} from '../../service/Config' import {Logging} from '../../service/Logging' import {AuthenticatableRepository} from '../types' import {Maybe} from '../../util' import {AuthenticationConfig, isAuthenticationConfig} from '../config' import {ResponseObject} from '../../http/routing/Route' import {SessionSecurityContext} from '../context/SessionSecurityContext' import {SecurityContext} from '../context/SecurityContext' /** * 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 @Inject() protected readonly logging!: Logging async apply(): Promise { this.logging.debug('Applying session auth middleware.') const context = 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: Maybe = this.config.get('auth') if ( !isAuthenticationConfig(config) ) { throw new TypeError('Invalid authentication config.') } const repo: Instantiable = config.storage return this.make(repo) } }