1import api from '../../api'; 2import Cookies from 'js-cookie'; 3import router from '../../../router'; 4 5const AuthenticationStore = { 6 namespaced: true, 7 state: { 8 authError: false, 9 cookie: Cookies.get('XSRF-TOKEN') 10 }, 11 getters: { 12 authError: state => state.authError, 13 isLoggedIn: state => !!state.cookie, 14 token: state => state.cookie 15 }, 16 mutations: { 17 authSuccess(state) { 18 state.authError = false; 19 state.cookie = Cookies.get('XSRF-TOKEN'); 20 }, 21 authError(state, authError = true) { 22 state.authError = authError; 23 }, 24 logout() { 25 Cookies.remove('XSRF-TOKEN'); 26 } 27 }, 28 actions: { 29 login({ commit }, auth) { 30 commit('authError', false); 31 return api 32 .post('/login', { data: auth }) 33 .then(() => commit('authSuccess')) 34 .catch(error => { 35 commit('authError'); 36 throw new Error(error); 37 }); 38 }, 39 logout({ commit }) { 40 api 41 .post('/logout', { data: [] }) 42 .then(() => commit('logout')) 43 .then(() => router.go('/login')) 44 .catch(error => console.log(error)); 45 } 46 } 47}; 48 49export default AuthenticationStore; 50