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

mendersoftware / gui / 1057188406

01 Nov 2023 04:24AM UTC coverage: 82.824% (-17.1%) from 99.964%
1057188406

Pull #4134

gitlab-ci

web-flow
chore: Bump uuid from 9.0.0 to 9.0.1

Bumps [uuid](https://github.com/uuidjs/uuid) from 9.0.0 to 9.0.1.
- [Changelog](https://github.com/uuidjs/uuid/blob/main/CHANGELOG.md)
- [Commits](https://github.com/uuidjs/uuid/compare/v9.0.0...v9.0.1)

---
updated-dependencies:
- dependency-name: uuid
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Pull Request #4134: chore: Bump uuid from 9.0.0 to 9.0.1

4349 of 6284 branches covered (0.0%)

8313 of 10037 relevant lines covered (82.82%)

200.97 hits per line

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

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

18
import Api, { apiUrl, headerNames } from '../api/general-api';
19
import { getToken } from '../auth';
20
import { SET_ANNOUNCEMENT, SORTING_OPTIONS, TIMEOUTS, locations } from '../constants/appConstants';
21
import { DEVICE_LIST_DEFAULTS } from '../constants/deviceConstants';
22
import {
23
  RECEIVE_AUDIT_LOGS,
24
  RECEIVE_CURRENT_CARD,
25
  RECEIVE_EXTERNAL_DEVICE_INTEGRATIONS,
26
  RECEIVE_SAML_CONFIGS,
27
  RECEIVE_SETUP_INTENT,
28
  RECEIVE_WEBHOOK_EVENTS,
29
  SET_AUDITLOG_STATE,
30
  SET_ORGANIZATION
31
} from '../constants/organizationConstants';
32
import { deepCompare } from '../helpers';
33
import { getTenantCapabilities } from '../selectors';
34
import { commonErrorFallback, commonErrorHandler, setFirstLoginAfterSignup, setSnackbar } from './appActions';
35
import { deviceAuthV2, iotManagerBaseURL } from './deviceActions';
36

37
const cookies = new Cookies();
184✔
38
export const auditLogsApiUrl = `${apiUrl.v1}/auditlogs`;
184✔
39
export const tenantadmApiUrlv1 = `${apiUrl.v1}/tenantadm`;
184✔
40
export const tenantadmApiUrlv2 = `${apiUrl.v2}/tenantadm`;
184✔
41
export const samlIdpApiUrlv1 = `${apiUrl.v1}/useradm/sso/idp/metadata`;
184✔
42

43
const { page: defaultPage, perPage: defaultPerPage } = DEVICE_LIST_DEFAULTS;
184✔
44

45
export const cancelRequest = (tenantId, reason) => dispatch =>
184✔
46
  Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/cancel`, { reason: reason }).then(() =>
1✔
47
    Promise.resolve(dispatch(setSnackbar('Deactivation request was sent successfully', TIMEOUTS.fiveSeconds, '')))
1✔
48
  );
49

50
export const getTargetLocation = key => {
184✔
51
  if (devLocations.includes(window.location.hostname)) {
14✔
52
    return '';
6✔
53
  }
54
  let subdomainSections = window.location.hostname.substring(0, window.location.hostname.indexOf(locations.us.location)).split('.');
8✔
55
  subdomainSections = subdomainSections.splice(0, subdomainSections.length - 1);
8✔
56
  if (!subdomainSections.find(section => section === key)) {
8✔
57
    subdomainSections = key === locations.us.key ? subdomainSections.filter(section => !locations[section]) : [...subdomainSections, key];
7✔
58
    return `https://${[...subdomainSections, ...locations.us.location.split('.')].join('.')}`;
7✔
59
  }
60
  return `https://${window.location.hostname}`;
1✔
61
};
62

63
const devLocations = ['localhost', 'docker.mender.io'];
184✔
64
export const createOrganizationTrial = data => dispatch => {
184✔
65
  const { key } = locations[data.location];
2✔
66
  const targetLocation = getTargetLocation(key);
2✔
67
  const target = `${targetLocation}${tenantadmApiUrlv2}/tenants/trial`;
2✔
68
  return Api.postUnauthorized(target, data)
2✔
69
    .catch(err => {
70
      if (err.response.status >= 400 && err.response.status < 500) {
×
71
        dispatch(setSnackbar(err.response.data.error, TIMEOUTS.fiveSeconds, ''));
×
72
        return Promise.reject(err);
×
73
      }
74
    })
75
    .then(({ headers }) => {
76
      cookies.remove('oauth');
2✔
77
      cookies.remove('externalID');
2✔
78
      cookies.remove('email');
2✔
79
      dispatch(setFirstLoginAfterSignup(true));
2✔
80
      return new Promise(resolve =>
2✔
81
        setTimeout(() => {
2✔
82
          window.location.assign(`${targetLocation}${headers.location || ''}`);
×
83
          return resolve();
×
84
        }, TIMEOUTS.fiveSeconds)
85
      );
86
    });
87
};
88

89
export const startCardUpdate = () => dispatch =>
184✔
90
  Api.post(`${tenantadmApiUrlv2}/billing/card`)
1✔
91
    .then(res => {
92
      dispatch({
1✔
93
        type: RECEIVE_SETUP_INTENT,
94
        intentId: res.data.intent_id
95
      });
96
      return Promise.resolve(res.data.secret);
1✔
97
    })
98
    .catch(err => commonErrorHandler(err, `Updating the card failed:`, dispatch));
×
99

100
export const confirmCardUpdate = () => (dispatch, getState) =>
184✔
101
  Api.post(`${tenantadmApiUrlv2}/billing/card/${getState().organization.intentId}/confirm`)
1✔
102
    .then(() =>
103
      Promise.all([
1✔
104
        dispatch(setSnackbar('Payment card was updated successfully')),
105
        dispatch({
106
          type: RECEIVE_SETUP_INTENT,
107
          intentId: null
108
        })
109
      ])
110
    )
111
    .catch(err => commonErrorHandler(err, `Updating the card failed:`, dispatch));
×
112

113
export const getCurrentCard = () => dispatch =>
184✔
114
  Api.get(`${tenantadmApiUrlv2}/billing`).then(res => {
2✔
115
    const { last4, exp_month, exp_year, brand } = res.data.card || {};
1!
116
    return Promise.resolve(
1✔
117
      dispatch({
118
        type: RECEIVE_CURRENT_CARD,
119
        card: {
120
          brand,
121
          last4,
122
          expiration: { month: exp_month, year: exp_year }
123
        }
124
      })
125
    );
126
  });
127

128
export const startUpgrade = tenantId => dispatch =>
184✔
129
  Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/upgrade/start`)
1✔
130
    .then(({ data }) => Promise.resolve(data.secret))
1✔
131
    .catch(err => commonErrorHandler(err, `There was an error upgrading your account:`, dispatch));
×
132

133
export const cancelUpgrade = tenantId => () => Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/upgrade/cancel`);
184✔
134

