• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mendersoftware / gui / 1315496247

03 Jun 2024 07:49AM UTC coverage: 83.437% (-16.5%) from 99.964%
1315496247

Pull #4434

gitlab-ci

mzedel
chore: aligned snapshots with updated mui version

Signed-off-by: Manuel Zedel <manuel.zedel@northern.tech>
Pull Request #4434: chore: Bump the mui group with 3 updates

4476 of 6391 branches covered (70.04%)

8488 of 10173 relevant lines covered (83.44%)

140.36 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

88.67
/src/js/actions/userActions.js
1
'use strict';
2

3
// Copyright 2019 Northern.tech AS
4
//
5
//    Licensed under the Apache License, Version 2.0 (the "License");
6
//    you may not use this file except in compliance with the License.
7
//    You may obtain a copy of the License at
8
//
9
//        http://www.apache.org/licenses/LICENSE-2.0
10
//
11
//    Unless required by applicable law or agreed to in writing, software
12
//    distributed under the License is distributed on an "AS IS" BASIS,
13
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
//    See the License for the specific language governing permissions and
15
//    limitations under the License.
16
import hashString from 'md5';
17
import Cookies from 'universal-cookie';
18

19
import GeneralApi, { apiRoot } from '../api/general-api';
20
import UsersApi from '../api/users-api';
21
import { cleanUp, maxSessionAge, setSessionInfo } from '../auth';
22
import { HELPTOOLTIPS } from '../components/helptips/helptooltips';
23
import { getSsoStartUrlById } from '../components/settings/organization/ssoconfig.js';
24
import * as AppConstants from '../constants/appConstants';
25
import { APPLICATION_JSON_CONTENT_TYPE, APPLICATION_JWT_CONTENT_TYPE } from '../constants/appConstants';
26
import { ALL_RELEASES } from '../constants/releaseConstants.js';
27
import * as UserConstants from '../constants/userConstants';
28
import { duplicateFilter, extractErrorMessage, isEmpty, preformatWithRequestID } from '../helpers';
29
import { getCurrentUser, getOnboardingState, getTooltipsState, getUserSettings as getUserSettingsSelector } from '../selectors';
30
import { clearAllRetryTimers } from '../utils/retrytimer';
31
import { commonErrorFallback, commonErrorHandler, initializeAppData, setOfflineThreshold, setSnackbar } from './appActions';
32

33
const cookies = new Cookies();
184✔
34
const {
35
  defaultPermissionSets,
36
  emptyRole,
37
  emptyUiPermissions,
38
  itemUiPermissionsReducer,
39
  OWN_USER_ID,
40
  PermissionTypes,
41
  rolesById: defaultRolesById,
42
  scopedPermissionAreas,
43
  twoFAStates,
44
  uiPermissionsByArea,
45
  uiPermissionsById,
46
  useradmApiUrl,
47
  useradmApiUrlv2
48
} = UserConstants;
184✔
49

50
const handleLoginError =
51
  (err, { token2fa: has2FA, password }) =>
184✔
52
  dispatch => {
1✔
53
    const errorText = extractErrorMessage(err);
1✔
54
    const is2FABackend = errorText.includes('2fa');
1✔
55
    if (is2FABackend && !has2FA) {
1!
56
      return Promise.reject({ error: '2fa code missing' });
1✔
57
    }
58
    if (password === undefined) {
×
59
      // Enterprise supports two-steps login. On the first step you can enter only email
60
      // and in case of SSO set up you will receive a redirect URL
61
      // otherwise you will receive 401 status code and password field will be shown.
62
      return Promise.reject();
×
63
    }
64
    const twoFAError = is2FABackend ? ' and verification code' : '';
×
65
    const errorMessage = `There was a problem logging in. Please check your email${
×
66
      twoFAError ? ',' : ' and'
×
67
    } password${twoFAError}. If you still have problems, contact an administrator.`;
68
    return Promise.reject(dispatch(setSnackbar(preformatWithRequestID(err.response, errorMessage), null, 'Copy to clipboard')));
×
69
  };
70

71
/*
72
  User management
73
*/
74
export const loginUser = (userData, stayLoggedIn) => dispatch =>
184✔
75
  UsersApi.postLogin(`${useradmApiUrl}/auth/login`, { ...userData, no_expiry: stayLoggedIn })
6✔
76
    .catch(err => {
77
      cleanUp();
1✔
78
      return Promise.resolve(dispatch(handleLoginError(err, userData)));
1✔
79
    })
