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

mendersoftware / mender-server / 1501783099

18 Oct 2024 07:49AM UTC coverage: 72.799%. First build
1501783099

push

gitlab-ci

web-flow
Merge pull request #101 from mineralsfree/MEN-7568

feat: tenant list added

4408 of 6393 branches covered (68.95%)

Branch coverage included in aggregate %.

88 of 182 new or added lines in 10 files covered. (48.35%)

42624 of 58212 relevant lines covered (73.22%)

28.08 hits per line

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

78.05
/frontend/src/js/store/organizationSlice/thunks.ts
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
// @ts-nocheck
15
import storeActions from '@northern.tech/store/actions';
16
import Api from '@northern.tech/store/api/general-api';
17
import {
18
  DEVICE_LIST_DEFAULTS,
19
  SORTING_OPTIONS,
20
  TENANT_LIST_DEFAULT,
21
  TIMEOUTS,
22
  deviceAuthV2,
23
  headerNames,
24
  iotManagerBaseURL,
25
  locations
26
} from '@northern.tech/store/constants';
27
import { getCurrentSession, getTenantCapabilities, getTenantsList } from '@northern.tech/store/selectors';
28
import { commonErrorFallback, commonErrorHandler } from '@northern.tech/store/store';
29
import { setFirstLoginAfterSignup } from '@northern.tech/store/thunks';
30
import { createAsyncThunk } from '@reduxjs/toolkit';
31
import { jwtDecode } from 'jwt-decode';
32
import hashString from 'md5';
33
import Cookies from 'universal-cookie';
34

35
import { actions, sliceName } from '.';
36
import { Tenant } from '../../components/tenants/types';
37
import { deepCompare } from '../../helpers';
38
import { SSO_TYPES, auditLogsApiUrl, ssoIdpApiUrlv1, tenantadmApiUrlv1, tenantadmApiUrlv2 } from './constants';
39
import { getAuditlogState, getOrganization } from './selectors';
40

41
const cookies = new Cookies();
101✔
42

43
const { setAnnouncement, setSnackbar } = storeActions;
101✔
44
const { page: defaultPage, perPage: defaultPerPage } = DEVICE_LIST_DEFAULTS;
101✔
45

46
export const cancelRequest = createAsyncThunk(`${sliceName}/cancelRequest`, (reason, { dispatch, getState }) => {
101✔
47
  const { id: tenantId } = getOrganization(getState());
1✔
48
  return Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/cancel`, { reason }).then(() =>
1✔
49
    Promise.resolve(dispatch(setSnackbar({ message: 'Deactivation request was sent successfully', autoHideDuration: TIMEOUTS.fiveSeconds })))
1✔
50
  );
51
});
52

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

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

92
export const startCardUpdate = createAsyncThunk(`${sliceName}/startCardUpdate`, (_, { dispatch }) =>
101✔
93
  Api.post(`${tenantadmApiUrlv2}/billing/card`)
1✔
94
    .then(({ data }) => {
95
      dispatch(actions.receiveSetupIntent(data.intent_id));
1✔
96
      return Promise.resolve(data.secret);
1✔
97
    })
98
    .catch(err => commonErrorHandler(err, `Updating the card failed:`, dispatch))
×
99
);
100

101
export const confirmCardUpdate = createAsyncThunk(`${sliceName}/confirmCardUpdate`, (_, { dispatch, getState }) =>
101✔
102
  Api.post(`${tenantadmApiUrlv2}/billing/card/${getState().organization.intentId}/confirm`)
1✔
103
    .then(() => Promise.all([dispatch(setSnackbar('Payment card was updated successfully')), dispatch(actions.receiveSetupIntent(null))]))
1✔
104
    .catch(err => commonErrorHandler(err, `Updating the card failed:`, dispatch))
×
105
);
106

107
export const getCurrentCard = createAsyncThunk(`${sliceName}/getCurrentCard`, (_, { dispatch }) =>
101✔
108
  Api.get(`${tenantadmApiUrlv2}/billing`).then(res => {
2✔
109
    const { last4, exp_month, exp_year, brand } = res.data.card || {};
2!
110
    return Promise.resolve(dispatch(actions.receiveCurrentCard({ brand, last4, expiration: { month: exp_month, year: exp_year } })));
2✔
111
  })
112
);
113

114
export const startUpgrade = createAsyncThunk(`${sliceName}/startUpgrade`, (tenantId, { dispatch }) =>
101✔
115
  Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/upgrade/start`)
1✔
116
    .then(({ data }) => Promise.resolve(data.secret))
1✔
117
    .catch(err => commonErrorHandler(err, `There was an error upgrading your account:`, dispatch))
×
118
);
119

