[SDC-29] Amdocs OnBoard 1707 initial commit.
[sdc.git] / openecomp-ui / src / nfvo-utils / RestAPIUtil.js
1 /*!
2  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
13  * or implied. See the License for the specific language governing
14  * permissions and limitations under the License.
15  */
16 import {RestfulAPI} from 'restful-js';
17 import uuid from 'uuid-js';
18 import md5 from 'md5';
19
20 import store from 'sdc-app/AppStore.js';
21 import {actionTypes as LoaderConstants} from 'nfvo-components/loader/LoaderConstants.js';
22 import Configuration from 'sdc-app/config/Configuration.js';
23 import errorResponseHandler from './ErrorResponseHandler.js';
24
25 const AUTHORIZATION_HEADER = 'X-AUTH-TOKEN';
26 const STORAGE_AUTH_KEY = 'sdc-auth-token';
27 const REQUEST_ID_HEADER = 'X-ECOMP-RequestID';
28 const CONTENT_MD5_HEADER = 'Content-MD5';
29
30
31
32
33 function applyMD5Header(options, data) {
34         if (options.md5) {
35                 let headers = options.headers;
36                 headers[CONTENT_MD5_HEADER] = window.btoa(md5(JSON.stringify(data)).toLowerCase());
37         }
38 }
39
40 function handleResponse(xhr) {
41         let authToken = xhr.getResponseHeader(AUTHORIZATION_HEADER);
42         let prevToken = this && this.headers && this.headers[AUTHORIZATION_HEADER];
43         if (authToken && authToken !== prevToken) {
44                 if (authToken === 'null') {
45                         localStorage.removeItem(STORAGE_AUTH_KEY);
46                 } else {
47                         localStorage.setItem(STORAGE_AUTH_KEY, authToken);
48                 }
49         }
50 }
51
52
53 class RestAPIUtil extends RestfulAPI {
54
55         applySecurity(options, data) {
56                 let headers = options.headers || (options.headers = {});
57
58                 let authToken = localStorage.getItem(STORAGE_AUTH_KEY);
59                 if (authToken) {
60                         headers[AUTHORIZATION_HEADER] = authToken;
61                 }
62
63                 let attApiHeaders = Configuration.get('ATTApiHeaders'),
64                         attUidHeader = attApiHeaders && attApiHeaders.userId;
65                 if (attUidHeader) {
66                         headers[attUidHeader.name] = attUidHeader.value;
67                 }
68
69                 headers[REQUEST_ID_HEADER] = uuid.create().toString();
70                 applyMD5Header(options, data);
71         }
72
73         handleRequest(url, type, options = {}, data){
74                 let success = options.success;
75                 options.success = function (resp, textStatus, xhr) {
76                         handleResponse.call(this, xhr);
77                         if (success) {
78                                 success.call(options.context, {...resp}, textStatus, xhr);
79                         }
80                 };
81
82                 if (DEBUG) {
83                         console.log('--> Making REST call (' + type + '): ' + url);
84                 }
85                 return super.handleRequest(url, type, options, data);
86         }
87
88 }
89
90 const instance = new RestAPIUtil({
91         errorResponseHandler,
92         ajaxStartHandler: () => store.dispatch({type: LoaderConstants.SHOW}),
93         ajaxStopHandler: () => store.dispatch({type: LoaderConstants.HIDE})
94 });
95
96 // jQuery binary transport to download files through XHR
97 // http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
98 // https://github.com/henrya/js-jquery/tree/master/BinaryTransport
99 instance.$.ajaxTransport('+binary', function (options/*, originalOptions , jqXHR*/) {
100         // check for conditions and support for blob / arraybuffer response type
101         if (window.FormData && ((options.dataType && (options.dataType === 'binary')) ||
102                 (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) ||
103                 (window.Blob && options.data instanceof Blob))))
104         ) {
105                 return {
106                         // create new XMLHttpRequest
107                         send: function (headers, callback) {
108                                 // setup all letiables
109                                 let xhr = new XMLHttpRequest(),
110                                         url = options.url,
111                                         type = options.type,
112                                         async = options.async || true,
113                                         // blob or arraybuffer. Default is blob
114                                         dataType = options.responseType || 'blob',
115                                         data = options.data || null,
116                                         username = options.username || null,
117                                         password = options.password || null;
118
119                                 xhr.addEventListener('load', function () {
120                                         let data = {};
121                                         data[options.dataType] = xhr.response;
122                                         // make callback and send data
123                                         callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
124                                 });
125
126                                 xhr.open(type, url, async, username, password);
127
128                                 // setup custom headers
129                                 for (let i in headers) {
130                                         xhr.setRequestHeader(i, headers[i]);
131                                 }
132
133                                 xhr.responseType = dataType;
134                                 xhr.send(data);
135                         },
136                         abort: function () {
137                         }
138                 };
139         }
140 });
141
142 export default instance;