80
    .then(({ text: response, contentType }) => {
81
      // If the content type is application/json then backend returned SSO configuration.
82
      // user should be redirected to the start sso url to finish login process.
83
      if (contentType.includes(APPLICATION_JSON_CONTENT_TYPE)) {
5✔
84
        const { id } = response;
2✔
85
        const ssoLoginUrl = getSsoStartUrlById(id);
2✔
86
        window.location.replace(ssoLoginUrl);
2✔
87
        return;
2✔
88
      }
89

90
      const token = response;
3✔
91
      if (contentType !== APPLICATION_JWT_CONTENT_TYPE || !token) {
3!
92
        return;
×
93
      }
94
      // save token to local storage & set maxAge if noexpiry checkbox not checked
95
      let now = new Date();
3✔
96
      now.setSeconds(now.getSeconds() + maxSessionAge);
3✔
97
      const expiresAt = stayLoggedIn ? undefined : now.toISOString();
3!
98
      setSessionInfo({ token, expiresAt });
3✔
99
      cookies.remove('JWT', { path: '/' });
3✔
100
      return dispatch(getUser(OWN_USER_ID))
3✔
101
        .catch(e => {
102
          cleanUp();
1✔
103
          return Promise.reject(dispatch(setSnackbar(extractErrorMessage(e))));
1✔
104
        })
105
        .then(() => {
106
          window.sessionStorage.removeItem('pendings-redirect');
2✔
107
          if (window.location.pathname !== '/ui/') {
2!
108
            window.location.replace('/ui/');
2✔
109
          }
110
          return Promise.all([dispatch({ type: UserConstants.SUCCESSFULLY_LOGGED_IN, value: { expiresAt, token } })]);
2✔
111
        });
112
    });
113

114
export const logoutUser = () => (dispatch, getState) => {
184✔
115
  if (Object.keys(getState().app.uploadsById).length) {
8!
116
    return Promise.reject();
×
117
  }
118
  return GeneralApi.post(`${useradmApiUrl}/auth/logout`).finally(() => {
8✔
119
    cleanUp();
8✔
120
    clearAllRetryTimers(setSnackbar);
8✔
121
    return Promise.resolve(dispatch({ type: UserConstants.USER_LOGOUT }));
8✔
122
  });
123
};
124

125
export const passwordResetStart = email => dispatch =>
184✔
126
  GeneralApi.post(`${useradmApiUrl}/auth/password-reset/start`, { email }).catch(err =>
2✔
127
    commonErrorHandler(err, `The password reset request cannot be processed:`, dispatch, undefined, true)
×
128
  );
129

130
export const passwordResetComplete = (secretHash, newPassword) => dispatch =>
184✔
131
  GeneralApi.post(`${useradmApiUrl}/auth/password-reset/complete`, { secret_hash: secretHash, password: newPassword }).catch((err = {}) => {
2!
132
    const { error, response = {} } = err;
×
133
    let errorMsg = '';
×
134
    if (response.status == 400) {
×
135
      errorMsg = 'the link you are using expired or the request is not valid, please try again.';
×
136
    } else {
137
      errorMsg = error;
×
138
    }
139
    dispatch(setSnackbar('The password reset request cannot be processed: ' + errorMsg));
×
140
    return Promise.reject(err);
×
141
  });
142

143
export const verifyEmailStart = () => (dispatch, getState) =>
184✔
144
  GeneralApi.post(`${useradmApiUrl}/auth/verify-email/start`, { email: getCurrentUser(getState()).email })
1✔
145
    .catch(err => commonErrorHandler(err, 'An error occured starting the email verification process:', dispatch))
×
146
    .finally(() => Promise.resolve(dispatch(getUser(OWN_USER_ID))));
1✔
147

148
export const setAccountActivationCode = code => dispatch => Promise.resolve(dispatch({ type: UserConstants.RECEIVED_ACTIVATION_CODE, code }));
184✔
149

150
export const verifyEmailComplete = secret => dispatch =>
184✔
151
  GeneralApi.post(`${useradmApiUrl}/auth/verify-email/complete`, { secret_hash: secret })
2✔
152
    .catch(err => commonErrorHandler(err, 'An error occured completing the email verification process:', dispatch))
1✔
153
    .finally(() => Promise.resolve(dispatch(getUser(OWN_USER_ID))));
2✔
154

155
export const verify2FA = tfaData => dispatch =>
184✔
156
  UsersApi.putVerifyTFA(`${useradmApiUrl}/2faverify`, tfaData)
2✔
157
    .then(() => Promise.resolve(dispatch(getUser(OWN_USER_ID))))
2✔
158
    .catch(err =>
159
      commonErrorHandler(err, 'An error occured validating the verification code: failed to verify token, please try again.', dispatch, undefined, true)
×
160
    );
161

162
export const getUserList = () => dispatch =>
184✔
163
  GeneralApi.get(`${useradmApiUrl}/users`)
19✔
164
    .then(res => {
165
      const users = res.data.reduce((accu, item) => {
19✔
166
        accu[item.id] = item;
38✔
167
        return accu;
38✔
168
      }, {});
169
      return dispatch({ type: UserConstants.RECEIVED_USER_LIST, users });
19✔
170
    })
171
    .catch(err => commonErrorHandler(err, `Users couldn't be loaded.`, dispatch, commonErrorFallback));
×
172

173
export const getUser = id => dispatch =>
184✔
174
  GeneralApi.get(`${useradmApiUrl}/users/${id}`).then(({ data: user }) =>
14✔
175
    Promise.all([
13✔
176
      dispatch({ type: UserConstants.RECEIVED_USER, user }),
177
      dispatch(setHideAnnouncement(false, user.id)),
178
      dispatch(updateUserColumnSettings(undefined, user.id)),
179
      user
180
    ])
181
  );
182

183
export const initializeSelf = () => dispatch => dispatch(getUser(UserConstants.OWN_USER_ID)).then(() => dispatch(initializeAppData()));
184✔
184

