datasquirel/package-shared/functions/backend/cookies/get-auth-cookie-names.js
Benjamin Toby 04a4452821 Updates
2024-12-10 15:10:32 +01:00

44 lines
1.5 KiB
JavaScript

// @ts-check
/**
* # Grab Auth Cookie Names
*
* @param {object} [params]
* @param {string} [params.database]
* @param {string | number} [params.userId]
*
* @returns {{ keyCookieName: string, csrfCookieName: string, oneTimeCodeName: string }}
*/
module.exports = function getAuthCookieNames(params) {
const cookiesPrefix = process.env.DSQL_COOKIES_PREFIX || "dsql_";
const cookiesKeyName = process.env.DSQL_COOKIES_KEY_NAME || "key";
const cookiesCSRFName = process.env.DSQL_COOKIES_CSRF_NAME || "csrf";
const cookieOneTimeCodeName =
process.env.DSQL_COOKIES_ONE_TIME_CODE_NAME || "one-time-code";
const targetDatabase =
params?.database ||
process.env.DSQL_DB_NAME?.replace(/^datasquirel_user_\d+_/, "");
let keyCookieName = cookiesPrefix;
if (params?.userId) keyCookieName += `user_${params.userId}_`;
if (targetDatabase) keyCookieName += `${targetDatabase}_`;
keyCookieName += cookiesKeyName;
let csrfCookieName = cookiesPrefix;
if (params?.userId) csrfCookieName += `user_${params.userId}_`;
if (targetDatabase) csrfCookieName += `${targetDatabase}_`;
csrfCookieName += cookiesCSRFName;
let oneTimeCodeName = cookiesPrefix;
if (params?.userId) oneTimeCodeName += `user_${params.userId}_`;
if (targetDatabase) oneTimeCodeName += `${targetDatabase}_`;
oneTimeCodeName += cookieOneTimeCodeName;
return {
keyCookieName,
csrfCookieName,
oneTimeCodeName,
};
};