120
export const cancelUpgrade = createAsyncThunk(`${sliceName}/cancelUpgrade`, tenantId => Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/upgrade/cancel`));
101✔
121

122
export const completeUpgrade = createAsyncThunk(`${sliceName}/completeUpgrade`, ({ tenantId, plan }, { dispatch }) =>
101✔
123
  Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/upgrade/complete`, { plan })
1✔
124
    .catch(err => commonErrorHandler(err, `There was an error upgrading your account:`, dispatch))
×
125
    .then(() => Promise.resolve(dispatch(getUserOrganization())))
1✔
126
);
127

128
const prepareAuditlogQuery = ({ startDate, endDate, user: userFilter, type, detail: detailFilter, sort = {} }) => {
101✔
129
  const userId = userFilter?.id || userFilter;
8✔
130
  const detail = detailFilter?.id || detailFilter;
8✔
131
  const createdAfter = startDate ? `&created_after=${Math.round(Date.parse(startDate) / 1000)}` : '';
8✔
132
  const createdBefore = endDate ? `&created_before=${Math.round(Date.parse(endDate) / 1000)}` : '';
8✔
133
  const typeSearch = type ? `&object_type=${type.value}`.toLowerCase() : '';
8!
134
  const userSearch = userId ? `&actor_id=${userId}` : '';
8!
135
  const objectSearch = type && detail ? `&${type.queryParameter}=${encodeURIComponent(detail)}` : '';
8!
136
  const { direction = SORTING_OPTIONS.desc } = sort;
8✔
137
  return `${createdAfter}${createdBefore}${userSearch}${typeSearch}${objectSearch}&sort=${direction}`;
8✔
138
};
139

140
export const getAuditLogs = createAsyncThunk(`${sliceName}/getAuditLogs`, (selectionState, { dispatch, getState }) => {
101✔
141
  const { page, perPage } = selectionState;
7✔
142
  const { hasAuditlogs } = getTenantCapabilities(getState());
7✔
143
  if (!hasAuditlogs) {
7✔
144
    return Promise.resolve();
1✔
145
  }
146
  return Api.get(`${auditLogsApiUrl}/logs?page=${page}&per_page=${perPage}${prepareAuditlogQuery(selectionState)}`)
6✔
147
    .then(({ data, headers }) => {
148
      let total = headers[headerNames.total];
6✔
149
      total = Number(total || data.length);
6!
150
      return Promise.resolve(dispatch(actions.receiveAuditLogs({ events: data, total })));
6✔
151
    })
152
    .catch(err => commonErrorHandler(err, `There was an error retrieving audit logs:`, dispatch));
×
153
});
154

155
export const getAuditLogsCsvLink = createAsyncThunk(`${sliceName}/getAuditLogsCsvLink`, (_, { getState }) =>
101✔
156
  Promise.resolve(`${window.location.origin}${auditLogsApiUrl}/logs/export?limit=20000${prepareAuditlogQuery(getAuditlogState(getState()))}`)
2✔
157
);
158

159
export const setAuditlogsState = createAsyncThunk(`${sliceName}/setAuditlogsState`, (selectionState, { dispatch, getState }) => {
101✔
160
  const currentState = getAuditlogState(getState());
4✔
161
  let nextState = {
4✔
162
    ...currentState,
163
    ...selectionState,
164
    sort: { ...currentState.sort, ...selectionState.sort }
165
  };
166
  let tasks = [];
4✔
167
  // eslint-disable-next-line no-unused-vars
168
  const { isLoading: currentLoading, selectedIssue: currentIssue, ...currentRequestState } = currentState;
4✔
169
  // eslint-disable-next-line no-unused-vars
170
  const { isLoading: selectionLoading, selectedIssue: selectionIssue, ...selectionRequestState } = nextState;
4✔
171
  if (!deepCompare(currentRequestState, selectionRequestState)) {
4!
172
    nextState.isLoading = true;
4✔
173
    tasks.push(dispatch(getAuditLogs(nextState)).finally(() => dispatch(actions.setAuditLogState({ isLoading: false }))));
4✔
174
  }
175
  tasks.push(dispatch(actions.setAuditLogState(nextState)));
4✔
176
  return Promise.all(tasks);
4✔
177
});
178

