1import api from '@/store/api';
2import Cookies from 'js-cookie';
3import router from '@/router';
4
5const AuthenticationStore = {
6  namespaced: true,
7  state: {
8    consoleWindow: null,
9    authError: false,
10    xsrfCookie: Cookies.get('XSRF-TOKEN'),
11    isAuthenticatedCookie: Cookies.get('IsAuthenticated'),
12  },
13  getters: {
14    consoleWindow: (state) => state.consoleWindow,
15    authError: (state) => state.authError,
16    isLoggedIn: (state) => {
17      return (
18        state.xsrfCookie !== undefined || state.isAuthenticatedCookie == 'true'
19      );
20    },
21    token: (state) => state.xsrfCookie,
22  },
23  mutations: {
24    authSuccess(state) {
25      state.authError = false;
26      state.xsrfCookie = Cookies.get('XSRF-TOKEN');
27    },
28    authError(state, authError = true) {
29      state.authError = authError;
30    },
31    logout(state) {
32      Cookies.remove('XSRF-TOKEN');
33      Cookies.remove('IsAuthenticated');
34      localStorage.removeItem('storedUsername');
35      state.xsrfCookie = undefined;
36      state.isAuthenticatedCookie = undefined;
37    },
38    setConsoleWindow: (state, window) => (state.consoleWindow = window),
39  },
40  actions: {
41    login({ commit }, { username, password }) {
42      commit('authError', false);
43      return api
44        .post('/login', { data: [username, password] })
45        .then(() => commit('authSuccess'))
46        .catch((error) => {
47          commit('authError');
48          throw new Error(error);
49        });
50    },
51    logout({ commit }) {
52      api
53        .post('/logout', { data: [] })
54        .then(() => {
55          commit('setConsoleWindow', false);
56          commit('logout');
57        })
58        .then(() => router.go('/login'))
59        .catch((error) => console.log(error));
60    },
61    getUserInfo(_, username) {
62      return api
63        .get(`/redfish/v1/AccountService/Accounts/${username}`)
64        .then(({ data }) => data)
65        .catch((error) => console.log(error));
66    },
67    resetStoreState({ state }) {
68      state.authError = false;
69      state.xsrfCookie = Cookies.get('XSRF-TOKEN');
70      state.isAuthenticatedCookie = Cookies.get('IsAuthenticated');
71    },
72  },
73};
74
75export default AuthenticationStore;
76