135
export const completeUpgrade = (tenantId, plan) => dispatch =>
184✔
136
  Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/upgrade/complete`, { plan })
1✔
137
    .catch(err => commonErrorHandler(err, `There was an error upgrading your account:`, dispatch))
×
138
    .then(() => Promise.resolve(dispatch(getUserOrganization())));
1✔
139

140
const prepareAuditlogQuery = ({ startDate, endDate, user: userFilter, type, detail: detailFilter, sort = {} }) => {
184✔
141
  const userId = userFilter?.id || userFilter;
13✔
142
  const detail = detailFilter?.id || detailFilter;
13✔
143
  const createdAfter = startDate ? `&created_after=${Math.round(Date.parse(startDate) / 1000)}` : '';
13✔
144
  const createdBefore = endDate ? `&created_before=${Math.round(Date.parse(endDate) / 1000)}` : '';
13✔
145
  const typeSearch = type ? `&object_type=${type.value}`.toLowerCase() : '';
13!
146
  const userSearch = userId ? `&actor_id=${userId}` : '';
13!
147
  const objectSearch = type && detail ? `&${type.queryParameter}=${encodeURIComponent(detail)}` : '';
13!
148
  const { direction = SORTING_OPTIONS.desc } = sort;
13✔
149
  return `${createdAfter}${createdBefore}${userSearch}${typeSearch}${objectSearch}&sort=${direction}`;
13✔
150
};
151

152
export const getAuditLogs = selectionState => (dispatch, getState) => {
184✔
153
  const { page, perPage } = selectionState;
12✔
154
  const { hasAuditlogs } = getTenantCapabilities(getState());
12✔
155
  if (!hasAuditlogs) {
12✔
156
    return Promise.resolve();
1✔
157
  }
158
  return Api.get(`${auditLogsApiUrl}/logs?page=${page}&per_page=${perPage}${prepareAuditlogQuery(selectionState)}`)
11✔
159
    .then(res => {
160
      let total = res.headers[headerNames.total];
11✔
161
      total = Number(total || res.data.length);
11!
162
      return Promise.resolve(dispatch({ type: RECEIVE_AUDIT_LOGS, events: res.data, total }));
11✔
163
    })
164
    .catch(err => commonErrorHandler(err, `There was an error retrieving audit logs:`, dispatch));
×
165
};
166

167
export const getAuditLogsCsvLink = () => (dispatch, getState) =>
184✔
168
  Promise.resolve(`${auditLogsApiUrl}/logs/export?limit=20000${prepareAuditlogQuery(getState().organization.auditlog.selectionState)}`);
2✔
169

170
export const setAuditlogsState = selectionState => (dispatch, getState) => {
184✔
171
  const currentState = getState().organization.auditlog.selectionState;
16✔
172
  let nextState = {
16✔
173
    ...currentState,
174
    ...selectionState,
175
    sort: { ...currentState.sort, ...selectionState.sort }
176
  };
177
  let tasks = [];
16✔
178
  // eslint-disable-next-line no-unused-vars
179
  const { isLoading: currentLoading, selectedIssue: currentIssue, ...currentRequestState } = currentState;
16✔
180
  // eslint-disable-next-line no-unused-vars
181
  const { isLoading: selectionLoading, selectedIssue: selectionIssue, ...selectionRequestState } = nextState;
16✔
182
  if (!deepCompare(currentRequestState, selectionRequestState)) {
16✔
183
    nextState.isLoading = true;
8✔
184
    tasks.push(dispatch(getAuditLogs(nextState)).finally(() => dispatch(setAuditlogsState({ isLoading: false }))));
8✔
185
  }
186
  tasks.push(dispatch({ type: SET_AUDITLOG_STATE, state: nextState }));
16✔
187
  return Promise.all(tasks);
16✔
188
};
189

190
/*
191
  Tenant management + Hosted Mender
192
*/
193
export const tenantDataDivergedMessage = 'The system detected there is a change in your plan or purchased add-ons. Please log out and log in again';
184✔
194
export const getUserOrganization = () => dispatch => {
184✔
195
  const token = getToken();
11✔
196
  return Api.get(`${tenantadmApiUrlv1}/user/tenant`).then(res => {
11✔
197
    let tasks = [dispatch({ type: SET_ORGANIZATION, organization: res.data })];
10✔
198
    const { addons, plan, trial } = res.data;
10✔
199
    const jwt = jwtDecode(token);
10✔
200
    const jwtData = { addons: jwt['mender.addons'], plan: jwt['mender.plan'], trial: jwt['mender.trial'] };
8✔
201
    if (!deepCompare({ addons, plan, trial }, jwtData)) {
8!
202
      const hash = hashString(tenantDataDivergedMessage);
8✔
203
      cookies.remove(`${jwt.sub}${hash}`);
8✔
204
      tasks.push(dispatch({ type: SET_ANNOUNCEMENT, announcement: tenantDataDivergedMessage }));
8✔
205
    }
206
    return Promise.all(tasks);
8✔
207
  });
208
};
209

210
export const sendSupportMessage = content => dispatch =>
184✔
211
  Api.post(`${tenantadmApiUrlv2}/contact/support`, content)
1✔
212
    .catch(err => commonErrorHandler(err, 'There was an error sending your request', dispatch, commonErrorFallback))
×
213
    .then(() => Promise.resolve(dispatch(setSnackbar('Your request was sent successfully', TIMEOUTS.fiveSeconds, ''))));
1✔
214

215
export const requestPlanChange = (tenantId, content) => dispatch =>
184✔
216
  Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/plan`, content)