179
/*
180
  Tenant management + Hosted Mender
181
*/
182
export const tenantDataDivergedMessage = 'The system detected there is a change in your plan or purchased add-ons. Please log out and log in again';
101✔
183

184
const tenantListRetrieval = async (config): Promise<[Tenant[], number]> => {
101✔
NEW
185
  const { page, perPage } = config;
×
NEW
186
  const params = new URLSearchParams({ page, per_page: perPage }).toString();
×
NEW
187
  const tenantList = await Api.get(`${tenantadmApiUrlv2}/tenants?${params}`);
×
NEW
188
  const totalCount = tenantList.headers[headerNames.total] || TENANT_LIST_DEFAULT.perPage;
×
NEW
189
  return [tenantList.data, totalCount];
×
190
};
191
export const getTenants = createAsyncThunk(`${sliceName}/getTenants`, async (_, { dispatch, getState }) => {
101✔
NEW
192
  const currentState = getTenantsList(getState());
×
NEW
193
  const [tenants, pageCount] = await tenantListRetrieval(currentState);
×
NEW
194
  dispatch(actions.setTenantListState({ ...currentState, total: pageCount, tenants }));
×
195
});
196

197
export const setTenantsListState = createAsyncThunk(`${sliceName}/setTenantsListState`, async (selectionState: any, { dispatch, getState }) => {
101✔
NEW
198
  const currentState = getTenantsList(getState());
×
NEW
199
  const nextState = {
×
200
    ...currentState,
201
    ...selectionState
202
  };
NEW
203
  if (!deepCompare(currentState, selectionState)) {
×
NEW
204
    const [tenants, pageCount] = await tenantListRetrieval(nextState);
×
NEW
205
    return dispatch(actions.setTenantListState({ ...nextState, tenants, total: pageCount }));
×
206
  }
NEW
207
  return dispatch(actions.setTenantListState({ ...nextState }));
×
208
});
209

210
export const getUserOrganization = createAsyncThunk(`${sliceName}/getUserOrganization`, (_, { dispatch, getState }) => {
101✔
211
  return Api.get(`${tenantadmApiUrlv1}/user/tenant`).then(res => {
9✔
212
    let tasks = [dispatch(actions.setOrganization(res.data))];
8✔
213
    const { addons, plan, trial } = res.data;
8✔
214
    const { token } = getCurrentSession(getState());
8✔
215
    const jwt = jwtDecode(token);
8✔
216
    const jwtData = { addons: jwt['mender.addons'], plan: jwt['mender.plan'], trial: jwt['mender.trial'] };
8✔
217
    if (!deepCompare({ addons, plan, trial }, jwtData)) {
8!
218
      const hash = hashString(tenantDataDivergedMessage);
8✔
219
      cookies.remove(`${jwt.sub}${hash}`);
8✔
220
      tasks.push(dispatch(setAnnouncement(tenantDataDivergedMessage)));
8✔
221
    }
222
    return Promise.all(tasks);
8✔
223
  });
224
});
225

226
export const sendSupportMessage = createAsyncThunk(`${sliceName}/sendSupportMessage`, (content, { dispatch }) =>
101✔
227
  Api.post(`${tenantadmApiUrlv2}/contact/support`, content)
1✔
228
    .catch(err => commonErrorHandler(err, 'There was an error sending your request', dispatch, commonErrorFallback))
×
229
    .then(() => Promise.resolve(dispatch(setSnackbar({ message: 'Your request was sent successfully', autoHideDuration: TIMEOUTS.fiveSeconds }))))
1✔
230
);
231

232
export const requestPlanChange = createAsyncThunk(`${sliceName}/requestPlanChange`, ({ content, tenantId }, { dispatch }) =>
101✔
233
  Api.post(`${tenantadmApiUrlv2}/tenants/${tenantId}/plan`, content)
1✔
234
    .catch(err => commonErrorHandler(err, 'There was an error sending your request', dispatch, commonErrorFallback))
×
235
    .then(() => Promise.resolve(dispatch(setSnackbar({ message: 'Your request was sent successfully', autoHideDuration: TIMEOUTS.fiveSeconds }))))
1✔
236
);
237

