55 lines
1.3 KiB
JavaScript
55 lines
1.3 KiB
JavaScript
import Vue from 'vue'
|
|
import Vuex from 'vuex'
|
|
import { authService } from '@/services/api'
|
|
|
|
Vue.use(Vuex)
|
|
|
|
export default new Vuex.Store({
|
|
state: {
|
|
user: null,
|
|
token: localStorage.getItem('token') || null,
|
|
loading: false,
|
|
error: null
|
|
},
|
|
mutations: {
|
|
SET_USER(state, user) {
|
|
state.user = user
|
|
},
|
|
SET_TOKEN(state, token) {
|
|
state.token = token
|
|
},
|
|
SET_LOADING(state, loading) {
|
|
state.loading = loading
|
|
},
|
|
SET_ERROR(state, error) {
|
|
state.error = error
|
|
}
|
|
},
|
|
actions: {
|
|
async login({ commit }, credentials) {
|
|
commit('SET_LOADING', true)
|
|
commit('SET_ERROR', null)
|
|
try {
|
|
const response = await authService.login(credentials)
|
|
commit('SET_TOKEN', response.token)
|
|
localStorage.setItem('token', response.token)
|
|
} catch (error) {
|
|
commit('SET_ERROR', error.message)
|
|
throw error
|
|
} finally {
|
|
commit('SET_LOADING', false)
|
|
}
|
|
},
|
|
logout({ commit }) {
|
|
commit('SET_USER', null)
|
|
commit('SET_TOKEN', null)
|
|
localStorage.removeItem('token')
|
|
}
|
|
},
|
|
getters: {
|
|
isAuthenticated: state => !!state.token,
|
|
currentUser: state => state.user,
|
|
isLoading: state => state.loading,
|
|
error: state => state.error
|
|
}
|
|
}) |