import {SecurityContext} from './SecurityContext' import {Inject, Injectable} from '../../di' import {Session} from '../../http/session/Session' import {Awaitable} from '../../util' import {AuthenticatableRepository} from '../types' import {UserAuthenticationResumedEvent} from '../event/UserAuthenticationResumedEvent' export const EXTOLLO_AUTH_SESSION_KEY = '@extollo:auth.securityIdentifier' /** * Security context implementation that uses the session as storage. */ @Injectable() export class SessionSecurityContext extends SecurityContext { @Inject() protected readonly session!: Session constructor( /** The repository from which to draw users. */ public readonly repository: AuthenticatableRepository, ) { super(repository, 'session') } persist(): Awaitable { this.session.set(EXTOLLO_AUTH_SESSION_KEY, this.getUser()?.getIdentifier()) } async resume(): Promise { const identifier = this.session.get(EXTOLLO_AUTH_SESSION_KEY) if ( identifier ) { const user = await this.repository.getByIdentifier(identifier) if ( user ) { this.authenticatedUser = user await this.bus.push(new UserAuthenticationResumedEvent(user, this)) return } } this.authenticatedUser = undefined } }