@foal/core
Version:
Full-featured Node.js framework, with no complexity
51 lines (50 loc) • 2.18 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.setSessionCookie = setSessionCookie;
// FoalTS
const core_1 = require("../../../core");
const constants_1 = require("../constants");
/**
* Sends the session token in a cookie.
*
* If the CSRF protection is enabled, it also sends the CSRF token in a CSRF cookie.
*
* If a "user" argument is provided, it also sends its value in a "user" cookie.
*
* @export
* @param {HttpResponse} response - The HTTP response.
* @param {Session} session - The session object.
* @param {string} [user] - The content of the "user" cookie if any.
*/
function setSessionCookie(response, session, user) {
const cookieName = core_1.Config.get('settings.session.cookie.name', 'string', constants_1.SESSION_DEFAULT_COOKIE_NAME);
const csrfEnabled = core_1.Config.get('settings.session.csrf.enabled', 'boolean', false);
let sameSite = core_1.Config.get('settings.session.cookie.sameSite', 'string');
if (csrfEnabled && sameSite === undefined) {
sameSite = constants_1.SESSION_DEFAULT_SAME_SITE_ON_CSRF_ENABLED;
}
const options = {
domain: core_1.Config.get('settings.session.cookie.domain', 'string'),
expires: new Date(session.expirationTime * 1000),
path: core_1.Config.get('settings.session.cookie.path', 'string', constants_1.SESSION_DEFAULT_COOKIE_PATH),
sameSite,
secure: core_1.Config.get('settings.session.cookie.secure', 'boolean')
};
response.setCookie(cookieName, session.getToken(), {
...options,
httpOnly: core_1.Config.get('settings.session.cookie.httpOnly', 'boolean', constants_1.SESSION_DEFAULT_COOKIE_HTTP_ONLY),
});
if (csrfEnabled) {
const csrfCookieName = core_1.Config.get('settings.session.csrf.cookie.name', 'string', constants_1.SESSION_DEFAULT_CSRF_COOKIE_NAME);
response.setCookie(csrfCookieName, session.get('csrfToken') || '', {
...options,
httpOnly: false,
});
}
if (user) {
response.setCookie(constants_1.SESSION_USER_COOKIE_NAME, user, {
...options,
httpOnly: false,
});
}
}