48 lines
1.1 KiB
TypeScript
48 lines
1.1 KiB
TypeScript
import type { AuthSession } from './auth.models';
|
|
|
|
const SESSION_KEY = 'gorodar.session';
|
|
|
|
export function readAuthSession(): AuthSession | null {
|
|
const raw = localStorage.getItem(SESSION_KEY);
|
|
|
|
if (!raw) {
|
|
return null;
|
|
}
|
|
|
|
const session = parseSession(raw);
|
|
const expired = !!session && typeof session.expiresAt === 'number' && session.expiresAt <= Date.now();
|
|
|
|
if (!session || !isEmail(session.email) || !session.accessToken || expired) {
|
|
localStorage.removeItem(SESSION_KEY);
|
|
return null;
|
|
}
|
|
|
|
return session;
|
|
}
|
|
|
|
export function writeAuthSession(session: AuthSession): void {
|
|
localStorage.setItem(SESSION_KEY, JSON.stringify(session));
|
|
}
|
|
|
|
export function clearAuthSession(): void {
|
|
localStorage.removeItem(SESSION_KEY);
|
|
}
|
|
|
|
function parseSession(raw: string): AuthSession | null {
|
|
try {
|
|
const parsed: unknown = JSON.parse(raw);
|
|
|
|
if (!parsed || typeof parsed !== 'object') {
|
|
return null;
|
|
}
|
|
|
|
return parsed as AuthSession;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function isEmail(value: string): boolean {
|
|
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
|
|
}
|