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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| export default { namespaced: true, state() { return { token: localStorage.getItem('token') || '', user: JSON.parse(localStorage.getItem('user')) || null, loading: false, error: null } }, mutations: { SET_TOKEN(state, token) { state.token = token localStorage.setItem('token', token) }, SET_USER(state, user) { state.user = user localStorage.setItem('user', JSON.stringify(user)) }, SET_LOADING(state, loading) { state.loading = loading }, SET_ERROR(state, error) { state.error = error }, CLEAR_AUTH(state) { state.token = '' state.user = null localStorage.removeItem('token') localStorage.removeItem('user') } }, actions: { async login({ commit }, { email, password }) { try { commit('SET_LOADING', true) commit('SET_ERROR', null) const response = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }) }) const data = await response.json() if (!response.ok) { throw new Error(data.message || 'Login failed') } commit('SET_TOKEN', data.token) commit('SET_USER', data.user) return data.user } catch (error) { commit('SET_ERROR', error.message) throw error } finally { commit('SET_LOADING', false) } }, async logout({ commit, state }) { try { commit('SET_LOADING', true) await fetch('/api/auth/logout', { method: 'POST', headers: { 'Authorization': `Bearer ${state.token}` } }) } finally { commit('CLEAR_AUTH') commit('SET_LOADING', false) } }, async checkAuth({ commit, state }) { if (!state.token) return false try { commit('SET_LOADING', true) const response = await fetch('/api/auth/me', { headers: { 'Authorization': `Bearer ${state.token}` } }) if (!response.ok) { commit('CLEAR_AUTH') return false } const user = await response.json() commit('SET_USER', user) return true } catch (error) { commit('CLEAR_AUTH') return false } finally { commit('SET_LOADING', false) } } }, getters: { isAuthenticated: (state) => !!state.token, currentUser: (state) => state.user, isLoading: (state) => state.loading, authError: (state) => state.error, userRole: (state) => state.user?.role || 'user' } }
|