185
export const updateUserColumnSettings = (columns, currentUserId) => (dispatch, getState) => {
184✔
186
  const userId = currentUserId ?? getCurrentUser(getState()).id;
16✔
187
  const storageKey = `${userId}-column-widths`;
16✔
188
  let customColumns = [];
16✔
189
  if (!columns) {
16✔
190
    try {
14✔
191
      customColumns = JSON.parse(window.localStorage.getItem(storageKey)) || customColumns;
14!
192
    } catch {
193
      // most likely the column info doesn't exist yet or is lost - continue
194
    }
195
  } else {
196
    customColumns = columns;
2✔
197
  }
198
  window.localStorage.setItem(storageKey, JSON.stringify(customColumns));
16✔
199
  return Promise.resolve(dispatch({ type: UserConstants.SET_CUSTOM_COLUMNS, value: customColumns }));
16✔
200
};
201

202
const actions = {
184✔
203
  create: {
204
    successMessage: 'The user was created successfully.',
205
    errorMessage: 'creating'
206
  },
207
  edit: {
208
    successMessage: 'The user has been updated.',
209
    errorMessage: 'editing'
210
  },
211
  remove: {
212
    successMessage: 'The user was removed from the system.',
213
    errorMessage: 'removing'
214
  }
215
};
216

217
const userActionErrorHandler = (err, type, dispatch) => commonErrorHandler(err, `There was an error ${actions[type].errorMessage} the user.`, dispatch);
184✔
218

219
export const createUser =
220
  ({ assignToSso, shouldResetPassword, ...userData }) =>
184✔
221
  (dispatch, getState) => {
4✔
222
    const { email, sso = [] } = getCurrentUser(getState());
4✔
223
    let ssoConfig = sso.find(({ subject }) => subject === email);
4✔
224
    if (!ssoConfig && sso.length) {
4✔
225
      ssoConfig = sso[0];
1✔
226
    }
227
    const user = {
4✔
228
      ...userData,
229
      send_reset_password: shouldResetPassword,
230
      sso: !userData.password && !shouldResetPassword && assignToSso ? [ssoConfig] : undefined
14✔
231
    };
232
    return GeneralApi.post(`${useradmApiUrl}/users`, user)
4✔
233
      .then(() =>
234
        Promise.all([dispatch({ type: UserConstants.CREATED_USER, user }), dispatch(getUserList()), dispatch(setSnackbar(actions.create.successMessage))])
4✔
235
      )
236
      .catch(err => userActionErrorHandler(err, 'create', dispatch));
×
237
  };
238

239
export const removeUser = userId => dispatch =>
184✔
240
  GeneralApi.delete(`${useradmApiUrl}/users/${userId}`)
1✔
241
    .then(() =>
242
      Promise.all([dispatch({ type: UserConstants.REMOVED_USER, userId }), dispatch(getUserList()), dispatch(setSnackbar(actions.remove.successMessage))])
1✔
243
    )
244
    .catch(err => userActionErrorHandler(err, 'remove', dispatch));
×
245

246
export const editUser = (userId, userData) => (dispatch, getState) => {
184✔
247
  return GeneralApi.put(`${useradmApiUrl}/users/${userId}`, userData).then(() =>
3✔
248
    Promise.all([
1✔
249
      dispatch({ type: UserConstants.UPDATED_USER, userId: userId === UserConstants.OWN_USER_ID ? getState().users.currentUser : userId, user: userData }),
1!
250
      dispatch(setSnackbar(actions.edit.successMessage))
251
    ])
252
  );
253
};
254

255
export const enableUser2fa =
256
  (userId = OWN_USER_ID) =>
184✔
257
  dispatch =>
2✔
258
    GeneralApi.post(`${useradmApiUrl}/users/${userId}/2fa/enable`)
2✔
259
      .catch(err => commonErrorHandler(err, `There was an error enabling Two Factor authentication for the user.`, dispatch))
×
260
      .then(() => Promise.resolve(dispatch(getUser(userId))));
2✔
261

262
export const disableUser2fa =
263
  (userId = OWN_USER_ID) =>
184!
264
  dispatch =>
1✔
265
    GeneralApi.post(`${useradmApiUrl}/users/${userId}/2fa/disable`)
1✔
266
      .catch(err => commonErrorHandler(err, `There was an error disabling Two Factor authentication for the user.`, dispatch))
×
267
      .then(() => Promise.resolve(dispatch(getUser(userId))));
1✔
268

269
/* RBAC related things follow:  */
270

271
const mergePermissions = (existingPermissions = { ...emptyUiPermissions }, addedPermissions) =>
184!
272
  Object.entries(existingPermissions).reduce(
1,518✔
273
    (accu, [key, value]) => {
274
      let values;
275
      if (!accu[key]) {
2,857✔
276
        accu[key] = value;
327✔
277
        return accu;
327✔
278
      }
279
      if (Array.isArray(value)) {
2,530✔
280
        values = [...value, ...accu[key]].filter(duplicateFilter);
1,554✔
281
      } else {
282
        values = mergePermissions(accu[key], { ...value });
976✔
283
      }
284
      accu[key] = values;
2,530✔
285
      return accu;
2,530✔
286
    },
287
    { ...addedPermissions }
288
  );
289

