Files
data-entry-app/frontend/src/lib/session.ts
T

79 lines
1.7 KiB
TypeScript
Raw Normal View History

2026-04-25 20:43:37 +12:00
import { browser } from '$app/environment';
import { writable } from 'svelte/store';
2026-04-25 22:51:36 +12:00
export type AppSession = {
2026-04-25 20:43:37 +12:00
name: string;
email: string;
role: string;
2026-04-25 22:51:36 +12:00
token: string;
tenant_id?: string | null;
2026-04-25 20:43:37 +12:00
};
2026-04-25 22:51:36 +12:00
const CLIENT_STORAGE_KEY = 'data-entry-app-client-session';
const ADMIN_STORAGE_KEY = 'data-entry-app-admin-session';
2026-04-25 20:43:37 +12:00
2026-04-25 22:51:36 +12:00
function readStoredSession(storageKey: string): AppSession | null {
2026-04-25 20:43:37 +12:00
if (!browser) {
return null;
}
2026-04-25 22:51:36 +12:00
const value = localStorage.getItem(storageKey);
2026-04-25 20:43:37 +12:00
if (!value) {
return null;
}
try {
2026-04-25 22:51:36 +12:00
return JSON.parse(value) as AppSession;
2026-04-25 20:43:37 +12:00
} catch {
2026-04-25 22:51:36 +12:00
localStorage.removeItem(storageKey);
2026-04-25 20:43:37 +12:00
return null;
}
}
2026-04-25 22:51:36 +12:00
function createSessionStore(storageKey: string) {
const store = writable<AppSession | null>(readStoredSession(storageKey));
2026-04-25 20:43:37 +12:00
if (browser) {
window.addEventListener('storage', (event) => {
2026-04-25 22:51:36 +12:00
if (event.key === storageKey) {
store.set(readStoredSession(storageKey));
2026-04-25 20:43:37 +12:00
}
});
}
return {
subscribe: store.subscribe,
2026-04-25 22:51:36 +12:00
set(session: AppSession) {
2026-04-25 20:43:37 +12:00
if (browser) {
2026-04-25 22:51:36 +12:00
localStorage.setItem(storageKey, JSON.stringify(session));
2026-04-25 20:43:37 +12:00
}
store.set(session);
},
clear() {
if (browser) {
2026-04-25 22:51:36 +12:00
localStorage.removeItem(storageKey);
2026-04-25 20:43:37 +12:00
}
store.set(null);
}
};
}
2026-04-25 22:51:36 +12:00
export function getStoredClientSession() {
return readStoredSession(CLIENT_STORAGE_KEY);
}
export function getStoredAdminSession() {
return readStoredSession(ADMIN_STORAGE_KEY);
}
export function hasStoredClientSession() {
return getStoredClientSession() !== null;
}
export function hasStoredAdminSession() {
return getStoredAdminSession() !== null;
}
export const clientSession = createSessionStore(CLIENT_STORAGE_KEY);
export const adminSession = createSessionStore(ADMIN_STORAGE_KEY);