1import api from '@/store/api';
2import Cookies from 'js-cookie';
3import router from '@/router';
4import { roles } from '@/router/routes';
5
6const AuthenticationStore = {
7  namespaced: true,
8  state: {
9    consoleWindow: null,
10    authError: false,
11    xsrfCookie: Cookies.get('XSRF-TOKEN'),
12    isAuthenticatedCookie: Cookies.get('IsAuthenticated'),
13  },
14  getters: {
15    consoleWindow: (state) => state.consoleWindow,
16    authError: (state) => state.authError,
17    isLoggedIn: (state) => {
18      return (
19        state.xsrfCookie !== undefined || state.isAuthenticatedCookie == 'true'
20      );
21    },
22    token: (state) => state.xsrfCookie,
23  },
24  mutations: {
25    authSuccess(state) {
26      state.authError = false;
27      state.xsrfCookie = Cookies.get('XSRF-TOKEN');
28    },
29    authError(state, authError = true) {
30      state.authError = authError;
31    },
32    logout(state) {
33      Cookies.remove('XSRF-TOKEN');
34      Cookies.remove('IsAuthenticated');
35      localStorage.removeItem('storedUsername');
36      state.xsrfCookie = undefined;
37      state.isAuthenticatedCookie = undefined;
38    },
39    setConsoleWindow: (state, window) => (state.consoleWindow = window),
40  },
41  actions: {
42    login({ commit }, { username, password }) {
43      commit('authError', false);
44      return api
45        .post('/login', {
46          username: username,
47          password: password,
48        })
49        .then(() => commit('authSuccess'))
50        .catch((error) => {
51          commit('authError');
52          throw new Error(error);
53        });
54    },
55    logout({ commit }) {
56      api
57        .post('/logout', { data: [] })
58        .then(() => {
59          commit('setConsoleWindow', false);
60          commit('logout');
61        })
62        .then(() => router.push('/login'))
63        .catch((error) => console.log(error));
64    },
65    getUserInfo({ commit }, username) {
66      return api
67        .get(`/redfish/v1/AccountService/Accounts/${username}`)
68        .then(({ data }) => {
69          commit('global/setPrivilege', data.RoleId, { root: true });
70          return data;
71        })
72        .catch((error) => {
73          if (error.response?.status === 404) {
74            // We have valid credentials but user isn't known, assume remote
75            // authentication (e.g. LDAP) and do not restrict the routing
76            commit('global/setPrivilege', roles.administrator, { root: true });
77            return {};
78          } else {
79            console.log(error);
80          }
81        });
82    },
83    resetStoreState({ state }) {
84      state.authError = false;
85      state.xsrfCookie = Cookies.get('XSRF-TOKEN');
86      state.isAuthenticatedCookie = Cookies.get('IsAuthenticated');
87    },
88  },
89};
90
91export default AuthenticationStore;
92