290
const mapHttpPermission = permission =>
184✔
291
  Object.entries(uiPermissionsByArea).reduce(
126✔
292
    (accu, [area, definition]) => {
293
      const endpointMatches = definition.endpoints.filter(
630✔
294
        endpoint => endpoint.path.test(permission.value) && (endpoint.types.includes(permission.type) || permission.type === PermissionTypes.Any)
1,638✔
295
      );
296
      if (permission.value === PermissionTypes.Any || (permission.value.includes(apiRoot) && endpointMatches.length)) {
630✔
297
        const endpointUiPermission = endpointMatches.reduce((endpointAccu, endpoint) => [...endpointAccu, ...endpoint.uiPermissions], []);
189✔
298
        const collector = (endpointUiPermission || definition.uiPermissions)
99!
299
          .reduce((permissionsAccu, uiPermission) => {
300
            if (permission.type === PermissionTypes.Any || (!endpointMatches.length && uiPermission.verbs.some(verb => verb === permission.type))) {
207!
301
              permissionsAccu.push(uiPermission.value);
207✔
302
            }
303
            return permissionsAccu;
207✔
304
          }, [])
305
          .filter(duplicateFilter);
306
        if (Array.isArray(accu[area])) {
99✔
307
          accu[area] = [...accu[area], ...collector].filter(duplicateFilter);
54✔
308
        } else {
309
          accu[area] = mergePermissions(accu[area], { [scopedPermissionAreas[area].excessiveAccessSelector]: collector });
45✔
310
        }
311
      }
312
      return accu;
630✔
313
    },
314
    { ...emptyUiPermissions }
315
  );
316

317
const permissionActionTypes = {
184✔
318
  any: mapHttpPermission,
319
  CREATE_DEPLOYMENT: permission =>
320
    permission.type === PermissionTypes.DeviceGroup
9!
321
      ? {
322
          deployments: [uiPermissionsById.deploy.value],
323
          groups: { [permission.value]: [uiPermissionsById.deploy.value] }
324
        }
325
      : {},
326
  http: mapHttpPermission,
327
  REMOTE_TERMINAL: permission =>
328
    permission.type === PermissionTypes.DeviceGroup
×
329
      ? {
330
          groups: { [permission.value]: [uiPermissionsById.connect.value] }
331
        }
332
      : {},
333
  VIEW_DEVICE: permission =>
334
    permission.type === PermissionTypes.DeviceGroup
9!
335
      ? {
336
          groups: { [permission.value]: [uiPermissionsById.read.value] }
337
        }
338
      : {}
339
};
340

341
const combinePermissions = (existingPermissions, additionalPermissions = {}) =>
184!
342
  Object.entries(additionalPermissions).reduce((accu, [name, permissions]) => {
86✔
343
    let maybeExistingPermissions = accu[name] || [];
86✔
344
    accu[name] = [...permissions, ...maybeExistingPermissions].filter(duplicateFilter);
86✔
345
    return accu;
86✔
346
  }, existingPermissions);
347

348
const tryParseCustomPermission = permission => {
184✔
349
  const uiPermissions = permissionActionTypes[permission.action](permission.object);
144✔
350
  const result = mergePermissions({ ...emptyUiPermissions }, uiPermissions);
144✔
351
  return { isCustom: true, permission, result };
144✔
352
};
353

354
const customPermissionHandler = (accu, permission) => {
184✔
355
  let processor = tryParseCustomPermission(permission);
144✔
356
  return {
144✔
357
    ...accu,
358
    isCustom: accu.isCustom || processor.isCustom,
171✔
359
    uiPermissions: mergePermissions(accu.uiPermissions, processor.result)
360
  };
361
};
362

363
const mapPermissionSet = (permissionSetName, names, scope, existingGroupsPermissions = {}) => {
184✔
364
  const permission = Object.values(uiPermissionsById).find(permission => permission.permissionSets[scope] === permissionSetName).value;
267✔
365
  const scopedPermissions = names.reduce((accu, name) => combinePermissions(accu, { [name]: [permission] }), existingGroupsPermissions);
86✔
366
  return Object.entries(scopedPermissions).reduce((accu, [key, permissions]) => ({ ...accu, [key]: deriveImpliedAreaPermissions(scope, permissions) }), {});
86✔
367
};
368

369
const isEmptyPermissionSet = permissionSet =>
184✔
370
  !Object.values(permissionSet).reduce((accu, permissions) => {
135✔
371
    if (Array.isArray(permissions)) {
675✔
372
      return accu || !!permissions.length;
405✔
373
    }
374
    return accu || !isEmpty(permissions);
270✔
375
  }, false);
376

377
const parseRolePermissions = ({ permission_sets_with_scope = [], permissions = [] }, permissionSets) => {
184✔
378
  const preliminaryResult = permission_sets_with_scope.reduce(
63✔
379
    (accu, permissionSet) => {
380
      let processor = permissionSets[permissionSet.name];
171✔
381
      if (!processor) {
171!
382
        return accu;
×
383
      }
384
      const scope = Object.keys(scopedPermissionAreas).find(scope => uiPermissionsByArea[scope].scope === permissionSet.scope?.type);
306✔
385
      if (scope) {
171✔
386
        const result = mapPermissionSet(permissionSet.name, permissionSet.scope.value, scope, accu.uiPermissions[scope]);
36✔
387
        return { ...accu, uiPermissions: { ...accu.uiPermissions, [scope]: result } };
36✔
388
      } else if (isEmptyPermissionSet(processor.result)) {
135!
389
        return processor.permissions.reduce(customPermissionHandler, accu);
×
390
      }
391
      return {
135✔
392
        ...accu,
393
        isCustom: accu.isCustom || processor.isCustom,
270✔
394
        uiPermissions: mergePermissions(accu.uiPermissions, processor.result)
395
      };
396
    },
397
    { isCustom: false, uiPermissions: { ...emptyUiPermissions, groups: {}, releases: {} } }
398
  );
399
  return permissions.reduce(customPermissionHandler, preliminaryResult);
63✔
400
};
401

