datasquirel/package-shared/functions/backend/cookies/get-auth-cookie-names.js

44 lines
1.5 KiB
JavaScript
Raw Normal View History

2024-12-08 08:58:57 +00:00
// @ts-check
/**
* # Grab Auth Cookie Names
*
* @param {object} [params]
* @param {string} [params.database]
* @param {string | number} [params.userId]
*
2024-12-10 14:10:32 +00:00
* @returns {{ keyCookieName: string, csrfCookieName: string, oneTimeCodeName: string }}
2024-12-08 08:58:57 +00:00
*/
module.exports = function getAuthCookieNames(params) {
2024-12-06 10:31:24 +00:00
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";
2024-12-10 14:10:32 +00:00
const cookieOneTimeCodeName =
process.env.DSQL_COOKIES_ONE_TIME_CODE_NAME || "one-time-code";
2024-12-06 10:31:24 +00:00
2024-12-09 11:45:39 +00:00
const targetDatabase =
2024-12-10 18:44:59 +00:00
params?.database?.replace(/^datasquirel_user_\d+_/, "") ||
2024-12-09 11:45:39 +00:00
process.env.DSQL_DB_NAME?.replace(/^datasquirel_user_\d+_/, "");
2024-12-08 08:58:57 +00:00
let keyCookieName = cookiesPrefix;
if (params?.userId) keyCookieName += `user_${params.userId}_`;
2024-12-09 11:45:39 +00:00
if (targetDatabase) keyCookieName += `${targetDatabase}_`;
2024-12-08 08:58:57 +00:00
keyCookieName += cookiesKeyName;
let csrfCookieName = cookiesPrefix;
if (params?.userId) csrfCookieName += `user_${params.userId}_`;
2024-12-09 11:45:39 +00:00
if (targetDatabase) csrfCookieName += `${targetDatabase}_`;
2024-12-08 08:58:57 +00:00
csrfCookieName += cookiesCSRFName;
2024-12-06 10:31:24 +00:00
2024-12-10 14:10:32 +00:00
let oneTimeCodeName = cookiesPrefix;
if (params?.userId) oneTimeCodeName += `user_${params.userId}_`;
if (targetDatabase) oneTimeCodeName += `${targetDatabase}_`;
oneTimeCodeName += cookieOneTimeCodeName;
2024-12-06 10:31:24 +00:00
return {
keyCookieName,
csrfCookieName,
2024-12-10 14:10:32 +00:00
oneTimeCodeName,
2024-12-06 10:31:24 +00:00
};
};