import {Container} from '../di' import {RequestLocalStorage} from '../http/RequestLocalStorage' import {Session} from '../http/session/Session' import {Logging} from '../service/Logging' import {SecurityContext} from './context/SecurityContext' import {Bus} from '../support/bus' import {AuthCheckFailed} from './event/AuthCheckFailed' /** * Check if the security context for the current request's web socket is still valid. * If not, raise an `AuthCheckFailed` event. This is meant to be used as a subscriber * to `WebSocketHealthCheckEvent` on the request. * * @see AuthCheckFailed */ export async function webSocketAuthCheck(): Promise { const request = Container.getContainer() .make(RequestLocalStorage) .get() const logging = request.make(Logging) try { // Try to re-load the session in case we're using the SessionSecurityContext await request.make(Session).load() } catch (e: unknown) { logging.error(e) } const security = request.make(SecurityContext) await security.resume() if ( !security.hasUser() ) { await request.make(Bus).push(new AuthCheckFailed()) } }