2020-07-28 00:48:44 +00:00
|
|
|
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'
|
|
|
|
|
2020-08-16 19:31:47 +00:00
|
|
|
/**
|
|
|
|
* HTTP kernel module to retrieve and inject the session into the request.
|
|
|
|
* @extends Module
|
|
|
|
*/
|
2020-07-28 00:48:44 +00:00
|
|
|
@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()
|
|
|
|
}
|
|
|
|
|
2020-08-16 19:31:47 +00:00
|
|
|
/**
|
|
|
|
* Lookup or create the session object and inject it into the request.
|
|
|
|
* @param {Request} request
|
|
|
|
*/
|
2020-07-28 00:48:44 +00:00
|
|
|
public async apply(request: Request): Promise<Request> {
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|