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