45 lines
1.1 KiB
TypeScript
45 lines
1.1 KiB
TypeScript
import { defineStore } from 'pinia'
|
|
|
|
interface User {
|
|
id: number
|
|
email: string
|
|
displayName: string | null
|
|
}
|
|
|
|
export const useAuthStore = defineStore('auth', {
|
|
state: () => ({
|
|
token: localStorage.getItem('wraith_token') || '',
|
|
user: null as User | null,
|
|
}),
|
|
getters: {
|
|
isAuthenticated: (state) => !!state.token,
|
|
},
|
|
actions: {
|
|
async login(email: string, password: string) {
|
|
const res = await $fetch<{ access_token: string; user: User }>('/api/auth/login', {
|
|
method: 'POST',
|
|
body: { email, password },
|
|
})
|
|
this.token = res.access_token
|
|
this.user = res.user
|
|
localStorage.setItem('wraith_token', res.access_token)
|
|
},
|
|
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()
|
|
}
|
|
},
|
|
},
|
|
})
|