summaryrefslogtreecommitdiff
path: root/src/store/modules/Authentication/AuthenticanStore.js
blob: 828c3cc8bc055744dc1fc8dc018a00b803870720 (plain)
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
import api from "../../api";

const AuthenticationStore = {
  namespaced: true,
  state: {
    auth: {},
    status: "",
    token: sessionStorage.getItem("token") || ""
  },
  getters: {
    authStatus: state => state.status,
    isLoggedIn: state => !!state.token
  },
  mutations: {
    authRequest(state) {
      state.status = "loading";
    },
    authSuccess(state, token, auth) {
      state.status = "authenicated";
      state.auth = auth;
      state.token = token;
    },
    authError(state) {
      state.status = "error";
    },
    logout(state) {
      state.status = "";
      state.token = "";
    }
  },
  actions: {
    login({ commit }, auth) {
      commit("authRequest");
      return api
        .post("/login", auth)
        .then(response => {
          const token = response.data.token;
          sessionStorage.setItem("token", token);
          api.defaults.auth = auth; // TODO Permanent Solution
          commit("authSuccess", token, auth);
        })
        .catch(error => {
          commit("authError");
          sessionStorage.removeItem("token");
          throw new Error(error);
        });
    },
    logout({ commit }) {
      commit("logout");
      sessionStorage.removeItem("token");
      api.defaults.auth = {}; // Permanent solution
    }
  }
};

export default AuthenticationStore;