import { defineStore } from 'pinia' interface User { id: number email: string displayName: string | null role: string totpEnabled?: boolean } interface LoginResponse { access_token?: string user?: User requires_totp?: boolean } export const useAuthStore = defineStore('auth', { state: () => ({ token: localStorage.getItem('wraith_token') || '', user: null as User | null, }), getters: { isAuthenticated: (state) => !!state.token, isAdmin: (state) => state.user?.role === 'admin', }, actions: { async login(email: string, password: string, totpCode?: string): Promise { const body: Record = { email, password } if (totpCode) body.totpCode = totpCode const res = await $fetch('/api/auth/login', { method: 'POST', body, }) if (res.requires_totp) { return { requires_totp: true } } this.token = res.access_token! this.user = res.user! localStorage.setItem('wraith_token', res.access_token!) return res }, logout() { this.token = '' this.user = null localStorage.removeItem('wraith_token') navigateTo('/login') }, async fetchProfile() { if (!this.token) return try { this.user = await $fetch('/api/auth/profile', { headers: { Authorization: `Bearer ${this.token}` }, }) } catch { this.logout() } }, }, })