402
export const normalizeRbacRoles = (roles, rolesById, permissionSets) =>
184✔
403
  roles.reduce(
10✔
404
    (accu, role) => {
405
      let normalizedPermissions;
406
      let isCustom = false;
120✔
407
      if (rolesById[role.name]) {
120✔
408
        normalizedPermissions = {
57✔
409
          ...rolesById[role.name].uiPermissions,
410
          groups: { ...rolesById[role.name].uiPermissions.groups },
411
          releases: { ...rolesById[role.name].uiPermissions.releases }
412
        };
413
      } else {
414
        const result = parseRolePermissions(role, permissionSets);
63✔
415
        normalizedPermissions = result.uiPermissions;
63✔
416
        isCustom = result.isCustom;
63✔
417
      }
418

419
      const roleState = accu[role.name] ?? { ...emptyRole };
120✔
420
      accu[role.name] = {
120✔
421
        ...roleState,
422
        ...role,
423
        description: roleState.description ? roleState.description : role.description,
120✔
424
        editable: !defaultRolesById[role.name] && !isCustom && (typeof roleState.editable !== 'undefined' ? roleState.editable : true),
276✔
425
        isCustom,
426
        name: roleState.name ? roleState.name : role.name,
120✔
427
        uiPermissions: normalizedPermissions
428
      };
429
      return accu;
120✔
430
    },
431
    { ...rolesById }
432
  );
433

434
export const mapUserRolesToUiPermissions = (userRoles, roles) =>
184✔
435
  userRoles.reduce(
89✔
436
    (accu, roleId) => {
437
      if (!(roleId && roles[roleId])) {
74!
438
        return accu;
×
439
      }
440
      return mergePermissions(accu, roles[roleId].uiPermissions);
74✔
441
    },
442
    { ...emptyUiPermissions }
443
  );
444

445
export const getPermissionSets = () => (dispatch, getState) =>
184✔
446
  GeneralApi.get(`${useradmApiUrlv2}/permission_sets?per_page=500`)
10✔
447
    .then(({ data }) => {
448
      const permissionSets = data.reduce(
10✔
449
        (accu, permissionSet) => {
450
          const permissionSetState = accu[permissionSet.name] ?? {};
140✔
451
          let permissionSetObject = { ...permissionSetState, ...permissionSet };
140✔
452
          permissionSetObject.result = Object.values(uiPermissionsById).reduce(
140✔
453
            (accu, item) =>
454
              Object.entries(item.permissionSets).reduce((collector, [area, permissionSet]) => {
840✔
455
                if (scopedPermissionAreas[area]) {
1,680✔
456
                  return collector;
1,120✔
457
                }
458
                if (permissionSet === permissionSetObject.name) {
560✔
459
                  collector[area] = [...collector[area], item.value].filter(duplicateFilter);
40✔
460
                }
461
                return collector;
560✔
462
              }, accu),
463
            { ...emptyUiPermissions, ...(permissionSetObject.result ?? {}) }
149✔
464
          );
465
          const scopes = Object.values(scopedPermissionAreas).reduce((accu, { key, scopeType }) => {
140✔
466
            if (permissionSetObject.supported_scope_types?.includes(key) || permissionSetObject.supported_scope_types?.includes(scopeType)) {
280✔
467
              accu.push(key);
50✔
468
            }
469
            return accu;
280✔
470
          }, []);
471
          permissionSetObject = scopes.reduce((accu, scope) => {
140✔
472
            accu.result[scope] = mapPermissionSet(permissionSetObject.name, [scopedPermissionAreas[scope].excessiveAccessSelector], scope);
50✔
473
            return accu;
50✔
474
          }, permissionSetObject);
475
          accu[permissionSet.name] = permissionSetObject;
140✔
476
          return accu;
140✔
477
        },
478
        { ...getState().users.permissionSetsById }
479
      );
480
      return Promise.all([dispatch({ type: UserConstants.RECEIVED_PERMISSION_SETS, value: permissionSets }), permissionSets]);
10✔
481
    })
482
    .catch(() => console.log('Permission set retrieval failed - likely accessing a non-RBAC backend'));
×
483

484
export const getRoles = () => (dispatch, getState) =>
184✔
485
  Promise.all([GeneralApi.get(`${useradmApiUrlv2}/roles?per_page=500`), dispatch(getPermissionSets())])
10✔
486
    .then(results => {
487
      if (!results) {
10!
488
        return Promise.resolve();
×
489
      }
490
      const [{ data: roles }, permissionSetTasks] = results;
10✔
491
      const rolesById = normalizeRbacRoles(roles, getState().users.rolesById, permissionSetTasks[permissionSetTasks.length - 1]);
10✔
492
      return Promise.resolve(dispatch({ type: UserConstants.RECEIVED_ROLES, value: rolesById }));
10✔
493
    })