238
export const downloadLicenseReport = createAsyncThunk(`${sliceName}/downloadLicenseReport`, (_, { dispatch }) =>
101✔
239
  Api.get(`${deviceAuthV2}/reports/devices`)
1✔
240
    .catch(err => commonErrorHandler(err, 'There was an error downloading the report', dispatch, commonErrorFallback))
×
241
    .then(res => res.data)
1✔
242
);
243

244
// eslint-disable-next-line no-unused-vars
245
export const createIntegration = createAsyncThunk(`${sliceName}/createIntegration`, ({ id, ...integration }, { dispatch }) =>
101✔
246
  Api.post(`${iotManagerBaseURL}/integrations`, integration)
1✔
247
    .catch(err => commonErrorHandler(err, 'There was an error creating the integration', dispatch, commonErrorFallback))
×
248
    .then(() => Promise.all([dispatch(setSnackbar('The integration was set up successfully')), dispatch(getIntegrations())]))
1✔
249
);
250

251
export const changeIntegration = createAsyncThunk(`${sliceName}/changeIntegration`, ({ id, credentials }, { dispatch }) =>
101✔
252
  Api.put(`${iotManagerBaseURL}/integrations/${id}/credentials`, credentials)
1✔
253
    .catch(err => commonErrorHandler(err, 'There was an error updating the integration', dispatch, commonErrorFallback))
×
254
    .then(() => Promise.all([dispatch(setSnackbar('The integration was updated successfully')), dispatch(getIntegrations())]))
1✔
255
);
256

257
export const deleteIntegration = createAsyncThunk(`${sliceName}/deleteIntegration`, ({ id, provider }, { dispatch, getState }) =>
101✔
258
  Api.delete(`${iotManagerBaseURL}/integrations/${id}`, {})
1✔
259
    .catch(err => commonErrorHandler(err, 'There was an error removing the integration', dispatch, commonErrorFallback))
×
260
    .then(() => {
261
      const integrations = getState().organization.externalDeviceIntegrations.filter(item => provider !== item.provider);
1✔
262
      return Promise.all([
1✔
263
        dispatch(setSnackbar('The integration was removed successfully')),
264
        dispatch(actions.receiveExternalDeviceIntegrations(integrations))
265
      ]);
266
    })
267
);
268

269
export const getIntegrations = createAsyncThunk(`${sliceName}/getIntegrations`, (_, { dispatch, getState }) =>
101✔
270
  Api.get(`${iotManagerBaseURL}/integrations`)
15✔
271
    .catch(err => commonErrorHandler(err, 'There was an error retrieving the integration', dispatch, commonErrorFallback))
×
272
    .then(({ data }) => {
273
      const existingIntegrations = getState().organization.externalDeviceIntegrations;
15✔
274
      const integrations = data.reduce((accu, item) => {
15✔
275
        const existingIntegration = existingIntegrations.find(integration => item.id === integration.id) ?? {};
30✔
276
        const integration = { ...existingIntegration, ...item };
30✔
277
        accu.push(integration);
30✔
278
        return accu;
30✔
279
      }, []);
280
      return Promise.resolve(dispatch(actions.receiveExternalDeviceIntegrations(integrations)));
15✔
281
    })
282
);
283

284
export const getWebhookEvents = createAsyncThunk(`${sliceName}/getWebhookEvents`, (config = {}, { dispatch, getState }) => {
101✔
285
  const { isFollowUp, page = defaultPage, perPage = defaultPerPage } = config;
3✔
286
  return Api.get(`${iotManagerBaseURL}/events?page=${page}&per_page=${perPage}`)
3✔
287
    .catch(err => commonErrorHandler(err, 'There was an error retrieving activity for this integration', dispatch, commonErrorFallback))
×
288
    .then(({ data }) => {
289
      let tasks = [
3✔
290
        dispatch(
291
          actions.receiveWebhookEvents({
292
            value: isFollowUp ? getState().organization.webhooks.events : data,
3✔
293
            total: (page - 1) * perPage + data.length
294
          })
295
        )
296
      ];
297
      if (data.length >= perPage && !isFollowUp) {
3✔
298
        tasks.push(dispatch(getWebhookEvents({ isFollowUp: true, page: page + 1, perPage: 1 })));
1✔
299
      }
300
      return Promise.all(tasks);
3✔
301
    });
302
});
303

