1import api from "../../api";
2
3const AuthenticationStore = {
4  namespaced: true,
5  state: {
6    auth: {},
7    status: "",
8    token: sessionStorage.getItem("token") || ""
9  },
10  getters: {
11    authStatus: state => state.status,
12    isLoggedIn: state => !!state.token
13  },
14  mutations: {
15    authRequest(state) {
16      state.status = "loading";
17    },
18    authSuccess(state, token, auth) {
19      state.status = "authenicated";
20      state.auth = auth;
21      state.token = token;
22    },
23    authError(state) {
24      state.status = "error";
25    },
26    logout(state) {
27      state.status = "";
28      state.token = "";
29    }
30  },
31  actions: {
32    login({ commit }, auth) {
33      commit("authRequest");
34      return api
35        .post("/login", auth)
36        .then(response => {
37          const token = response.data.token;
38          sessionStorage.setItem("token", token);
39          api.defaults.auth = auth; // TODO Permanent Solution
40          commit("authSuccess", token, auth);
41        })
42        .catch(error => {
43          commit("authError");
44          sessionStorage.removeItem("token");
45          throw new Error(error);
46        });
47    },
48    logout({ commit }) {
49      commit("logout");
50      sessionStorage.removeItem("token");
51      api.defaults.auth = {}; // Permanent solution
52    }
53  }
54};
55
56export default AuthenticationStore;
57