Integrate VNF Repository with SDC
[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                 if (options.isAnonymous) {
59                         return;
60                 }
61
62                 let authToken = localStorage.getItem(STORAGE_AUTH_KEY);
63                 if (authToken) {
64                         headers[AUTHORIZATION_HEADER] = authToken;
65                 }
66
67                 let attApiHeaders = Configuration.get('ATTApiHeaders'),
68                         attUidHeader = attApiHeaders && attApiHeaders.userId;
69                 if (attUidHeader) {
70                         headers[attUidHeader.name] = attUidHeader.value;
71                 }
72
73                 headers[REQUEST_ID_HEADER] = uuid.create().toString();
74                 applyMD5Header(options, data);
75         }
76
77         handleRequest(url, type, options = {}, data){
78                 let success = options.success;
79                 options.success = function (resp, textStatus, xhr) {
80                         handleResponse.call(this, xhr);
81                         if (success) {
82                                 success.call(options.context, {...resp}, textStatus, xhr);
83                         }
84                 };
85
86                 if (DEBUG) {
87                         console.log('--> Making REST call (' + type + '): ' + url);
88                 }
89                 return super.handleRequest(url, type, options, data);
90         }
91
92 }
93
94 const instance = new RestAPIUtil({
95         errorResponseHandler,
96         ajaxStartHandler: () => store.dispatch({type: LoaderConstants.SHOW}),
97         ajaxStopHandler: () => store.dispatch({type: LoaderConstants.HIDE})
98 });
99
100 // jQuery binary transport to download files through XHR
101 // http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
102 // https://github.com/henrya/js-jquery/tree/master/BinaryTransport
103 instance.$.ajaxTransport('+binary', function (options/*, originalOptions , jqXHR*/) {
104         // check for conditions and support for blob / arraybuffer response type
105         if (window.FormData && ((options.dataType && (options.dataType === 'binary')) ||
106                 (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) ||
107                 (window.Blob && options.data instanceof Blob))))
108         ) {
109                 return {
110                         // create new XMLHttpRequest
111                         send: function (headers, callback) {
112                                 // setup all letiables
113                                 let xhr = new XMLHttpRequest(),
114                                         url = options.url,
115                                         type = options.type,
116                                         async = options.async || true,
117                                         // blob or arraybuffer. Default is blob
118                                         dataType = options.responseType || 'blob',
119                                         data = options.data || null,
120                                         username = options.username || null,
121                                         password = options.password || null;
122
123                                 xhr.addEventListener('load', function () {
124                                         let data = {};
125                                         data[options.dataType] = xhr.response;
126                                         // make callback and send data
127                                         callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
128                                 });
129
130                                 xhr.open(type, url, async, username, password);
131
132                                 // setup custom headers
133                                 for (let i in headers) {
134                                         xhr.setRequestHeader(i, headers[i]);
135                                 }
136
137                                 xhr.responseType = dataType;
138                                 xhr.send(data);
139                         },
140                         abort: function () {
141                         }
142                 };
143         }
144 });
145
146 export default instance;