@crmcom/self-service-sdk 2.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/httpUtil.js ADDED
@@ -0,0 +1,863 @@
1
+ /**
2
+ * class to handle HTTP Requests and Token refresh
3
+ */
4
+
5
+ //import querystring from 'querystring';
6
+ import { initOptionHeader, ACCESS_TOKEN, REFRESH_TOKEN, getData } from '../../utils/common';
7
+ import { jwtDecode } from 'jwt-decode';
8
+ import { connection } from '../../portal.config';
9
+ import { logger } from './logger';
10
+
11
+ // import { showMessageError } from '../../utils/util';
12
+ export const httpUtil = {
13
+ setupChannel,
14
+ put,
15
+ post,
16
+ get,
17
+ sendDelete,
18
+ uploadFile,
19
+ is200OK,
20
+ startSession,
21
+ getSession,
22
+ cleanObj,
23
+ cleanSession,
24
+ switchSession,
25
+ refreshToken,
26
+ getURI,
27
+ storeOrganisation,
28
+ getOrganisation,
29
+ uploadFileNew,
30
+ getToken,
31
+ setupApiKey,
32
+ startSessionUnregister,
33
+ };
34
+
35
+
36
+ /** local variables */
37
+
38
+ let _storeKVFn;
39
+ let _getKVFn;
40
+ let _sessionInvalidCallback;
41
+ let _fetchFn;
42
+
43
+ let _apiKey;
44
+ let _accessToken;
45
+ let _refreshToken;
46
+ let _host;
47
+ let _sessionData;
48
+
49
+ let _selfServicePath = '/self-service'
50
+ let _backofficePath = '/backoffice'
51
+ let _ssl_pinning_options;
52
+ let _enable_ssl_pinning;
53
+ let _isBackend;
54
+ let _middleware_host;
55
+ let _middleware_apiKey;
56
+ let _mwNodejs_host;
57
+ let _mwNodejs_apiKey;
58
+ /**
59
+ *
60
+ * TODO: do we need a call back for no internet connection ?
61
+ * when no connection refresh token will not be available -> should not kick user out.
62
+ */
63
+
64
+ async function setupChannel({
65
+ storeKVFn, //function to store key value
66
+ getKVFn, //function to get value by key from the storage
67
+ sessionInvalidCallback, //function to call when api_key or token key is invalid and refresh token if available was failed
68
+ apiKey,
69
+ host,
70
+ fetchFn,
71
+ sslPinningOptions,
72
+ enableSslPinning,
73
+ isBackend,
74
+ middlewareHost,
75
+ middlewareApiKey,
76
+ mwNodejsHost,
77
+ mwNodejsApiKey,
78
+ }) {
79
+ _storeKVFn = storeKVFn;
80
+ _getKVFn = getKVFn;
81
+ _sessionInvalidCallback = sessionInvalidCallback;
82
+ _apiKey = apiKey;
83
+ _host = host;
84
+ _enable_ssl_pinning = enableSslPinning;
85
+ _ssl_pinning_options = sslPinningOptions;
86
+ _middleware_host = middlewareHost
87
+ _middleware_apiKey = middlewareApiKey
88
+ _mwNodejs_host = mwNodejsHost
89
+ _mwNodejs_apiKey = mwNodejsApiKey
90
+ if (fetchFn)
91
+ _fetchFn = fetchFn;
92
+ else
93
+ _fetchFn = fetch;
94
+ if (isBackend) {
95
+ _isBackend = isBackend;
96
+ }
97
+ if (_getKVFn) {
98
+ _accessToken = await _getKVFn(ACCESS_TOKEN ? ACCESS_TOKEN : 'access_token');
99
+ _refreshToken = await _getKVFn(REFRESH_TOKEN ? REFRESH_TOKEN : 'refresh_token');
100
+ try {
101
+ if (_accessToken) {
102
+ _sessionData = jwtDecode(_accessToken);
103
+ await checkRefreshToken();
104
+ }
105
+ else if (_refreshToken) {
106
+ await refreshToken(true);
107
+ }
108
+ } catch (e) {
109
+ logger.warn('Failed to load session data:', e);
110
+ _sessionData = undefined;
111
+ }
112
+ }
113
+ //TODO add silent refresh token here
114
+ }
115
+
116
+ async function setupApiKey(apikey){
117
+ _apiKey = apikey
118
+ }
119
+
120
+ async function checkRefreshToken() {
121
+ let currentTime = Date.now();
122
+ let tokenLiveInSec = (_sessionData.exp - currentTime / 1000);
123
+ //console.log('tokenLiveInSec====', tokenLiveInSec)
124
+ if (tokenLiveInSec > 60 * 60)
125
+ return;
126
+ else
127
+ await refreshToken(true);
128
+ }
129
+
130
+ async function refreshToken(logOutIfSessionInvalid) {
131
+ try {
132
+ logger.debug('Attempting token refresh');
133
+ logger.debug('Starting token refresh');
134
+ let path = '/v2/contacts/refresh';
135
+ if (_isBackend) {
136
+ path = '/v2/users/refresh'
137
+ }
138
+ let response = await postRefreshToken({
139
+ resourcePath: path,
140
+ body: {},
141
+ isBackend: _isBackend
142
+ });
143
+ logger.debug('Token refresh response received');
144
+ if (response.status == "200") {
145
+ let bodyText = await response.text()
146
+ logger.debug('Token refreshed successfully');
147
+ startSession(json2Obj(bodyText));
148
+ return { code: "OK", data: bodyText ? json2Obj(bodyText) : null };
149
+ } else {
150
+ validateForceLogout(response, true);
151
+ return response;
152
+ }
153
+ } catch (e) {
154
+ validateForceLogout(e, true);
155
+ return e;
156
+ }
157
+ }
158
+
159
+ function startSession({ access_token, refresh_token, exp, communities }) {
160
+ //TODO handle expiration
161
+ _accessToken = access_token;
162
+ _refreshToken = refresh_token;
163
+ if (_storeKVFn) {
164
+ _storeKVFn(REFRESH_TOKEN ? REFRESH_TOKEN : "refresh_token", refresh_token)
165
+ _storeKVFn(ACCESS_TOKEN ? ACCESS_TOKEN : "access_token", access_token)
166
+ let _communities = communities ? communities : [];
167
+ _storeKVFn("communities", JSON.stringify(_communities))
168
+ // _storeKVFn("exp", exp)
169
+ //parse and store session data
170
+ _sessionData = jwtDecode(_accessToken);
171
+ // console.log('Session data:', _sessionData);
172
+ }
173
+
174
+ }
175
+
176
+ function startSessionUnregister({ access_token, refresh_token }) {
177
+ _accessToken = access_token;
178
+ _refreshToken = refresh_token;
179
+ _sessionData = jwtDecode(_accessToken);
180
+
181
+ }
182
+
183
+ function storeOrganisation({ organisations }) {
184
+ //TODO handle expiration
185
+ if (organisations && organisations.length && organisations.length > 0) {
186
+ let orgs = organisations.filter(org => org.org_type === 'MERCHANT')
187
+ if (orgs.length > 0 && _storeKVFn) {
188
+ _storeKVFn("organisation_id", orgs[0].external_id);
189
+ }
190
+ }
191
+ }
192
+ async function getOrganisation() {
193
+ //TODO handle expiration
194
+ if (_getKVFn) {
195
+ var organisation_id = await _getKVFn('organisation_id');
196
+ return organisation_id;
197
+ }
198
+ return null;
199
+ }
200
+
201
+ function switchSession({ access_token, refresh_token, exp,contact,initial_contact,communities }, isCommunity) {
202
+ _sessionData = jwtDecode(access_token);
203
+ if (isCommunity) {
204
+ let permission = _sessionData.groups ? _sessionData.groups : [];
205
+ let initialName = "";
206
+ if(initial_contact){
207
+ initialName = initial_contact.first_name + (initial_contact.last_name ? ( " " + initial_contact.last_name) : "");
208
+ }
209
+ _storeKVFn("community_id", contact.id);
210
+ _storeKVFn("initial_contact_id", initial_contact ? initial_contact.id : null);
211
+ _storeKVFn("initial_contact_name", initialName);
212
+ _storeKVFn("community_permission", JSON.stringify(permission));
213
+ } else {
214
+ _storeKVFn("community_id", null);
215
+ _storeKVFn("initial_contact_id", contact.id);
216
+ _storeKVFn("initial_contact_name", null);
217
+ _storeKVFn("community_permission", null);
218
+ }
219
+
220
+ startSession({ access_token, refresh_token, exp,communities })
221
+ }
222
+
223
+ function cleanSession() {
224
+ //TODO handle expiration
225
+ _accessToken = undefined;
226
+ _refreshToken = undefined;
227
+ if (_storeKVFn) {
228
+ _storeKVFn(REFRESH_TOKEN ? REFRESH_TOKEN : "refresh_token", undefined)
229
+ _storeKVFn(ACCESS_TOKEN ? ACCESS_TOKEN : "access_token", undefined)
230
+ //parse and store session data
231
+ logger.debug('Session cleared');
232
+ }
233
+ _sessionData = undefined;
234
+ }
235
+
236
+ function getSession() {
237
+ return _sessionData;
238
+ }
239
+
240
+ function getToken() {
241
+ return _accessToken;
242
+ }
243
+
244
+ function getURI(isBackend, resourcePath, isMiddleware, isMwNodejs, plugin) {
245
+ if (isMiddleware) {
246
+ return _middleware_host + resourcePath;
247
+ } else if (isMwNodejs) return _mwNodejs_host + resourcePath;
248
+ else if (plugin) {
249
+ return _host + '/plugins/v2/' + plugin + resourcePath;
250
+ }
251
+ else {
252
+ if (isBackend == true)
253
+ return _host + _backofficePath + resourcePath;
254
+ else
255
+ return _host + _selfServicePath + resourcePath;
256
+ }
257
+ }
258
+
259
+ export function json2Obj(str) {
260
+ try {
261
+ return JSON.parse(str);
262
+ } catch (e) {
263
+ return null;
264
+ }
265
+ }
266
+ async function post({
267
+ resourcePath,
268
+ body,
269
+ queryParams,
270
+ withAccessToken = false,
271
+ withoutApikey = false,
272
+ isBackend = false,
273
+ logOutIfSessionInvalid = true,
274
+ isRefreshToken,
275
+ accessToken,
276
+ returnText,
277
+ isMiddleware = false,
278
+ isMwNodejs = false,
279
+ plugin,
280
+ }) {
281
+ try {
282
+ let logoutStatus = await getData('LOGOUT_STATUS');
283
+ if(logoutStatus == 'PROCESSING') return;
284
+ let uri = getURI(isBackend, resourcePath, isMiddleware, isMwNodejs, plugin);
285
+ var options = {};
286
+ options.headers = initOptionHeader();
287
+ options.method = "POST";
288
+ options.credentials = 'omit';
289
+ if (isMiddleware) {
290
+ options.headers['x-api-key'] = _middleware_apiKey;
291
+ } else if (isMwNodejs) {
292
+ options.headers['x-api-key'] = _mwNodejs_apiKey;
293
+ }
294
+ else {
295
+ if (withAccessToken == true || logOutIfSessionInvalid == true || isRefreshToken == true) {
296
+ if (isRefreshToken)
297
+ options.headers['Authorization'] = 'Bearer ' + _refreshToken;
298
+ else if (accessToken) {
299
+ options.headers['Authorization'] = 'Bearer ' + accessToken;
300
+ }
301
+ else
302
+ options.headers['Authorization'] = 'Bearer ' + _accessToken;
303
+ }
304
+ else if (!withoutApikey) {
305
+ options.headers['api_key'] = _apiKey;
306
+ }
307
+ }
308
+ if (body)
309
+ options.body = JSON.stringify(body);
310
+ //console.log("_ssl_certificates:", _ssl_certificates);
311
+ if (_enable_ssl_pinning && _ssl_pinning_options)
312
+ options = { ...options, ..._ssl_pinning_options };
313
+ if (queryParams)
314
+ uri = uri + '?' + URLSearchParams(queryParams).toString();
315
+ logger.debug('POST:', uri);
316
+ let response = await _fetchFn(uri, options);
317
+ if (response.status == '200' || response.status == '201' || response.status == '204' || (response.status >= '200' && response.status <= '299')) {
318
+ if (returnText) {
319
+ let bodyText = await response.text()
320
+ logger.debug('Response:', response.status);
321
+ return { code: "OK", data: bodyText };
322
+ } else {
323
+ let bodyText = await response.text()
324
+ logger.debug('Response:', response.status);
325
+ return { code: "OK", data: bodyText ? json2Obj(bodyText) : null };
326
+ }
327
+ } else if (response.status == '401') {
328
+ var refreshResult = await refreshToken(logOutIfSessionInvalid);
329
+ logger.debug('POST refresh result received');
330
+ if (refreshResult.code == 'OK') {
331
+ options.headers = { ...options.headers, Authorization: "Bearer " + refreshResult.data.access_token };
332
+ options = { ...options, headers: options.headers };
333
+ response = await _fetchFn(uri, options);
334
+ let bodyText = await response.text()
335
+ if (response.status == '200') {
336
+ return { code: "OK", data: bodyText ? json2Obj(bodyText) : null };
337
+ }
338
+ return { code: response.status, bodyText: bodyText, error: json2Obj(bodyText) };
339
+ } else {
340
+ validateForceLogout(refreshResult, true);
341
+ }
342
+ }else if(response.status == '403'){
343
+ let bodyText = await response.text()
344
+ // showMessageError(resourcePath,'permission');
345
+ return { code: response.status, bodyText: bodyText, error: json2Obj(bodyText) };
346
+ } else {
347
+ let bodyText = await response.text()
348
+ validateForceLogout(response, logOutIfSessionInvalid);
349
+ return { code: response.status, bodyText: bodyText, error: json2Obj(bodyText) };
350
+ }
351
+ } catch (e) {
352
+ let bodyText = await e.text();
353
+ // if (e.status == '401') {
354
+ // let uri = getURI(isBackend, resourcePath);
355
+ // if (queryParams)
356
+ // uri = uri + '?' + querystring.encode(queryParams);
357
+ // var result = await processRefreshToken(uri,logOutIfSessionInvalid);
358
+ // return result;
359
+ // }
360
+ return { code: e.status, bodyText: bodyText, error: returnText ? bodyText : json2Obj(bodyText) };
361
+ }
362
+ }
363
+
364
+ async function postRefreshToken({
365
+ resourcePath,
366
+ body,
367
+ isBackend
368
+ }) {
369
+ try {
370
+ let logoutStatus = await getData('LOGOUT_STATUS');
371
+ if(logoutStatus == 'PROCESSING') return;
372
+ let uri = getURI(isBackend, resourcePath);
373
+ var options = {};
374
+ options.headers = initOptionHeader();
375
+ options.method = "POST";
376
+ options.credentials = 'omit';
377
+ options.headers['Authorization'] = 'Bearer ' + _refreshToken;
378
+ if (body)
379
+ options.body = JSON.stringify(body);
380
+ if (_enable_ssl_pinning && _ssl_pinning_options)
381
+ options = { ...options, ..._ssl_pinning_options };
382
+ logger.debug('POST:', uri);
383
+ let response = await _fetchFn(uri, options);
384
+ logger.debug('Refresh token response received');
385
+ return response;
386
+ } catch (e) {
387
+ return e;
388
+ }
389
+ }
390
+
391
+ async function validateForceLogout(response, logOutIfSessionInvalid) {
392
+ try {
393
+ if (logOutIfSessionInvalid == true && _sessionInvalidCallback && response.status == '401') {
394
+ await _sessionInvalidCallback(true);
395
+ cleanSession();
396
+ } else {
397
+ return response;
398
+ }
399
+ } catch (e) {
400
+ logger.error(e);
401
+ return e;
402
+ }
403
+ }
404
+
405
+ async function get({
406
+ resourcePath,
407
+ queryParams,
408
+ withAccessToken = false,
409
+ isBackend = false,
410
+ logOutIfSessionInvalid = true,
411
+ returnText = false,
412
+ unauthorize = false,
413
+ returnBlob = false,
414
+ apiKey,
415
+ isMiddleware = false,
416
+ isMwNodejs = false,
417
+ plugin,
418
+ }) {
419
+ try {
420
+ let logoutStatus = await getData('LOGOUT_STATUS');
421
+ if(logoutStatus == 'PROCESSING') return;
422
+ let uri = getURI(isBackend, resourcePath, isMiddleware, isMwNodejs, plugin);
423
+ var options = {};
424
+ options.headers = initOptionHeader();
425
+ options.method = "GET";
426
+ options.credentials = 'omit';
427
+ if (isMiddleware) {
428
+ options.headers['x-api-key'] = _middleware_apiKey;
429
+ if(withAccessToken) options.headers['x-access-token'] = _accessToken;
430
+ } else if (isMwNodejs) {
431
+ options.headers['x-api-key'] = _mwNodejs_apiKey;
432
+ }
433
+ else {
434
+ if (withAccessToken == true || logOutIfSessionInvalid == true)
435
+ options.headers['Authorization'] = 'Bearer ' + _accessToken;
436
+ else if (!unauthorize){
437
+ let key = apiKey ? apiKey : _apiKey;
438
+ if(key){
439
+ options.headers['api_key'] = key;
440
+ }
441
+ }
442
+ }
443
+ if (_enable_ssl_pinning && _ssl_pinning_options)
444
+ options = { ...options, ..._ssl_pinning_options };
445
+ if (queryParams)
446
+ {
447
+ const queryString = new URLSearchParams(
448
+ Object.fromEntries(
449
+ Object.entries(cleanObj(queryParams)).map(([k, v]) => [k, String(v)])
450
+ )
451
+ ).toString();
452
+ uri = uri + '?' + queryString;
453
+ }
454
+ let response = await _fetchFn(uri, options);
455
+ if (response.status == '200' || (response.status >= '200' && response.status <= '299')) {
456
+ if (returnText) {
457
+ let bodyText = await response.text()
458
+ return { code: "OK", data: bodyText };
459
+ } else if (returnBlob) {
460
+ let blob = await response.blob();
461
+ return { code: "OK", data: blob ? blob : null };
462
+ } else {
463
+ let bodyText = await response.text()
464
+ return { code: "OK", data: bodyText ? json2Obj(bodyText) : null };
465
+ }
466
+ } else if (response.status == '401') {
467
+ var result = await processRefreshToken(uri, logOutIfSessionInvalid, returnText);
468
+ return result;
469
+ }else if(response.status == '403'){
470
+ let bodyText = await response.text()
471
+ // showMessageError(resourcePath,'permission');
472
+ return { code: response.status, bodyText: bodyText, error: json2Obj(bodyText) };
473
+ }
474
+ else {
475
+ let bodyText = await response.text()
476
+ return { code: response.status, bodyText: bodyText, error: json2Obj(bodyText) };
477
+ }
478
+ } catch (e) {
479
+ logger.error("Request error:", e);
480
+ let bodyText = await e.text();
481
+ // if (e.status == '401') {
482
+ // let uri = getURI(isBackend, resourcePath);
483
+ // if (queryParams)
484
+ // uri = uri + '?' + querystring.encode(cleanObj(queryParams));
485
+ // var result = await processRefreshToken(uri,logOutIfSessionInvalid,returnText);
486
+ // return result;
487
+ // }
488
+ return { code: e.status, bodyText: bodyText, error: json2Obj(bodyText) };
489
+ }
490
+ }
491
+
492
+ async function sendDelete({
493
+ resourcePath,
494
+ queryParams,
495
+ withAccessToken = false,
496
+ isBackend = false,
497
+ logOutIfSessionInvalid = true,
498
+ isMiddleware = false,
499
+ isMwNodejs = false,
500
+ }) {
501
+ try {
502
+ let uri = getURI(isBackend, resourcePath, isMiddleware, isMwNodejs);
503
+ var options = {};
504
+ options.headers = initOptionHeader();
505
+ options.method = "DELETE";
506
+ options.credentials = 'omit';
507
+ if (isMiddleware) {
508
+ options.headers['x-api-key'] = _middleware_apiKey;
509
+ } else if (isMwNodejs) {
510
+ options.headers['x-api-key'] = _mwNodejs_apiKey;
511
+ }
512
+ else {
513
+ if (withAccessToken == true || logOutIfSessionInvalid == true)
514
+ options.headers['Authorization'] = 'Bearer ' + _accessToken;
515
+ else
516
+ options.headers['api_key'] = _apiKey;
517
+ }
518
+ if (_enable_ssl_pinning && _ssl_pinning_options)
519
+ options = { ...options, ..._ssl_pinning_options };
520
+ if (queryParams)
521
+ {
522
+ const queryString = new URLSearchParams(
523
+ Object.fromEntries(
524
+ Object.entries(cleanObj(queryParams)).map(([k, v]) => [k, String(v)])
525
+ )
526
+ ).toString();
527
+ uri = uri + '?' + queryString;
528
+ }
529
+ logger.debug('DELETE:', uri);
530
+ let response = await _fetchFn(uri, options);
531
+ let bodyText = await response.text()
532
+ logger.debug('Response:', response.status);
533
+ if (response.status == '200' || (response.status >= '200' && response.status <= '299')) {
534
+ return { code: "OK", data: bodyText ? json2Obj(bodyText) : null };
535
+ } else if (response.status == '401') {
536
+ var refreshResult = await refreshToken(logOutIfSessionInvalid);
537
+ if (refreshResult.code == 'OK') {
538
+ options.headers = { ...options.headers, Authorization: "Bearer " + refreshResult.data.access_token };
539
+ options = { ...options, headers: options.headers };
540
+ response = await _fetchFn(uri, options);
541
+ bodyText = await response.text()
542
+ if (response.status == '200') {
543
+ return { code: "OK", data: bodyText ? json2Obj(bodyText) : null };
544
+ }
545
+ return { code: response.status, bodyText: bodyText, error: json2Obj(bodyText) };
546
+ } else {
547
+ validateForceLogout(refreshResult, true);
548
+ }
549
+ }else if(response.status == '403'){
550
+ // showMessageError(resourcePath,'permission');
551
+ return { code: response.status, bodyText: bodyText, error: json2Obj(bodyText) };
552
+ } else {
553
+ validateForceLogout(response, logOutIfSessionInvalid);
554
+ return { code: response.status, bodyText: bodyText, error: json2Obj(bodyText) };
555
+ }
556
+ } catch (e) {
557
+ let bodyText = await e.text();
558
+ // if (e.status == '401') {
559
+ // let uri = getURI(isBackend, resourcePath);
560
+ // if (queryParams)
561
+ // uri = uri + '?' + querystring.encode(cleanObj(queryParams));
562
+ // var result = await processRefreshToken(uri,logOutIfSessionInvalid);
563
+ // return result;
564
+ // }
565
+ return { code: e.status, bodyText: bodyText, error: json2Obj(bodyText) };
566
+ }
567
+ }
568
+
569
+ async function put({
570
+ resourcePath,
571
+ body,
572
+ queryParams,
573
+ withAccessToken = false,
574
+ isBackend = false,
575
+ logOutIfSessionInvalid = true,
576
+ isMiddleware = false,
577
+ isMwNodejs = false,
578
+ accessToken,
579
+ }) {
580
+ try {
581
+ let uri = getURI(isBackend, resourcePath, isMiddleware, isMwNodejs);
582
+ var options = {};
583
+ options.headers = initOptionHeader();
584
+ options.method = "PUT";
585
+ options.credentials = 'omit';
586
+ if (isMiddleware) {
587
+ options.headers['x-api-key'] = _middleware_apiKey;
588
+ } else if (isMwNodejs) {
589
+ options.headers['x-api-key'] = _mwNodejs_apiKey;
590
+ }
591
+ else {
592
+ if (withAccessToken == true || logOutIfSessionInvalid == true) {
593
+ if (accessToken) {
594
+ options.headers['Authorization'] = 'Bearer ' + accessToken;
595
+ }
596
+ else{
597
+ options.headers['Authorization'] = 'Bearer ' + _accessToken;
598
+ }
599
+ }
600
+ else
601
+ options.headers['api_key'] = _apiKey;
602
+ }
603
+ if (body)
604
+ options.body = JSON.stringify(body);
605
+ if (_enable_ssl_pinning && _ssl_pinning_options)
606
+ options = { ...options, ..._ssl_pinning_options };
607
+ if (queryParams)
608
+ uri = uri + '?' + URLSearchParams(queryParams).toString();
609
+ logger.debug('PUT:', uri);
610
+ let response = await _fetchFn(uri, options);
611
+ let bodyText = await response.text()
612
+ logger.debug('Response:', response.status);
613
+ if (response.status == '200' || (response.status >= '200' && response.status <= '299')) {
614
+ return { code: "OK", data: bodyText ? json2Obj(bodyText) : null };
615
+ } else if (response.status == '401') {
616
+ var refreshResult = await refreshToken(logOutIfSessionInvalid);
617
+ if (refreshResult.code == 'OK') {
618
+ options.headers = { ...options.headers, Authorization: "Bearer " + refreshResult.data.access_token };
619
+ options = { ...options, headers: options.headers };
620
+ response = await _fetchFn(uri, options);
621
+ bodyText = await response.text()
622
+ if (response.status == '200') {
623
+ return { code: "OK", data: bodyText ? json2Obj(bodyText) : null };
624
+ }
625
+ return { code: response.status, bodyText: bodyText, error: json2Obj(bodyText) };
626
+ } else {
627
+ validateForceLogout(refreshResult, true);
628
+ }
629
+ } else if(response.status == '403'){
630
+ // showMessageError(resourcePath,'permission');
631
+ return { code: response.status, bodyText: bodyText, error: json2Obj(bodyText) };
632
+ } else {
633
+ validateForceLogout(response, logOutIfSessionInvalid);
634
+ return { code: response.status, bodyText: bodyText, error: json2Obj(bodyText) };
635
+ }
636
+ } catch (e) {
637
+ let bodyText = await e.text();
638
+ // if (e.status == '401') {
639
+ // let uri = getURI(isBackend, resourcePath);
640
+ // if (queryParams)
641
+ // uri = uri + '?' + querystring.encode(cleanObj(queryParams));
642
+ // var result = await processRefreshToken(uri,logOutIfSessionInvalid);
643
+ // return result;
644
+ // }
645
+ return { code: e.status, bodyText: bodyText, error: json2Obj(bodyText) };
646
+ }
647
+ }
648
+
649
+
650
+ function is200OK(result) {
651
+ if (result && result.status && result.status == '200')
652
+ return true;
653
+ else
654
+ return false;
655
+ }
656
+
657
+ function cleanObj(obj) {
658
+ for (var propName in obj) {
659
+ if (obj[propName] === null || obj[propName] === undefined) {
660
+ delete obj[propName];
661
+ }
662
+ }
663
+ return obj;
664
+ }
665
+
666
+ async function processRefreshToken(uri, logOutIfSessionInvalid, returnText) {
667
+ try {
668
+ let logoutStatus = await getData('LOGOUT_STATUS');
669
+ if(logoutStatus == 'PROCESSING') return;
670
+ var refreshResult = await refreshToken(logOutIfSessionInvalid);
671
+ if (refreshResult.code == 'OK') {
672
+ var options = {};
673
+ options.headers = initOptionHeader();
674
+ options.method = "GET";
675
+ options.credentials = 'omit';
676
+ if (_enable_ssl_pinning && _ssl_pinning_options)
677
+ options = { ...options, ..._ssl_pinning_options };
678
+ options.headers = { ...options.headers, Authorization: "Bearer " + refreshResult.data.access_token };
679
+ options = { ...options, headers: options.headers };
680
+ var response = await _fetchFn(uri, options);
681
+ var bodyText = await response.text()
682
+ if (response.status == '200') {
683
+ if (returnText)
684
+ return { code: "OK", data: bodyText };
685
+ return { code: "OK", data: bodyText ? json2Obj(bodyText) : null };
686
+ }
687
+ return { code: response.status, bodyText: bodyText, error: json2Obj(bodyText) };
688
+ } else {
689
+ validateForceLogout(refreshResult, true);
690
+ }
691
+ } catch (error) {
692
+ logger.error("Token refresh exception:", error);
693
+ validateForceLogout(error, true);
694
+ }
695
+ }
696
+
697
+ async function uploadFile({
698
+ resourcePath,
699
+ fileData,
700
+ body,
701
+ queryParams,
702
+ withAccessToken = false,
703
+ withoutApikey = false,
704
+ isBackend = false,
705
+ logOutIfSessionInvalid = true,
706
+ accessToken,
707
+ isMiddleware = false,
708
+ method = 'POST',
709
+ keyParam = 'file',
710
+ disalbedContentType = false,
711
+ }) {
712
+ try {
713
+ let uri = getURI(isBackend, resourcePath, isMiddleware);
714
+ var options = {};
715
+
716
+ if(!disalbedContentType){
717
+ options.headers = {
718
+ 'User-Agent': 'request',
719
+ 'Content-Type': 'multipart/form-data'
720
+ };
721
+ }
722
+ else {
723
+ options.headers = {};
724
+ }
725
+ if (isMiddleware) {
726
+ options.headers['x-api-key'] = _middleware_apiKey;
727
+ } else {
728
+ if (withAccessToken == true || logOutIfSessionInvalid == true) {
729
+ if (accessToken) {
730
+ options.headers['Authorization'] = 'Bearer ' + accessToken;
731
+ }
732
+ else
733
+ options.headers['Authorization'] = 'Bearer ' + _accessToken;
734
+ }
735
+ else if (!withoutApikey) {
736
+ options.headers['api_key'] = _apiKey;
737
+ }
738
+ }
739
+ var formData = new FormData();
740
+ if (fileData) {
741
+ formData.append(keyParam, fileData);
742
+ }
743
+ if (body) {
744
+ formData.body = JSON.stringify(body);
745
+ }
746
+ options.method = method;
747
+ options.credentials = 'omit';
748
+ options.body = formData;
749
+ //console.log("_ssl_certificates:", _ssl_certificates);
750
+ if (_enable_ssl_pinning && _ssl_pinning_options)
751
+ options = { ...options, ..._ssl_pinning_options };
752
+ logger.debug('UPLOAD POST:', uri);
753
+ let response = await _fetchFn(uri, options);
754
+ let bodyText = await response.text()
755
+ logger.debug('Response:', response.status);
756
+ if (response.status == '200' || response.status == '201' || response.status == 201) {
757
+ return { code: "OK", data: bodyText ? json2Obj(bodyText) : null };
758
+ } else if (response.status == '401') {
759
+ var refreshResult = await refreshToken(logOutIfSessionInvalid);
760
+ logger.debug('POST refresh result received');
761
+ if (refreshResult.code == 'OK') {
762
+ options.headers = { ...options.headers, Authorization: "Bearer " + refreshResult.data.access_token };
763
+ options = { ...options, headers: options.headers };
764
+ response = await _fetchFn(uri, options);
765
+ bodyText = await response.text()
766
+ if (response.status == '200' || response.status == '201' || response.status == 201) {
767
+ return { code: "OK", data: bodyText ? json2Obj(bodyText) : null };
768
+ }
769
+ return { code: response.status, bodyText: bodyText, error: json2Obj(bodyText) };
770
+ } else {
771
+ validateForceLogout(refreshResult, true);
772
+ }
773
+ } else if(response.status == '403'){
774
+ // showMessageError(resourcePath,'permission');
775
+ return { code: response.status, bodyText: bodyText, error: json2Obj(bodyText) };
776
+ }else {
777
+ validateForceLogout(response, logOutIfSessionInvalid);
778
+ return { code: response.status, bodyText: bodyText, error: json2Obj(bodyText) };
779
+ }
780
+ } catch (error) {
781
+ logger.error("Upload file exception:", error);
782
+ validateForceLogout(error, true);
783
+ }
784
+
785
+ }
786
+
787
+ async function uploadFileNew({
788
+ resourcePath,
789
+ fileData,
790
+ body,
791
+ queryParams,
792
+ withAccessToken = false,
793
+ withoutApikey = false,
794
+ isBackend = false,
795
+ logOutIfSessionInvalid = true,
796
+ accessToken,
797
+ isMiddleware = false
798
+ }) {
799
+ try {
800
+ let uri = getURI(isBackend, resourcePath, isMiddleware);
801
+
802
+ var formData = new FormData();
803
+ if (fileData) {
804
+ formData.append('file', fileData);
805
+ }
806
+
807
+ var options = {
808
+ method: 'POST',
809
+ body: formData,
810
+ credentials: 'omit',
811
+ headers: {},
812
+ };
813
+ if (isMiddleware) {
814
+ options.headers['x-api-key'] = _middleware_apiKey;
815
+ } else {
816
+ if (withAccessToken == true || logOutIfSessionInvalid == true) {
817
+ if (accessToken) {
818
+ options.headers['Authorization'] = 'Bearer ' + accessToken;
819
+ }
820
+ else
821
+ options.headers['Authorization'] = 'Bearer ' + _accessToken;
822
+ }
823
+ else if (!withoutApikey) {
824
+ options.headers['api_key'] = _apiKey;
825
+ }
826
+ }
827
+ //console.log("_ssl_certificates:", _ssl_certificates);
828
+ if (_enable_ssl_pinning && _ssl_pinning_options)
829
+ options = { ...options, ..._ssl_pinning_options };
830
+ logger.debug('UPLOAD POST:', uri);
831
+ let response = await _fetchFn(uri, options);
832
+ let bodyText = await response.text()
833
+ logger.debug('Response:', response.status);
834
+ if (response.status == '200') {
835
+ return { code: "OK", data: bodyText ? json2Obj(bodyText) : null };
836
+ } else if (response.status == '401') {
837
+ var refreshResult = await refreshToken(logOutIfSessionInvalid);
838
+ logger.debug('POST refresh result received');
839
+ if (refreshResult.code == 'OK') {
840
+ options.headers = { ...options.headers, Authorization: "Bearer " + refreshResult.data.access_token };
841
+ options = { ...options, headers: options.headers };
842
+ response = await _fetchFn(uri, options);
843
+ bodyText = await response.text()
844
+ if (response.status == '200') {
845
+ return { code: "OK", data: bodyText ? json2Obj(bodyText) : null };
846
+ }
847
+ return { code: response.status, bodyText: bodyText, error: json2Obj(bodyText) };
848
+ } else {
849
+ validateForceLogout(refreshResult, true);
850
+ }
851
+ }else if(response.status == '403'){
852
+ // showMessageError(resourcePath,'permission');
853
+ return { code: response.status, bodyText: bodyText, error: json2Obj(bodyText) };
854
+ } else {
855
+ validateForceLogout(response, logOutIfSessionInvalid);
856
+ return { code: response.status, bodyText: bodyText, error: json2Obj(bodyText) };
857
+ }
858
+ } catch (error) {
859
+ logger.error("Upload file exception:", error);
860
+ validateForceLogout(error, true);
861
+ }
862
+
863
+ }