| import { defineStore } from 'pinia' | |
| import api from '@/services' | |
| interface User { | |
| id: string | |
| username: string | |
| role: string | |
| } | |
| interface AuthState { | |
| user: User | null | |
| token: string | null | |
| isAuthenticated: boolean | |
| } | |
| export const useAuthStore = defineStore('auth', { | |
| state: (): AuthState => ({ | |
| user: null, | |
| token: localStorage.getItem('pptist_token'), | |
| isAuthenticated: false | |
| }), | |
| getters: { | |
| currentUser: (state) => state.user, | |
| isLoggedIn: (state) => state.isAuthenticated && !!state.token, | |
| userRole: (state) => state.user?.role || 'guest' | |
| }, | |
| actions: { | |
| async login(username: string, password: string) { | |
| try { | |
| const response = await api.login(username, password) | |
| this.token = response.token | |
| this.user = response.user | |
| this.isAuthenticated = true | |
| localStorage.setItem('pptist_token', response.token) | |
| localStorage.setItem('pptist_user', JSON.stringify(response.user)) | |
| return response | |
| } catch (error) { | |
| this.logout() | |
| throw error | |
| } | |
| }, | |
| async verifyToken() { | |
| if (!this.token) { | |
| this.logout() | |
| return false | |
| } | |
| try { | |
| const response = await api.verifyToken() | |
| this.user = response.user | |
| this.isAuthenticated = true | |
| return true | |
| } catch (error) { | |
| this.logout() | |
| return false | |
| } | |
| }, | |
| logout() { | |
| this.user = null | |
| this.token = null | |
| this.isAuthenticated = false | |
| localStorage.removeItem('pptist_token') | |
| localStorage.removeItem('pptist_user') | |
| }, | |
| async initAuth() { | |
| const savedUser = localStorage.getItem('pptist_user') | |
| if (savedUser && this.token) { | |
| try { | |
| this.user = JSON.parse(savedUser) | |
| await this.verifyToken() | |
| } catch (error) { | |
| this.logout() | |
| } | |
| } | |
| } | |
| } | |
| }) |