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    xsrfCookie: Cookies.get('XSRF-TOKEN'),
10    isAuthenticatedCookie: Cookies.get('IsAuthenticated'),
11  },
12  getters: {
13    authError: (state) => state.authError,
14    isLoggedIn: (state) => {
15      return (
16        state.xsrfCookie !== undefined || state.isAuthenticatedCookie == 'true'
17      );
18    },
19    token: (state) => state.xsrfCookie,
20  },
21  mutations: {
22    authSuccess(state) {
23      state.authError = false;
24      state.xsrfCookie = Cookies.get('XSRF-TOKEN');
25    },
26    authError(state, authError = true) {
27      state.authError = authError;
28    },
29    logout(state) {
30      Cookies.remove('XSRF-TOKEN');
31      Cookies.remove('IsAuthenticated');
32      localStorage.removeItem('storedUsername');
33      state.xsrfCookie = undefined;
34      state.isAuthenticatedCookie = undefined;
35    },
36  },
37  actions: {
38    login({ commit }, { username, password }) {
39      commit('authError', false);
40      return api
41        .post('/login', { data: [username, password] })
42        .then(() => commit('authSuccess'))
43        .catch((error) => {
44          commit('authError');
45          throw new Error(error);
46        });
47    },
48    logout({ commit }) {
49      api
50        .post('/logout', { data: [] })
51        .then(() => commit('logout'))
52        .then(() => router.go('/login'))
53        .catch((error) => console.log(error));
54    },
55    checkPasswordChangeRequired(_, username) {
56      api
57        .get(`/redfish/v1/AccountService/Accounts/${username}`)
58        .then(({ data: { PasswordChangeRequired } }) => PasswordChangeRequired)
59        .catch((error) => console.log(error));
60    },
61    resetStoreState({ state }) {
62      state.authError = false;
63      state.xsrfCookie = Cookies.get('XSRF-TOKEN');
64      state.isAuthenticatedCookie = Cookies.get('IsAuthenticated');
65    },
66  },
67};
68
69export default AuthenticationStore;
70