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    sessionURI: localStorage.getItem('sessionURI'),
14  },
15  getters: {
16    consoleWindow: (state) => state.consoleWindow,
17    authError: (state) => state.authError,
18    isLoggedIn: (state) => {
19      // We might have gotten XSRF-TOKEN (and HttpOnly SESSION cookie) by Mutual TLS authentication,
20      // without going through explicit Session creation
21      return (
22        state.xsrfCookie !== undefined || state.isAuthenticatedCookie == 'true'
23      );
24    },
25    // Used to authenticate WebSocket connections via subprotocol value
26    token: (state) => state.xsrfCookie,
27  },
28  mutations: {
29    authSuccess(state, { session }) {
30      state.authError = false;
31      state.xsrfCookie = Cookies.get('XSRF-TOKEN');
32      // Preserve session data across page reloads and browser restarts
33      localStorage.setItem('sessionURI', session);
34      state.sessionURI = session;
35    },
36    authError(state, authError = true) {
37      state.authError = authError;
38    },
39    logout(state) {
40      Cookies.remove('XSRF-TOKEN');
41      Cookies.remove('IsAuthenticated');
42      localStorage.removeItem('storedUsername');
43      state.xsrfCookie = undefined;
44      state.isAuthenticatedCookie = undefined;
45      localStorage.removeItem('sessionURI');
46      state.sessionURI = null;
47      state.consoleWindow = false;
48    },
49  },
50  actions: {
51    login({ commit }, { username, password }) {
52      commit('authError', false);
53      return api
54        .post('/redfish/v1/SessionService/Sessions', {
55          UserName: username,
56          Password: password,
57        })
58        .then((response) => {
59          commit('authSuccess', {
60            session: response.headers['location'],
61          });
62        })
63        .catch((error) => {
64          commit('authError');
65          throw new Error(error);
66        });
67    },
68    logout({ commit, state }) {
69      api
70        .delete(state.sessionURI)
71        .then(() => commit('logout'))
72        .then(() => router.push('/login'))
73        .catch((error) => console.log(error));
74    },
75    getUserInfo({ commit }, username) {
76      return api
77        .get(`/redfish/v1/AccountService/Accounts/${username}`)
78        .then(({ data }) => {
79          commit('global/setPrivilege', data.RoleId, { root: true });
80          return data;
81        })
82        .catch((error) => {
83          if (error.response?.status === 404) {
84            // We have valid credentials but user isn't known, assume remote
85            // authentication (e.g. LDAP) and do not restrict the routing
86            commit('global/setPrivilege', roles.administrator, { root: true });
87            return {};
88          } else {
89            console.log(error);
90          }
91        });
92    },
93    resetStoreState({ state }) {
94      state.authError = false;
95      state.xsrfCookie = Cookies.get('XSRF-TOKEN');
96      state.isAuthenticatedCookie = Cookies.get('IsAuthenticated');
97    },
98  },
99};
100
101export default AuthenticationStore;
102