import { defineStore } from 'pinia' /** * Store d'auth "mince" : il ne fait que relayer vers le back et mémoriser l'utilisateur courant. * Aucune logique métier ici (règle : tout est géré côté back). */ interface SfUser { id: number name: string email: string locale?: string units?: string avatar_url?: string | null } export const useAuthStore = defineStore('auth', () => { const user = ref(null) const streak = ref<{ current: number, longest: number, freezes: number } | null>(null) const push = ref<{ vapid_public_key: string | null, enabled: boolean }>({ vapid_public_key: null, enabled: false }) const ready = ref(false) const isAuthed = computed(() => !!user.value) async function fetchMe() { const { api } = useApi() try { const res = await api<{ user: SfUser, streak: typeof streak.value, push: typeof push.value }>('/api/me') user.value = res.user streak.value = res.streak if (res.push) push.value = res.push } catch { user.value = null streak.value = null } finally { ready.value = true } } async function login(email: string, password: string) { const { api, ensureCsrf } = useApi() await ensureCsrf() const res = await api<{ user: SfUser }>('/login', { method: 'POST', body: { email, password } }) user.value = res.user await fetchMe() } async function register(name: string, email: string, password: string) { const { api, ensureCsrf } = useApi() await ensureCsrf() const res = await api<{ user: SfUser }>('/register', { method: 'POST', body: { name, email, password } }) user.value = res.user await fetchMe() } async function logout() { const { api, ensureCsrf } = useApi() await ensureCsrf() try { await api('/logout', { method: 'POST' }) } finally { user.value = null streak.value = null } } /** Login OIDC pocket-id : 100% back — on redirige simplement le navigateur. */ function loginWithPocketId() { const { base } = useApi() window.location.href = `${base}/auth/oidc/redirect` } return { user, streak, push, ready, isAuthed, fetchMe, login, register, logout, loginWithPocketId } })