494
    .catch(() => console.log('Role retrieval failed - likely accessing a non-RBAC backend'));
×
495

496
const deriveImpliedAreaPermissions = (area, areaPermissions, skipPermissions = []) => {
184✔
497
  const highestAreaPermissionLevelSelected = areaPermissions.reduce(
94✔
498
    (highest, current) => (uiPermissionsById[current].permissionLevel > highest ? uiPermissionsById[current].permissionLevel : highest),
99✔
499
    1
500
  );
501
  return uiPermissionsByArea[area].uiPermissions.reduce((permissions, current) => {
94✔
502
    if ((current.permissionLevel < highestAreaPermissionLevelSelected || areaPermissions.includes(current.value)) && !skipPermissions.includes(current.value)) {
459✔
503
      permissions.push(current.value);
160✔
504
    }
505
    return permissions;
459✔
506
  }, []);
507
};
508

509
/**
510
 * transforms [{ group: "groupName",  uiPermissions: ["read", "manage", "connect"] }, ...] to
511
 * [{ name: "ReadDevices", scope: { type: "DeviceGroups", value: ["groupName", ...] } }, ...]
512
 */
513
const transformAreaRoleDataToScopedPermissionsSets = (area, areaPermissions, excessiveAccessSelector) => {
184✔
514
  const permissionSetObject = areaPermissions.reduce((accu, { item, uiPermissions }) => {
4✔
515
    // if permission area is release and item is release tag (not all releases) then exclude upload permission as it cannot be applied to tags
516
    const skipPermissions = scopedPermissionAreas.releases.key === area && item !== ALL_RELEASES ? [uiPermissionsById.upload.value] : [];
6✔
517
    const impliedPermissions = deriveImpliedAreaPermissions(area, uiPermissions, skipPermissions);
6✔
518
    accu = impliedPermissions.reduce((itemPermissionAccu, impliedPermission) => {
6✔
519
      const permissionSetState = itemPermissionAccu[uiPermissionsById[impliedPermission].permissionSets[area]] ?? {
7✔
520
        type: uiPermissionsByArea[area].scope,
521
        value: []
522
      };
523
      itemPermissionAccu[uiPermissionsById[impliedPermission].permissionSets[area]] = {
7✔
524
        ...permissionSetState,
525
        value: [...permissionSetState.value, item]
526
      };
527
      return itemPermissionAccu;
7✔
528
    }, accu);
529
    return accu;
6✔
530
  }, {});
531
  return Object.entries(permissionSetObject).map(([name, { value, ...scope }]) => {
4✔
532
    if (value.includes(excessiveAccessSelector)) {
7✔
533
      return { name };
3✔
534
    }
535
    return { name, scope: { ...scope, value: value.filter(duplicateFilter) } };
4✔
536
  });
537
};
538

539
const transformRoleDataToRole = (roleData, roleState = {}) => {
184✔
540
  const role = { ...roleState, ...roleData };
3✔
541
  const { description = '', name, uiPermissions = emptyUiPermissions } = role;
3!
542
  const { maybeUiPermissions, remainderKeys } = Object.entries(emptyUiPermissions).reduce(
3✔
543
    (accu, [key, emptyPermissions]) => {
544
      if (!scopedPermissionAreas[key]) {
15✔
545
        accu.remainderKeys.push(key);
9✔
546
      } else if (uiPermissions[key]) {
6✔
547
        accu.maybeUiPermissions[key] = uiPermissions[key].reduce(itemUiPermissionsReducer, emptyPermissions);
4✔
548
      }
549
      return accu;
15✔
550
    },
551
    { maybeUiPermissions: {}, remainderKeys: [] }
552
  );
553
  const { permissionSetsWithScope, roleUiPermissions } = remainderKeys.reduce(
3✔
554
    (accu, area) => {
555
      const areaPermissions = role.uiPermissions[area];
9✔
556
      if (!Array.isArray(areaPermissions)) {
9✔
557
        return accu;
7✔
558
      }
559
      const impliedPermissions = deriveImpliedAreaPermissions(area, areaPermissions);
2✔
560
      accu.roleUiPermissions[area] = impliedPermissions;
2✔
561
      const mappedPermissions = impliedPermissions.map(uiPermission => ({ name: uiPermissionsById[uiPermission].permissionSets[area] }));
2✔
562
      accu.permissionSetsWithScope.push(...mappedPermissions);
2✔
563
      return accu;
2✔
564
    },
565
    { permissionSetsWithScope: [{ name: defaultPermissionSets.Basic.name }], roleUiPermissions: {} }
566
  );
567
  const scopedPermissionSets = Object.values(scopedPermissionAreas).reduce((accu, { key, excessiveAccessSelector }) => {
3✔
568
    if (!uiPermissions[key]) {
6✔
569
      return accu;
2✔
570
    }
571
    accu.push(...transformAreaRoleDataToScopedPermissionsSets(key, uiPermissions[key], excessiveAccessSelector));
4✔
572
    return accu;
4✔
573
  }, []);
574
  return {
3✔
575
    permissionSetsWithScope: [...permissionSetsWithScope, ...scopedPermissionSets],
576
    role: {
577
      ...emptyRole,
578
      name,
579
      description: description ? description : roleState.description,
3!
580
      uiPermissions: {
581
        ...emptyUiPermissions,
582
        ...roleUiPermissions,
583
        ...maybeUiPermissions
584
      }
585
    }
586
  };
587
};
588

