-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathactions.js
538 lines (503 loc) · 14.4 KB
/
actions.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
import 'isomorphic-fetch';
import {
apiPath,
userAPIPath,
headers,
hostname,
hostnameWithSubdomain,
basename,
submissionApiPath,
graphqlPath,
guppyGraphQLUrl,
graphqlSchemaUrl,
authzPath,
authzMappingPath,
wtsAggregateAuthzPath,
} from './configs';
import { config } from './params';
import { showSystemUse, showSystemUseOnlyOnLogin } from './localconf';
import sessionMonitor from './SessionMonitor';
import isEnabled from './helpers/featureFlags';
export const updatePopup = (state) => ({
type: 'UPDATE_POPUP',
data: state,
});
export const connectionError = () => {
// eslint-disable-next-line no-console
console.error('connection error');
return {
type: 'REQUEST_ERROR',
error: 'connection_error',
};
};
const fetchCache = {};
const getJsonOrText = (path, response, useCache, method = 'GET') => response.text()
.then(
(textData) => {
let data = textData;
if (data) {
try {
data = JSON.parse(data);
if (useCache && method === 'GET' && response.status === 200) {
fetchCache[path] = textData;
}
} catch (e) {
// # do nothing
}
}
return {
response, data, status: response.status, headers: response.headers,
};
});
let pendingRequest = null;
export const fetchCreds = (opts) => {
if (pendingRequest) {
return pendingRequest;
}
const { path = `${userAPIPath}user/`, method = 'GET', dispatch } = opts;
const request = {
credentials: 'include',
headers: { ...headers },
method,
};
pendingRequest = fetch(path, request)
.then(
(response) => {
pendingRequest = null;
return Promise.resolve(getJsonOrText(path, response, false));
},
(error) => {
pendingRequest = null;
if (dispatch) {
dispatch(connectionError());
}
return Promise.reject(error);
},
);
return pendingRequest;
};
/**
* Little helper issues fetch, then resolves response
* as text, and tries to JSON.parse the text before resolving, but
* ignores JSON.parse failure and response.status, and returns {response, data} either way.
* If dispatch is supplied, then dispatch(connectionError()) on fetch reject.
* If useCache is supplied and method is GET,
* then text for 200 JSON responses are cached, and re-used, and
* the result promise only includes {data, status} - where JSON data is re-parsed
* every time to avoid mutation by the client
*
* @method fetchWithCreds
* @param {path,method=GET,body=null,customHeaders?, dispatch?, useCache?} opts
* @return Promise<{response,data,status,headers}> or Promise<{data,status}> if useCache specified
*/
export const fetchWithCreds = (opts) => {
const {
path, method = 'GET', body = null, customHeaders, dispatch, useCache,
} = opts;
if (useCache && (method === 'GET') && fetchCache[path]) {
return Promise.resolve({ status: 200, data: JSON.parse(fetchCache[path]) });
}
const request = {
credentials: 'include',
headers: { ...headers, ...customHeaders },
method,
body,
};
return fetch(path, request)
.then(
(response) => {
if (response.status !== 403 && response.status !== 401) {
return Promise.resolve(getJsonOrText(path, response, useCache, method));
}
return Promise.resolve(fetchCreds({ dispatch })
.then(
(resp) => {
switch (resp.status) {
case 200:
return Promise.resolve(fetch(path, request)
.then(
(res) => getJsonOrText(path, res, useCache, method),
));
default:
return {
response: resp,
data: { data: {} },
status: resp.status,
headers: resp.headers,
};
}
},
));
},
(error) => {
if (dispatch) {
dispatch(connectionError());
}
return Promise.reject(error);
},
);
};
export const fetchWithCredsAndTimeout = (opts, timeoutInMS) => {
let didTimeOut = false;
return new Promise(((resolve, reject) => {
const timeout = setTimeout(() => {
didTimeOut = true;
reject(new Error('Request timed out'));
}, timeoutInMS);
fetchWithCreds(opts)
.then((response) => {
// Clear the timeout as cleanup
clearTimeout(timeout);
if (!didTimeOut) {
resolve(response);
}
})
.catch((err) => {
// Rejection already happened with setTimeout
if (didTimeOut) return;
// Reject with error
reject(err);
});
}));
};
/**
* Redux 'thunk' wrapper around fetchWithCreds
* invokes dispatch(handler( { status, data, headers} ) and callback()
* and propagates {response,data, status, headers} on resolved fetch,
* otherwise dipatch(connectionError()) on fetch rejection.
* May prefer this over straight call to fetchWithCreds in Redux context due to
* conectionError() dispatch on fetch rejection.
*
* @param { path, method=GET, body=null, customerHeaders, handler, callback } opts
* @return Promise
*/
export const fetchWrapper = ({
path, method = 'GET', body = null, customHeaders, handler, callback = () => (null),
}) => (dispatch) => fetchWithCreds({
path, method, body, customHeaders, dispatch,
},
)
.then(
({ response, data }) => {
const result = {
response, data, status: response.status, headers: response.headers,
};
const dispatchPromise = handler ? Promise.resolve(dispatch(handler(result))) : Promise.resolve('ok');
return dispatchPromise.then(
() => {
callback();
return result;
},
);
},
);
// We first update the session so that the user will be notified
// if their auth is insufficient to perform the query.
export const fetchGraphQL = (graphQLParams) => sessionMonitor.updateSession()
.then(() => fetchWithCreds({ path: graphqlPath, body: JSON.stringify(graphQLParams), method: 'POST' })
.then((response) => {
if (response.status === 200 && response.data) {
return response.data;
}
return response;
}));
export const fetchFlatGraphQL = (graphQLParams) => sessionMonitor.updateSession()
.then(() => fetchWithCreds({ path: guppyGraphQLUrl, body: JSON.stringify(graphQLParams), method: 'POST' })
.then((response) => {
if (response.status === 200 && response.data) {
return response.data;
}
return response;
}));
export const handleResponse = (type) => ({ data, status }) => {
switch (status) {
case 200:
return {
type,
data,
};
default:
return {
type: 'FETCH_ERROR',
error: data,
};
}
};
const handleFetchUser = ({ status, data }) => {
switch (status) {
case 200:
return {
type: 'RECEIVE_USER',
user: data,
};
default:
return {
type: 'FETCH_ERROR',
error: data.error,
};
}
};
export const fetchUser = (dispatch) => fetchCreds({
dispatch,
})
.then(
(status, data) => handleFetchUser(status, data),
)
.then((msg) => dispatch(msg));
export const refreshUser = () => fetchUser;
export const logoutAPI = (displayAuthPopup = false) => (dispatch) => {
const cleanBasename = basename.replace(/^\/+/g, '').replace(/(dev.html$)/, '');
fetch(`${userAPIPath}logout?next=${hostname}${cleanBasename}`)
.then((response) => {
if (displayAuthPopup) {
dispatch({
type: 'UPDATE_POPUP',
data: {
authPopup: true,
},
});
} else if (document.location.pathname.includes('/dev.html')) {
document.location.replace(`${response.url}dev.html`);
} else {
document.location.replace(response.url);
}
});
};
/**
* Determine if we need to display the system Use Message
* For all protected content, so sites require display of
* a use message. This is enabled by defining a object in
* gitops.json:
"systemUse" : {
"systemUseText" : "Text Message",
"expireUseMsgDays" : 10,
}
* displayUseMsg: define if you want message to be displayed: values are:
* *) "cookie": set a cookie upon acceptance default of 10 day but can be set using
* expireUseMsgDays
* *) expireUseMsgDays: number of days until displaying message again, set to 0 to make it
* a browser session
*/
export const checkIfDisplaySystemUseNotice = (authenticated) => (dispatch) => {
// couple of option for when to display the system use warning
// displayUseMsg:
// "cookie": use the cookie and expireValue (defaults to 0 to show use message per session
// undefined or systemUseText is undefined: always false
//
if (!showSystemUse) {
dispatch({
type: 'UPDATE_POPUP',
data: {
systemUseWarnPopup: false,
},
});
return;
}
// look for cookie, if exists then do not show systemUse
if (document.cookie.indexOf('systemUseWarning=') >= 0) {
dispatch({
type: 'UPDATE_POPUP',
data: {
systemUseWarnPopup: false,
},
});
return;
}
// test to see if systemUse dialog should be shown
if (showSystemUseOnlyOnLogin) { // if set to show only on login
if (authenticated) { // and logged in, show systemUse
dispatch({
type: 'UPDATE_POPUP',
data: {
systemUseWarnPopup: true,
},
});
}
return;
}
// last case, show system use
dispatch({
type: 'UPDATE_POPUP',
data: {
systemUseWarnPopup: true,
},
});
// don't change anything
};
export const updateSystemUseNotice = (displayUseWarning) => (dispatch) => {
dispatch({
type: 'UPDATE_POPUP',
data: {
systemUseWarnPopup: displayUseWarning,
},
});
};
export const displaySystemUseNotice = (authenticated) => (dispatch) => dispatch(
checkIfDisplaySystemUseNotice(authenticated),
);
/*
* redux-thunk support asynchronous redux actions via 'thunks' -
* lambdas that accept dispatch and getState functions as arguments
*/
export const fetchProjects = () => (dispatch) => fetchWithCreds({
path: `${submissionApiPath}graphql`,
body: JSON.stringify({
query: 'query { project(first:0) {code, project_id, availability_type}}',
}),
method: 'POST',
})
.then(
({ status, data }) => {
switch (status) {
case 200:
return {
type: 'RECEIVE_PROJECTS',
data: data.data.project,
status,
};
default:
return {
type: 'FETCH_ERROR',
error: data,
status,
};
}
})
.then((msg) => dispatch(msg));
/**
* Fetch the schema for graphi, and stuff it into redux -
* handled by router
*/
export const fetchSchema = (dispatch) => fetchWithCreds({ path: graphqlSchemaUrl, dispatch })
.then(
({ status, data }) => {
switch (status) {
case 200:
return dispatch(
{
type: 'RECEIVE_SCHEMA_LOGIN',
schema: data,
},
);
default:
return Promise.resolve('NOOP');
}
},
);
export const fetchDictionary = (dispatch) => fetchWithCreds({
path: `${submissionApiPath}_dictionary/_all`,
method: 'GET',
useCache: true,
})
.then(
({ status, data }) => {
switch (status) {
case 200:
return {
type: 'RECEIVE_DICTIONARY',
data,
};
default:
return {
type: 'FETCH_ERROR',
error: data,
};
}
})
.then((msg) => dispatch(msg));
export const fetchVersionInfo = (dispatch) => fetchWithCreds({
path: `${apiPath}_version`,
method: 'GET',
useCache: true,
})
.then(
({ status, data }) => {
switch (status) {
case 200:
return {
type: 'RECEIVE_VERSION_INFO',
data,
};
default:
return {
type: 'FETCH_ERROR',
error: data,
};
}
},
)
.then((msg) => dispatch(msg));
// asks arborist which restricted access components the user has access to
export const fetchUserAccess = async (dispatch) => {
// restricted access components and their associated arborist resources:
const mapping = config.componentToResourceMapping || {};
const userAccess = await Object.keys(mapping)
.reduce(async (res, name) => {
const dict = await res;
const e = mapping[name];
// makes a call to arborist's auth/proxy endpoint
// returns true if the user has access to the resource, false otherwise
dict[name] = await fetch(
`${authzPath}?resource=${e.resource}&method=${e.method}&service=${e.service}`,
)
.then((fetchRes) => {
switch (fetchRes.status) {
case 401: // user is not logged in
case 403: // user is not allowed to access the resource
return false;
case 200: // user is authorized
return true;
default:
console.error(`Unknown status "${fetchRes.status}" returned by arborist call`);
return false;
}
});
return dict;
}, {});
dispatch({
type: 'RECEIVE_USER_ACCESS',
data: userAccess,
});
};
const fetchAuthMapping = (authzMappingURL) => fetch(
authzMappingURL,
).then((fetchRes) => {
switch (fetchRes.status) {
case 200:
return fetchRes.json();
default:
// This is dispatched on app init and on user login.
// Could be not logged in -> no username -> 404; this is ok
// There may be plans to update Arborist to return anonymous access when username not found
return {};
}
});
// asks arborist for the user's auth mapping if Arborist UI enabled
export const fetchUserAuthMapping = async (dispatch) => {
if (!config.showArboristAuthzOnProfile && !config.useArboristUI) {
return;
}
let fetchedAuthMapping;
let authMapping;
let aggregateAuthMappings = {};
if (isEnabled('discoveryUseAggWTS')) {
// Arborist will get the username from the jwt
fetchedAuthMapping = await fetchAuthMapping(wtsAggregateAuthzPath);
}
if (fetchedAuthMapping && Object.keys(fetchedAuthMapping).length) {
authMapping = fetchedAuthMapping[hostnameWithSubdomain];
aggregateAuthMappings = fetchedAuthMapping;
} else {
fetchedAuthMapping = await fetchAuthMapping(authzMappingPath);
authMapping = fetchedAuthMapping;
aggregateAuthMappings[hostnameWithSubdomain] = fetchedAuthMapping;
}
dispatch({
type: 'RECEIVE_USER_AUTH_MAPPING',
data: authMapping,
});
dispatch({
type: 'RECEIVE_AGGREGATE_USER_AUTH_MAPPINGS',
data: aggregateAuthMappings,
});
};