File size: 2,008 Bytes
89ce340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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()
        }
      }
    }
  }
})