import { writable } from 'svelte/store'; import { api, setAccessToken } from '$lib/api'; interface User { id: number; username: string; is_active: boolean; totp_enabled: boolean; last_login_at: string | null; } export const user = writable(null); export const isAuthenticated = writable(false); export async function login(username: string, password: string, totp_code?: string) { const data = await api<{ access_token: string }>('/auth/login', { method: 'POST', body: JSON.stringify({ username, password, totp_code: totp_code || undefined }), }); setAccessToken(data.access_token); await fetchUser(); } export async function fetchUser() { try { const data = await api('/auth/me'); user.set(data); isAuthenticated.set(true); } catch { user.set(null); isAuthenticated.set(false); } } export async function logout() { try { await api('/auth/logout', { method: 'POST' }); } catch { /* ignore */ } setAccessToken(null); user.set(null); isAuthenticated.set(false); } export async function tryRefresh() { try { const data = await api<{ access_token: string }>('/auth/refresh', { method: 'POST', }); setAccessToken(data.access_token); await fetchUser(); return true; } catch { return false; } }