589
const roleActions = {
184✔
590
  create: {
591
    successMessage: 'The role was created successfully.',
592
    errorMessage: 'creating'
593
  },
594
  edit: {
595
    successMessage: 'The role has been updated.',
596
    errorMessage: 'editing'
597
  },
598
  remove: {
599
    successMessage: 'The role was deleted successfully.',
600
    errorMessage: 'removing'
601
  }
602
};
603

604
const roleActionErrorHandler = (err, type, dispatch) => commonErrorHandler(err, `There was an error ${roleActions[type].errorMessage} the role.`, dispatch);
184✔
605

606
export const createRole = roleData => dispatch => {
184✔
607
  const { permissionSetsWithScope, role } = transformRoleDataToRole(roleData);
1✔
608
  return GeneralApi.post(`${useradmApiUrlv2}/roles`, {
1✔
609
    name: role.name,
610
    description: role.description,
611
    permission_sets_with_scope: permissionSetsWithScope
612
  })
613
    .then(() =>
614
      Promise.all([
1✔
615
        dispatch({ type: UserConstants.CREATED_ROLE, role, roleId: role.name }),
616
        dispatch(getRoles()),
617
        dispatch(setSnackbar(roleActions.create.successMessage))
618
      ])
619
    )
620
    .catch(err => roleActionErrorHandler(err, 'create', dispatch));
×
621
};
622

623
export const editRole = roleData => (dispatch, getState) => {
184✔
624
  const { permissionSetsWithScope, role } = transformRoleDataToRole(roleData, getState().users.rolesById[roleData.name]);
2✔
625
  return GeneralApi.put(`${useradmApiUrlv2}/roles/${role.name}`, {
2✔
626
    description: role.description,
627
    name: role.name,
628
    permission_sets_with_scope: permissionSetsWithScope
629
  })
630
    .then(() =>
631
      Promise.all([
2✔
632
        dispatch({ type: UserConstants.UPDATED_ROLE, role, roleId: role.name }),
633
        dispatch(getRoles()),
634
        dispatch(setSnackbar(roleActions.edit.successMessage))
635
      ])
636
    )
637
    .catch(err => roleActionErrorHandler(err, 'edit', dispatch));
×
638
};
639

640
export const removeRole = roleId => (dispatch, getState) =>
184✔
641
  GeneralApi.delete(`${useradmApiUrlv2}/roles/${roleId}`)
2✔
642
    .then(() => {
643
      // eslint-disable-next-line no-unused-vars
644
      const { [roleId]: toBeRemoved, ...rolesById } = getState().users.rolesById;
2✔
645
      return Promise.all([
2✔
646
        dispatch({ type: UserConstants.REMOVED_ROLE, value: rolesById }),
647
        dispatch(getRoles()),
648
        dispatch(setSnackbar(roleActions.remove.successMessage))
649
      ]);
650
    })
651
    .catch(err => roleActionErrorHandler(err, 'remove', dispatch));
×
652

653
/*
654
  Global settings
655
*/
656
export const getGlobalSettings = () => dispatch =>
184✔
657
  GeneralApi.get(`${useradmApiUrl}/settings`).then(({ data: settings, headers: { etag } }) => {
14✔
658
    window.sessionStorage.setItem(UserConstants.settingsKeys.initialized, true);
14✔
659
    return Promise.all([dispatch({ type: UserConstants.SET_GLOBAL_SETTINGS, settings }), dispatch(setOfflineThreshold()), etag]);
14✔
660
  });
661

662
export const saveGlobalSettings =
663
  (settings, beOptimistic = false, notify = false) =>
184✔
664
  (dispatch, getState) => {
10✔
665
    if (!window.sessionStorage.getItem(UserConstants.settingsKeys.initialized) && !beOptimistic) {
10!
666
      return;
×
667
    }
668
    return Promise.resolve(dispatch(getGlobalSettings())).then(result => {
10✔
669
      let updatedSettings = { ...getState().users.globalSettings, ...settings };
10✔
670
      if (getCurrentUser(getState()).verified) {
10✔
671
        updatedSettings['2fa'] = twoFAStates.enabled;
9✔
672
      } else {
673
        delete updatedSettings['2fa'];
1✔
674
      }
675
      let tasks = [dispatch({ type: UserConstants.SET_GLOBAL_SETTINGS, settings: updatedSettings })];
10✔
676
      const headers = result[result.length - 1] ? { 'If-Match': result[result.length - 1] } : {};
10!
677
      return GeneralApi.post(`${useradmApiUrl}/settings`, updatedSettings, { headers })
10✔
678
        .then(() => {
679
          if (notify) {
10✔
680
            tasks.push(dispatch(setSnackbar('Settings saved successfully')));
1✔
681
          }
682
          return Promise.all(tasks);
10✔
683
        })
684
        .catch(err => {
685
          if (beOptimistic) {
×
686
            return Promise.all([tasks]);
×
687
          }
688
          console.log(err);
×
689
          return commonErrorHandler(err, `The settings couldn't be saved.`, dispatch);
×
690
        });
691
    });
692
  };
693

