Files
saas_frontend/src/lib/authCookies.ts
T

50 lines
1.4 KiB
TypeScript

const LOGGED_IN_KEY = "logged_in";
const LOGGED_IN_MAX_AGE_SECONDS = 60 * 15;
const buildCookieOptions = (maxAgeSeconds?: number) => {
const options = ["path=/", "samesite=lax"];
if (typeof maxAgeSeconds === "number") {
options.push(`max-age=${maxAgeSeconds}`);
}
if (window.location.protocol === "https:") {
options.push("secure");
}
return options.join("; ");
};
const setCookie = (name: string, value: string, maxAgeSeconds?: number) => {
const encodedValue = encodeURIComponent(value);
document.cookie = `${name}=${encodedValue}; ${buildCookieOptions(maxAgeSeconds)}`;
};
const deleteCookie = (name: string) => {
document.cookie = `${name}=; ${buildCookieOptions(0)}`;
};
export const getCookie = (name: string) => {
const cookies = document.cookie.split(";").map((cookie) => cookie.trim());
const match = cookies.find((cookie) => cookie.startsWith(`${name}=`));
if (!match) {
return null;
}
const rawValue = match.substring(name.length + 1);
return decodeURIComponent(rawValue);
};
export const setAuthCookies = (_tokens: unknown, rememberMe = false) => {
const maxAge = rememberMe ? LOGGED_IN_MAX_AGE_SECONDS : undefined;
setCookie(LOGGED_IN_KEY, "1", maxAge);
};
export const clearAuthCookies = () => {
deleteCookie(LOGGED_IN_KEY);
};
export const refreshLoggedInFlag = () => {
setCookie(LOGGED_IN_KEY, "1", LOGGED_IN_MAX_AGE_SECONDS);
};
export const getAccessToken = () => getCookie(LOGGED_IN_KEY);