import { defineStore } from 'pinia'; import { ref } from 'vue'; import type { LoginResponse, MeResponse } from '@arboretum/shared'; import { api } from '../lib/api'; import { wsClient } from '../lib/ws-client'; export const useAuthStore = defineStore('auth', () => { /** null = pas encore vérifié auprès du serveur */ const authenticated = ref(null); const tokenLabel = ref(null); const serverVersion = ref(null); async function check(): Promise { try { const me = await api.get('/api/v1/auth/me'); tokenLabel.value = me.tokenLabel; serverVersion.value = me.serverVersion; authenticated.value = true; } catch { authenticated.value = false; } return authenticated.value === true; } async function login(token: string): Promise { const res = await api.post('/api/v1/auth/login', { token }); tokenLabel.value = res.label; authenticated.value = true; } async function logout(): Promise { try { await api.post<{ ok: true }>('/api/v1/auth/logout'); } finally { wsClient.disconnect(); authenticated.value = false; tokenLabel.value = null; } } return { authenticated, tokenLabel, serverVersion, check, login, logout }; });