694
export const getUserSettings = () => dispatch =>
184✔
695
  GeneralApi.get(`${useradmApiUrl}/settings/me`).then(({ data: settings, headers: { etag } }) => {
58✔
696
    window.sessionStorage.setItem(UserConstants.settingsKeys.initialized, true);
58✔
697
    return Promise.all([dispatch({ type: UserConstants.SET_USER_SETTINGS, settings }), etag]);
58✔
698
  });
699

700
export const saveUserSettings =
701
  (settings = { onboarding: {} }) =>
184✔
702
  (dispatch, getState) => {
54✔
703
    if (!getState().users.currentUser) {
54!
704
      return Promise.resolve();
×
705
    }
706
    return Promise.resolve(dispatch(getUserSettings())).then(result => {
54✔
707
      const userSettings = getUserSettingsSelector(getState());
54✔
708
      const onboardingState = getOnboardingState(getState());
54✔
709
      const tooltipState = getTooltipsState(getState());
54✔
710
      const updatedSettings = {
54✔
711
        ...userSettings,
712
        ...settings,
713
        onboarding: {
714
          ...onboardingState,
715
          ...settings.onboarding
716
        },
717
        tooltips: tooltipState
718
      };
719
      const headers = result[result.length - 1] ? { 'If-Match': result[result.length - 1] } : {};
54!
720
      return Promise.all([
54✔
721
        Promise.resolve(dispatch({ type: UserConstants.SET_USER_SETTINGS, settings: updatedSettings })),
722
        GeneralApi.post(`${useradmApiUrl}/settings/me`, updatedSettings, { headers })
723
      ]).catch(() => dispatch({ type: UserConstants.SET_USER_SETTINGS, settings: userSettings }));
×
724
    });
725
  };
726

727
export const get2FAQRCode = () => dispatch =>
184✔
728
  GeneralApi.get(`${useradmApiUrl}/2faqr`).then(res => dispatch({ type: UserConstants.RECEIVED_QR_CODE, value: res.data.qr }));
2✔
729

730
/*
731
  Onboarding
732
*/
733
export const setShowConnectingDialog = show => dispatch => dispatch({ type: UserConstants.SET_SHOW_CONNECT_DEVICE, show: Boolean(show) });
184✔
734

735
export const setHideAnnouncement = (shouldHide, userId) => (dispatch, getState) => {
184✔
736
  const currentUserId = userId || getCurrentUser(getState()).id;
14✔
737
  const hash = getState().app.hostedAnnouncement ? hashString(getState().app.hostedAnnouncement) : '';
14✔
738
  const announceCookie = cookies.get(`${currentUserId}${hash}`);
14✔
739
  if (shouldHide || (hash.length && typeof announceCookie !== 'undefined')) {
14!
740
    cookies.set(`${currentUserId}${hash}`, true, { maxAge: 604800 });
1✔
741
    return Promise.resolve(dispatch({ type: AppConstants.SET_ANNOUNCEMENT, announcement: undefined }));
1✔
742
  }
743
  return Promise.resolve();
13✔
744
};
745

746
export const getTokens = () => (dispatch, getState) =>
184✔
747
  GeneralApi.get(`${useradmApiUrl}/settings/tokens`).then(({ data: tokens }) => {
15✔
748
    const user = getCurrentUser(getState());
15✔
749
    const updatedUser = {
15✔
750
      ...user,
751
      tokens
752
    };
753
    return Promise.resolve(dispatch({ type: UserConstants.UPDATED_USER, user: updatedUser, userId: user.id }));
15✔
754
  });
755

756
const ONE_YEAR = 31536000;
184✔
757

758
export const generateToken =
759
  ({ expiresIn = ONE_YEAR, name }) =>
184✔
760
  dispatch =>
5✔
761
    GeneralApi.post(`${useradmApiUrl}/settings/tokens`, { name, expires_in: expiresIn })
5✔
762
      .then(({ data: token }) => Promise.all([dispatch(getTokens()), token]))
5✔
763
      .catch(err => commonErrorHandler(err, 'There was an error creating the token:', dispatch));
×
764

765
export const revokeToken = token => dispatch =>
184✔
766
  GeneralApi.delete(`${useradmApiUrl}/settings/tokens/${token.id}`).then(() => Promise.resolve(dispatch(getTokens())));
1✔
767

768
export const setTooltipReadState =
769
  (id, readState = UserConstants.READ_STATES.read, persist) =>
184!
770
  dispatch =>
1✔
771
    Promise.resolve(dispatch({ type: UserConstants.SET_TOOLTIP_STATE, id, value: { readState } })).then(() => {
1✔
772
      if (persist) {
1!
773
        return Promise.resolve(dispatch(saveUserSettings()));
1✔
774
      }
775
      return Promise.resolve();
×
776
    });
777

778
export const setAllTooltipsReadState =
779
  (readState = UserConstants.READ_STATES.read) =>
184!
780
  dispatch => {
1✔
781
    const updatedTips = Object.keys(HELPTOOLTIPS).reduce((accu, id) => ({ ...accu, [id]: { readState } }), {});
28✔
782
    return Promise.resolve(dispatch({ type: UserConstants.SET_TOOLTIPS_STATE, value: updatedTips })).then(() => dispatch(saveUserSettings()));
1✔
783
  };
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc