1import api, { getResponseCount } from '@/store/api';
2import i18n from '@/i18n';
3
4const UserManagementStore = {
5  namespaced: true,
6  state: {
7    allUsers: [],
8    accountRoles: [],
9    accountLockoutDuration: null,
10    accountLockoutThreshold: null,
11    accountMinPasswordLength: null,
12    accountMaxPasswordLength: null,
13  },
14  getters: {
15    allUsers(state) {
16      return state.allUsers;
17    },
18    accountRoles(state) {
19      return state.accountRoles;
20    },
21    accountSettings(state) {
22      return {
23        lockoutDuration: state.accountLockoutDuration,
24        lockoutThreshold: state.accountLockoutThreshold,
25      };
26    },
27    accountPasswordRequirements(state) {
28      return {
29        minLength: state.accountMinPasswordLength,
30        maxLength: state.accountMaxPasswordLength,
31      };
32    },
33  },
34  mutations: {
35    setUsers(state, allUsers) {
36      state.allUsers = allUsers;
37    },
38    setAccountRoles(state, accountRoles) {
39      state.accountRoles = accountRoles;
40    },
41    setLockoutDuration(state, lockoutDuration) {
42      state.accountLockoutDuration = lockoutDuration;
43    },
44    setLockoutThreshold(state, lockoutThreshold) {
45      state.accountLockoutThreshold = lockoutThreshold;
46    },
47    setAccountMinPasswordLength(state, minPasswordLength) {
48      state.accountMinPasswordLength = minPasswordLength;
49    },
50    setAccountMaxPasswordLength(state, maxPasswordLength) {
51      state.accountMaxPasswordLength = maxPasswordLength;
52    },
53  },
54  actions: {
55    async getUsers({ commit }) {
56      return await api
57        .get('/redfish/v1/AccountService/Accounts')
58        .then((response) =>
59          response.data.Members.map((user) => user['@odata.id'])
60        )
61        .then((userIds) => api.all(userIds.map((user) => api.get(user))))
62        .then((users) => {
63          const userData = users.map((user) => user.data);
64          commit('setUsers', userData);
65        })
66        .catch((error) => {
67          console.log(error);
68          const message = i18n.t('pageUserManagement.toast.errorLoadUsers');
69          throw new Error(message);
70        });
71    },
72    getAccountSettings({ commit }) {
73      api
74        .get('/redfish/v1/AccountService')
75        .then(({ data }) => {
76          commit('setLockoutDuration', data.AccountLockoutDuration);
77          commit('setLockoutThreshold', data.AccountLockoutThreshold);
78          commit('setAccountMinPasswordLength', data.MinPasswordLength);
79          commit('setAccountMaxPasswordLength', data.MaxPasswordLength);
80        })
81        .catch((error) => {
82          console.log(error);
83          const message = i18n.t(
84            'pageUserManagement.toast.errorLoadAccountSettings'
85          );
86          throw new Error(message);
87        });
88    },
89    getAccountRoles({ commit }) {
90      api
91        .get('/redfish/v1/AccountService/Roles')
92        .then(({ data: { Members = [] } = {} }) => {
93          const roles = Members.map((role) => {
94            return role['@odata.id'].split('/').pop();
95          });
96          commit('setAccountRoles', roles);
97        })
98        .catch((error) => console.log(error));
99    },
100    async createUser({ dispatch }, { username, password, privilege, status }) {
101      const data = {
102        UserName: username,
103        Password: password,
104        RoleId: privilege,
105        Enabled: status,
106      };
107      return await api
108        .post('/redfish/v1/AccountService/Accounts', data)
109        .then(() => dispatch('getUsers'))
110        .then(() =>
111          i18n.t('pageUserManagement.toast.successCreateUser', {
112            username,
113          })
114        )
115        .catch((error) => {
116          console.log(error);
117          const message = i18n.t('pageUserManagement.toast.errorCreateUser', {
118            username,
119          });
120          throw new Error(message);
121        });
122    },
123    async updateUser(
124      { dispatch },
125      { originalUsername, username, password, privilege, status, locked }
126    ) {
127      const data = {};
128      if (username) data.UserName = username;
129      if (password) data.Password = password;
130      if (privilege) data.RoleId = privilege;
131      if (status !== undefined) data.Enabled = status;
132      if (locked !== undefined) data.Locked = locked;
133      return await api
134        .patch(`/redfish/v1/AccountService/Accounts/${originalUsername}`, data)
135        .then(() => dispatch('getUsers'))
136        .then(() =>
137          i18n.t('pageUserManagement.toast.successUpdateUser', {
138            username: originalUsername,
139          })
140        )
141        .catch((error) => {
142          console.log(error);
143          const message = i18n.t('pageUserManagement.toast.errorUpdateUser', {
144            username: originalUsername,
145          });
146          throw new Error(message);
147        });
148    },
149    async deleteUser({ dispatch }, username) {
150      return await api
151        .delete(`/redfish/v1/AccountService/Accounts/${username}`)
152        .then(() => dispatch('getUsers'))
153        .then(() =>
154          i18n.t('pageUserManagement.toast.successDeleteUser', {
155            username,
156          })
157        )
158        .catch((error) => {
159          console.log(error);
160          const message = i18n.t('pageUserManagement.toast.errorDeleteUser', {
161            username,
162          });
163          throw new Error(message);
164        });
165    },
166    async deleteUsers({ dispatch }, users) {
167      const promises = users.map(({ username }) => {
168        return api
169          .delete(`/redfish/v1/AccountService/Accounts/${username}`)
170          .catch((error) => {
171            console.log(error);
172            return error;
173          });
174      });
175      return await api
176        .all(promises)
177        .then((response) => {
178          dispatch('getUsers');
179          return response;
180        })
181        .then(
182          api.spread((...responses) => {
183            const { successCount, errorCount } = getResponseCount(responses);
184            let toastMessages = [];
185
186            if (successCount) {
187              const message = i18n.tc(
188                'pageUserManagement.toast.successBatchDelete',
189                successCount
190              );
191              toastMessages.push({ type: 'success', message });
192            }
193
194            if (errorCount) {
195              const message = i18n.tc(
196                'pageUserManagement.toast.errorBatchDelete',
197                errorCount
198              );
199              toastMessages.push({ type: 'error', message });
200            }
201
202            return toastMessages;
203          })
204        );
205    },
206    async enableUsers({ dispatch }, users) {
207      const data = {
208        Enabled: true,
209      };
210      const promises = users.map(({ username }) => {
211        return api
212          .patch(`/redfish/v1/AccountService/Accounts/${username}`, data)
213          .catch((error) => {
214            console.log(error);
215            return error;
216          });
217      });
218      return await api
219        .all(promises)
220        .then((response) => {
221          dispatch('getUsers');
222          return response;
223        })
224        .then(
225          api.spread((...responses) => {
226            const { successCount, errorCount } = getResponseCount(responses);
227            let toastMessages = [];
228
229            if (successCount) {
230              const message = i18n.tc(
231                'pageUserManagement.toast.successBatchEnable',
232                successCount
233              );
234              toastMessages.push({ type: 'success', message });
235            }
236
237            if (errorCount) {
238              const message = i18n.tc(
239                'pageUserManagement.toast.errorBatchEnable',
240                errorCount
241              );
242              toastMessages.push({ type: 'error', message });
243            }
244
245            return toastMessages;
246          })
247        );
248    },
249    async disableUsers({ dispatch }, users) {
250      const data = {
251        Enabled: false,
252      };
253      const promises = users.map(({ username }) => {
254        return api
255          .patch(`/redfish/v1/AccountService/Accounts/${username}`, data)
256          .catch((error) => {
257            console.log(error);
258            return error;
259          });
260      });
261      return await api
262        .all(promises)
263        .then((response) => {
264          dispatch('getUsers');
265          return response;
266        })
267        .then(
268          api.spread((...responses) => {
269            const { successCount, errorCount } = getResponseCount(responses);
270            let toastMessages = [];
271
272            if (successCount) {
273              const message = i18n.tc(
274                'pageUserManagement.toast.successBatchDisable',
275                successCount
276              );
277              toastMessages.push({ type: 'success', message });
278            }
279
280            if (errorCount) {
281              const message = i18n.tc(
282                'pageUserManagement.toast.errorBatchDisable',
283                errorCount
284              );
285              toastMessages.push({ type: 'error', message });
286            }
287
288            return toastMessages;
289          })
290        );
291    },
292    async saveAccountSettings(
293      { dispatch },
294      { lockoutThreshold, lockoutDuration }
295    ) {
296      const data = {};
297      if (lockoutThreshold !== undefined) {
298        data.AccountLockoutThreshold = lockoutThreshold;
299      }
300      if (lockoutDuration !== undefined) {
301        data.AccountLockoutDuration = lockoutDuration;
302      }
303
304      return await api
305        .patch('/redfish/v1/AccountService', data)
306        //GET new settings to update view
307        .then(() => dispatch('getAccountSettings'))
308        .then(() => i18n.t('pageUserManagement.toast.successSaveSettings'))
309        .catch((error) => {
310          console.log(error);
311          const message = i18n.t('pageUserManagement.toast.errorSaveSettings');
312          throw new Error(message);
313        });
314    },
315  },
316};
317
318export default UserManagementStore;
319