1import api from '@/store/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      localStorage.removeItem('storedUsername');
27    }
28  },
29  actions: {
30    login({ commit }, auth) {
31      commit('authError', false);
32      return api
33        .post('/login', { data: auth })
34        .then(() => commit('authSuccess'))
35        .catch(error => {
36          commit('authError');
37          throw new Error(error);
38        });
39    },
40    logout({ commit }) {
41      api
42        .post('/logout', { data: [] })
43        .then(() => commit('logout'))
44        .then(() => router.go('/login'))
45        .catch(error => console.log(error));
46    },
47    async checkPasswordChangeRequired(_, username) {
48      return await api
49        .get(`/redfish/v1/AccountService/Accounts/${username}`)
50        .then(({ data: { PasswordChangeRequired } }) => PasswordChangeRequired)
51        .catch(error => console.log(error));
52    }
53  }
54};
55
56export default AuthenticationStore;
57