1✔
217
    .catch(err => commonErrorHandler(err, 'There was an error sending your request', dispatch, commonErrorFallback))
×
218
    .then(() => Promise.resolve(dispatch(setSnackbar('Your request was sent successfully', TIMEOUTS.fiveSeconds, ''))));
1✔
219

220
export const downloadLicenseReport = () => dispatch =>
184✔
221
  Api.get(`${deviceAuthV2}/reports/devices`)
1✔
222
    .catch(err => commonErrorHandler(err, 'There was an error downloading the report', dispatch, commonErrorFallback))
×
223
    .then(res => res.data);
1✔
224

225
export const createIntegration = integration => dispatch => {
184✔
226
  // eslint-disable-next-line no-unused-vars
227
  const { credentials, id, provider, ...remainder } = integration;
1✔
228
  return Api.post(`${iotManagerBaseURL}/integrations`, { provider, credentials, ...remainder })
1✔
229
    .catch(err => commonErrorHandler(err, 'There was an error creating the integration', dispatch, commonErrorFallback))
×
230
    .then(() => Promise.all([dispatch(setSnackbar('The integration was set up successfully')), dispatch(getIntegrations())]));
1✔
231
};
232

233
export const changeIntegration = integration => dispatch =>
184✔
234
  Api.put(`${iotManagerBaseURL}/integrations/${integration.id}/credentials`, integration.credentials)
