Files
pwa/src/atoms/auth.ts
T

49 lines
1.3 KiB
TypeScript
Raw Normal View History

2025-11-18 20:22:25 +03:30
import { atom } from 'jotai';
export type BackendUser = {
id: string;
email: string | null;
isGuest: boolean;
profileComplete: boolean;
};
export type GuestSession = {
id: string;
isGuest: true;
createdAt: string;
};
export const GUEST_SESSION_STORAGE_KEY = 'guest-session';
const readGuestSession = (): GuestSession | null => {
if (typeof window === 'undefined') return null;
const raw = localStorage.getItem(GUEST_SESSION_STORAGE_KEY);
if (!raw) return null;
try {
const parsed = JSON.parse(raw) as GuestSession;
if (!parsed?.id || parsed?.isGuest !== true) return null;
return parsed;
} catch {
return null;
}
};
export const backendUserAtom = atom<BackendUser | null>(null);
2025-11-18 20:22:25 +03:30
export const isAuthenticatedAtom = atom<boolean>((get) => {
return !!get(backendUserAtom);
2025-11-18 20:22:25 +03:30
});
export const guestSessionAtom = atom<GuestSession | null>(readGuestSession());
export const guestSessionHydratedAtom = atom(false);
export const isGuestAtom = atom<boolean>((get) => !!get(guestSessionAtom));
2025-11-18 20:22:25 +03:30
export const effectiveUserIdAtom = atom<string | null>((get) => {
const user = get(backendUserAtom);
if (user?.id) return user.id;
const guest = get(guestSessionAtom);
return guest?.id ?? null;
});
2025-11-18 20:22:25 +03:30
export const authInitialCheckDoneAtom = atom(false);