livebook/assets/js/lib/user.js
2023-04-28 14:50:40 +02:00

51 lines
1.2 KiB
JavaScript

import { decodeBase64, encodeBase64 } from "./utils";
const USER_DATA_COOKIE = "lb:user_data";
/**
* Stores user data in the `"lb:user_data"` cookie.
*/
export function storeUserData(userData) {
const json = JSON.stringify(userData);
const encoded = encodeBase64(json);
setCookie(USER_DATA_COOKIE, encoded, 157_680_000); // 5 years
}
/**
* Loads user data from the `"lb:user_data"` cookie.
*/
export function loadUserData() {
const encoded = getCookieValue(USER_DATA_COOKIE);
if (encoded) {
const json = decodeBase64(encoded);
return JSON.parse(json);
} else {
return null;
}
}
function getCookieValue(key) {
const cookie = document.cookie
.split("; ")
.find((cookie) => cookie.startsWith(`${key}=`));
if (cookie) {
const value = cookie.replace(`${key}=`, "");
return value;
} else {
return null;
}
}
function setCookie(key, value, maxAge) {
const cookie = `${key}=${value};max-age=${maxAge};path=/${cookieOptions()}`;
document.cookie = cookie;
}
function cookieOptions() {
if (document.body.hasAttribute("data-within-iframe")) {
return ";SameSite=None;Secure";
} else {
return ";SameSite=Lax";
}
}