1✔
235
    .catch(err => commonErrorHandler(err, 'There was an error updating the integration', dispatch, commonErrorFallback))
×
236
    .then(() => Promise.all([dispatch(setSnackbar('The integration was updated successfully')), dispatch(getIntegrations())]));
1✔
237

238
export const deleteIntegration = integration => (dispatch, getState) =>
184✔
239
  Api.delete(`${iotManagerBaseURL}/integrations/${integration.id}`, {})
1✔
240
    .catch(err => commonErrorHandler(err, 'There was an error removing the integration', dispatch, commonErrorFallback))
×
241
    .then(() => {
242
      const integrations = getState().organization.externalDeviceIntegrations.filter(item => integration.provider !== item.provider);
1✔
243
      return Promise.all([
1✔
244
        dispatch(setSnackbar('The integration was removed successfully')),
245
        dispatch({ type: RECEIVE_EXTERNAL_DEVICE_INTEGRATIONS, value: integrations })
246
      ]);
247
    });
248

249
export const getIntegrations = () => (dispatch, getState) =>
184✔
250
  Api.get(`${iotManagerBaseURL}/integrations`)
12✔
251
    .catch(err => commonErrorHandler(err, 'There was an error retrieving the integration', dispatch, commonErrorFallback))
×
252
    .then(({ data }) => {
253
      const existingIntegrations = getState().organization.externalDeviceIntegrations;
9✔
254
      const integrations = data.reduce((accu, item) => {
9✔
255
        const existingIntegration = existingIntegrations.find(integration => item.id === integration.id) ?? {};
18✔
256
        const integration = { ...existingIntegration, ...item };
18✔
257
        accu.push(integration);
18✔
258
        return accu;
18✔
259
      }, []);
260
      return Promise.resolve(dispatch({ type: RECEIVE_EXTERNAL_DEVICE_INTEGRATIONS, value: integrations }));
9✔
261
    });
262

263
export const getWebhookEvents =
264
  (config = {}) =>
