Support periodic auth checks in SecurityContext on web socket connections
This commit is contained in:
36
src/auth/webSocketAuthCheck.ts
Normal file
36
src/auth/webSocketAuthCheck.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
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<void> {
|
||||
const request = Container.getContainer()
|
||||
.make<RequestLocalStorage>(RequestLocalStorage)
|
||||
.get()
|
||||
|
||||
const logging = request.make<Logging>(Logging)
|
||||
|
||||
try {
|
||||
// Try to re-load the session in case we're using the SessionSecurityContext
|
||||
await request.make<Session>(Session).load()
|
||||
} catch (e: unknown) {
|
||||
logging.error(e)
|
||||
}
|
||||
|
||||
const security = request.make<SecurityContext>(SecurityContext)
|
||||
await security.resume()
|
||||
|
||||
if ( !security.hasUser() ) {
|
||||
await request.make<Bus>(Bus).push(new AuthCheckFailed())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user