304
const ssoConfigActions = {
101✔
305
  create: { success: 'stored', error: 'storing' },
306
  edit: { success: 'updated', error: 'updating' },
307
  read: { success: '', error: 'retrieving' },
308
  remove: { success: 'removed', error: 'removing' },
309
  readMultiple: { success: '', error: 'retrieving' }
310
};
311

312
const ssoConfigActionErrorHandler = (err, type) => dispatch =>
101✔
313
  commonErrorHandler(err, `There was an error ${ssoConfigActions[type].error} the SSO configuration.`, dispatch, commonErrorFallback);
×
314

315
const ssoConfigActionSuccessHandler = type => dispatch => dispatch(setSnackbar(`The SSO configuration was ${ssoConfigActions[type].success} successfully`));
101✔
316

317
export const storeSsoConfig = createAsyncThunk(`${sliceName}/storeSsoConfig`, ({ config, contentType }, { dispatch }) =>
101✔
318
  Api.post(ssoIdpApiUrlv1, config, { headers: { 'Content-Type': contentType, Accept: 'application/json' } })
1✔
319
    .catch(err => dispatch(ssoConfigActionErrorHandler(err, 'create')))
×
320
    .then(() => Promise.all([dispatch(ssoConfigActionSuccessHandler('create')), dispatch(getSsoConfigs())]))
1✔
321
);
322

323
export const changeSsoConfig = createAsyncThunk(`${sliceName}/changeSsoConfig`, ({ config, contentType }, { dispatch }) =>
101✔
324
  Api.put(`${ssoIdpApiUrlv1}/${config.id}`, config, { headers: { 'Content-Type': contentType, Accept: 'application/json' } })
1✔
325
    .catch(err => dispatch(ssoConfigActionErrorHandler(err, 'edit')))
×
326
    .then(() => Promise.all([dispatch(ssoConfigActionSuccessHandler('edit')), dispatch(getSsoConfigs())]))
1✔
327
);
328

329
export const deleteSsoConfig = createAsyncThunk(`${sliceName}/deleteSsoConfig`, ({ id }, { dispatch, getState }) =>
101✔
330
  Api.delete(`${ssoIdpApiUrlv1}/${id}`)
1✔
331
    .catch(err => dispatch(ssoConfigActionErrorHandler(err, 'remove')))
×
332
    .then(() => {
333
      const configs = getState().organization.ssoConfigs.filter(item => id !== item.id);
2✔
334
      return Promise.all([dispatch(ssoConfigActionSuccessHandler('remove')), dispatch(actions.receiveSsoConfigs(configs))]);
1✔
335
    })
336
);
337

338
export const getSsoConfigById = createAsyncThunk(`${sliceName}/getSsoConfigById`, (config, { dispatch }) =>
101✔
339
  Api.get(`${ssoIdpApiUrlv1}/${config.id}`)
10✔
340
    .catch(err => dispatch(ssoConfigActionErrorHandler(err, 'read')))
×
341
    .then(({ data, headers }) => {
342
      const sso = Object.values(SSO_TYPES).find(({ contentType }) => contentType === headers['content-type']);
20✔
343
      return sso ? Promise.resolve({ ...config, config: data, type: sso.id }) : Promise.reject('Unsupported SSO config content type.');
10!
344
    })
345
);
346

347
export const getSsoConfigs = createAsyncThunk(`${sliceName}/getSsoConfigs`, (_, { dispatch }) =>
101✔
348
  Api.get(ssoIdpApiUrlv1)
5✔
349
    .catch(err => dispatch(ssoConfigActionErrorHandler(err, 'readMultiple')))
×
350
    .then(({ data }) =>
351
      Promise.all(data.map(config => dispatch(getSsoConfigById(config)).unwrap()))
10✔
352
        .then(configs => dispatch(actions.receiveSsoConfigs(configs)))
5✔
353
        .catch(err => commonErrorHandler(err, err, dispatch, ''))
×
354
    )
355
);
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