lib/src/http/kernel/module/InjectSessionHTTPModule.ts

37 lines
1.2 KiB
TypeScript
Raw Normal View History

2021-06-03 03:36:25 +00:00
import {HTTPKernelModule} from '../HTTPKernelModule'
import {Injectable} from '../../../di'
import {ErrorWithContext} from '../../../util'
import {HTTPKernel} from '../HTTPKernel'
import {Request} from '../../lifecycle/Request'
import {SetSessionCookieHTTPModule} from './SetSessionCookieHTTPModule'
import {SessionFactory} from '../../session/SessionFactory'
import {Session} from '../../session/Session'
2021-03-07 19:26:14 +00:00
2021-03-25 13:50:13 +00:00
/**
* HTTP kernel middleware that creates the session using the configured driver
* and loads its data using the request's session cookie.
*/
2021-03-07 19:26:14 +00:00
@Injectable()
export class InjectSessionHTTPModule extends HTTPKernelModule {
2021-03-09 15:42:19 +00:00
public readonly executeWithBlockingWriteback = true
2021-06-03 03:36:25 +00:00
public static register(kernel: HTTPKernel): void {
2021-03-07 19:26:14 +00:00
kernel.register(this).after(SetSessionCookieHTTPModule)
}
2021-06-03 03:36:25 +00:00
public async apply(request: Request): Promise<Request> {
2021-03-07 19:26:14 +00:00
request.registerFactory(new SessionFactory())
const session = <Session> request.make(Session)
const id = request.cookies.get('extollo.session')
if ( !id ) {
throw new ErrorWithContext('Session ID has not been set. Cannot inject session!')
}
session.setKey(id.value)
await session.load()
return request
}
}