184✔
265
  (dispatch, getState) => {
3✔
266
    const { isFollowUp, page = defaultPage, perPage = defaultPerPage } = config;
3✔
267
    return Api.get(`${iotManagerBaseURL}/events?page=${page}&per_page=${perPage}`)
3✔
268
      .catch(err => commonErrorHandler(err, 'There was an error retrieving activity for this integration', dispatch, commonErrorFallback))
×
269
      .then(({ data }) => {
270
        let tasks = [
3✔
271
          dispatch({
272
            type: RECEIVE_WEBHOOK_EVENTS,
273
            value: isFollowUp ? getState().organization.webhooks.events : data,
3✔
274
            total: (page - 1) * perPage + data.length
275
          })
276
        ];
277
        if (data.length >= perPage && !isFollowUp) {
3✔
278
          tasks.push(dispatch(getWebhookEvents({ isFollowUp: true, page: page + 1, perPage: 1 })));
1✔
279
        }
280
        return Promise.all(tasks);
3✔
281
      });
282
  };
283

284
const samlConfigActions = {
184✔
285
  create: { success: 'stored', error: 'storing' },
286
  edit: { success: 'updated', error: 'updating' },
287
  read: { success: '', error: 'retrieving' },
288
  remove: { success: 'removed', error: 'removing' }
289
};
290

291
const samlConfigActionErrorHandler = (err, type) => dispatch =>
184✔
292
  commonErrorHandler(err, `There was an error ${samlConfigActions[type].error} the SAML configuration.`, dispatch, commonErrorFallback);
×
293

294
const samlConfigActionSuccessHandler = type => dispatch => dispatch(setSnackbar(`The SAML configuration was ${samlConfigActions[type].success} successfully`));
184✔
295

296
export const storeSamlConfig = config => dispatch =>
184✔
297
  Api.post(samlIdpApiUrlv1, config, { headers: { 'Content-Type': 'application/samlmetadata+xml', Accept: 'application/json' } })
1✔
298
    .catch(err => dispatch(samlConfigActionErrorHandler(err, 'create')))
×
299
    .then(() => Promise.all([dispatch(samlConfigActionSuccessHandler('create')), dispatch(getSamlConfigs())]));
1✔
300

301
export const changeSamlConfig =
302
  ({ id, config }) =>
184✔
303
  dispatch =>
1✔
304
    Api.put(`${samlIdpApiUrlv1}/${id}`, config, { headers: { 'Content-Type': 'application/samlmetadata+xml', Accept: 'application/json' } })
1✔
305
      .catch(err => dispatch(samlConfigActionErrorHandler(err, 'edit')))
×
306
      .then(() => Promise.all([dispatch(samlConfigActionSuccessHandler('edit')), dispatch(getSamlConfigs())]));
1✔
307

308
export const deleteSamlConfig =
309
  ({ id }) =>
184✔
310
  (dispatch, getState) =>
5✔
311
    Api.delete(`${samlIdpApiUrlv1}/${id}`)
5✔
312
      .catch(err => dispatch(samlConfigActionErrorHandler(err, 'remove')))
×
313
      .then(() => {
314
        const configs = getState().organization.samlConfigs.filter(item => id !== item.id);
6✔
315
        return Promise.all([dispatch(samlConfigActionSuccessHandler('remove')), dispatch({ type: RECEIVE_SAML_CONFIGS, value: configs })]);
5✔
316
      });
317

318
const getSamlConfigById = config => dispatch =>
184✔
319
  Api.get(`${samlIdpApiUrlv1}/${config.id}`)
12✔
320
    .catch(err => dispatch(samlConfigActionErrorHandler(err, 'read')))
×
321
    .then(({ data }) => Promise.resolve({ ...config, config: data }));
12✔
322

323
export const getSamlConfigs = () => dispatch =>
184✔
324
  Api.get(samlIdpApiUrlv1)
6✔
325
    .catch(err => commonErrorHandler(err, 'There was an error retrieving SAML configurations', dispatch, commonErrorFallback))
×
326
    .then(({ data }) =>
327
      Promise.all(data.map(config => Promise.resolve(dispatch(getSamlConfigById(config))))).then(configs => {
12✔
328
        return dispatch({ type: RECEIVE_SAML_CONFIGS, value: configs });
6✔
329
      })
330
    );
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