mirror of
https://github.com/livebook-dev/livebook.git
synced 2024-11-15 12:25:31 +08:00
51 lines
1.2 KiB
JavaScript
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";
|
|
}
|
|
}
|