datasquirel/package-shared/functions/backend/cookies/get-auth-cookie-names.ts
2025-01-10 20:10:28 +01:00

47 lines
1.5 KiB
TypeScript

type Param = {
database?: string;
userId?: string | number;
};
type Return = {
keyCookieName: string;
csrfCookieName: string;
oneTimeCodeName: string;
};
/**
* # Grab Auth Cookie Names
*/
export default function getAuthCookieNames(params?: Param): Return {
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?.replace(/^datasquirel_user_\d+_/, "") ||
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,
};
}