import Module from '../Module.ts' import Kernel from '../Kernel.ts' import {Request} from '../../Request.ts' import SetSessionCookie from './SetSessionCookie.ts' import SessionManager from '../../session/SessionManager.ts' import {Logging} from '../../../service/logging/Logging.ts' import {Injectable} from '../../../../../di/src/decorator/Injection.ts' /** * HTTP kernel module to retrieve and inject the session into the request. * @extends Module */ @Injectable() export default class InjectSession extends Module { public static register(kernel: Kernel) { kernel.register(this).after(SetSessionCookie) } constructor( protected readonly sessions: SessionManager, protected readonly logger: Logging, ) { super() } /** * Lookup or create the session object and inject it into the request. * @param {Request} request */ public async apply(request: Request): Promise { if ( request.session ) return request let key: string | undefined try { const result = await request.cookies.get('daton.session') key = result?.value } catch (e) { this.logger.error('Invalid Daton session cookie. The session will not be injected.') try { this.logger.debug(`Cookie: ${await request.cookies.get_raw('daton.session')}`) } catch (e2) {} this.logger.debug(e) return request } if ( !key ) { this.logger.warn(`No session key was found. Is the SetSessionCookie module registered?`) return request } const has_existing = await this.sessions.has_session(key) if ( has_existing ) { request.session = await this.sessions.get_session(key) return request } const new_session = await this.sessions.get_session() this.logger.verbose(`Populating new session: ${key}`) new_session.set_key(key) await new_session.persist() request.session = new_session return request } }