Add portal property; correct docker build script.
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / service / MicroserviceProxyServiceImpl.java
1 /*-
2  * ================================================================================
3  * ECOMP Portal
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ================================================================================
19  */
20 package org.openecomp.portalapp.portal.service;
21
22 import java.util.List;
23
24 import javax.servlet.http.HttpServletRequest;
25
26 import org.apache.commons.codec.binary.Base64;
27 import org.openecomp.portalapp.portal.domain.EPUser;
28 import org.openecomp.portalapp.portal.domain.MicroserviceData;
29 import org.openecomp.portalapp.portal.domain.MicroserviceParameter;
30 import org.openecomp.portalapp.portal.domain.WidgetCatalogParameter;
31 import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders;
32 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
33 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
34 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
35 import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
36 import org.openecomp.portalsdk.core.util.SystemProperties;
37 import org.springframework.beans.factory.annotation.Autowired;
38 import org.springframework.context.annotation.EnableAspectJAutoProxy;
39 import org.springframework.http.HttpEntity;
40 import org.springframework.http.HttpHeaders;
41 import org.springframework.http.HttpMethod;
42 import org.springframework.http.MediaType;
43 import org.springframework.http.ResponseEntity;
44 import org.springframework.stereotype.Service;
45 import org.springframework.web.client.HttpClientErrorException;
46 import org.springframework.web.client.RestTemplate;
47
48 @Service("microserviceProxyService")
49 @EnableAspectJAutoProxy
50 @EPMetricsLog
51 public class MicroserviceProxyServiceImpl implements MicroserviceProxyService {
52
53         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MicroserviceProxyServiceImpl.class);
54         private static final String BASIC_AUTH = "Basic Authentication";
55         private static final String NO_AUTH = "No Authentication";
56         private static final String COOKIE_AUTH = "Cookie based Authentication";
57         private static final String QUESTION_MARK = "?";
58         private static final String ADD_MARK = "&";
59
60         String whatService = "widgets-service";
61
62         @Autowired
63         private ConsulHealthService consulHealthService;
64
65         @Autowired
66         MicroserviceService microserviceService;
67
68         @Autowired
69         WidgetParameterService widgetParameterService;
70
71         RestTemplate template = new RestTemplate();
72
73         @Override
74         public String proxyToDestination(long serviceId, EPUser user, HttpServletRequest request) throws Exception {
75
76                 String response = null;
77
78                 // get the microservice object by the id
79                 MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId);
80
81                 // No such microservice available
82                 if (data == null) {
83                         return response;
84                 }
85                 List<MicroserviceParameter> params = data.getParameterList();
86                 MicroserviceParameter userId_param = new MicroserviceParameter();
87                 userId_param.setPara_key("userId");
88                 userId_param.setPara_value(user.getOrgUserId());
89                 params.add(userId_param);
90
91                 if (data.getSecurityType().equals(NO_AUTH)) {
92                         HttpHeaders headers = new HttpHeaders();
93                         headers.setContentType(MediaType.APPLICATION_JSON);
94                         HttpEntity<String> entity = new HttpEntity<String>(headers);
95
96                         String url = microserviceUrlConverter(data, params);
97                         logger.debug(EELFLoggerDelegate.debugLogger, "Before making no authentication call: {}", url);
98                         response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
99                         logger.debug(EELFLoggerDelegate.debugLogger, "No authentication call response: {}", response);
100
101                 } else if (data.getSecurityType().equals(BASIC_AUTH)) {
102                         // encoding the username and password
103                         String plainCreds = data.getUsername() + ":" + decryptedPassword(data.getPassword());
104                         byte[] plainCredsBytes = plainCreds.getBytes();
105                         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
106                         String base64Creds = new String(base64CredsBytes);
107
108                         HttpHeaders headers = new HttpHeaders();
109                         headers.add("Authorization", "Basic " + base64Creds);
110                         headers.setContentType(MediaType.APPLICATION_JSON);
111                         HttpEntity<String> entity = new HttpEntity<String>(headers);
112
113                         String url = microserviceUrlConverter(data, params);
114                         logger.debug(EELFLoggerDelegate.debugLogger, "Before making basic authentication call: {}", url);
115                         response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
116                         logger.debug(EELFLoggerDelegate.debugLogger, "Basic authentication call response: {}", response);
117
118                 } else if (data.getSecurityType().equals(COOKIE_AUTH)) {
119                         HttpHeaders headers = new HttpHeaders();
120                         headers.setContentType(MediaType.APPLICATION_JSON);
121                         String rawCookie = request.getHeader("Cookie");
122                         headers.add("Cookie", rawCookie);
123                         HttpEntity<String> entity = new HttpEntity<String>(headers);
124
125                         String url = microserviceUrlConverter(data, params);
126                         logger.debug(EELFLoggerDelegate.debugLogger, "Before making cookie-based authentication call: {}", url);
127                         response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
128                         logger.debug(EELFLoggerDelegate.debugLogger, "Cookie-based authentication call response: {}", response);
129                 }
130                 return response;
131         }
132
133         @Override
134         public String proxyToDestinationByWidgetId(long widgetId, EPUser user, HttpServletRequest request)
135                         throws Exception {
136
137                 String response = null;
138
139                 @SuppressWarnings({ "rawtypes", "unchecked" })
140                 ResponseEntity<Long> ans = (ResponseEntity<Long>) template.exchange(
141                                 EcompPortalUtils.widgetMsProtocol() + "://"
142                                                 + consulHealthService.getServiceLocation(whatService,
143                                                                 SystemProperties.getProperty("microservices.widget.local.port"))
144                                                 + "/widget/microservices/widgetCatalog/parameters/" + widgetId,
145                                 HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), Long.class);
146                 Long serviceId = ans.getBody();
147
148                 // get the microservice object by the id
149                 MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId);
150
151                 // No such microservice available
152                 if (data == null) {
153                         return response;
154                 }
155
156                 List<MicroserviceParameter> params = data.getParameterList();
157                 MicroserviceParameter userId_param = new MicroserviceParameter();
158                 userId_param.setPara_key("userId");
159                 userId_param.setPara_value(user.getOrgUserId());
160                 params.add(userId_param);
161
162                 for (MicroserviceParameter p : params) {
163                         WidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(),
164                                         p.getId());
165                         if (userValue != null)
166                                 p.setPara_value(userValue.getUser_value());
167                 }
168
169                 if (data.getSecurityType().equals(NO_AUTH)) {
170                         HttpHeaders headers = new HttpHeaders();
171                         headers.setContentType(MediaType.APPLICATION_JSON);
172                         HttpEntity<String> entity = new HttpEntity<String>(headers);
173
174                         String url = microserviceUrlConverter(data, params);
175                         try {
176                                 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
177                         } catch (HttpClientErrorException e) {
178                                 throw e;
179                         }
180                 } else if (data.getSecurityType().equals(BASIC_AUTH)) {
181                         // encoding the username and password
182                         String plainCreds = data.getUsername() + ":" + decryptedPassword(data.getPassword());
183                         byte[] plainCredsBytes = plainCreds.getBytes();
184                         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
185                         String base64Creds = new String(base64CredsBytes);
186
187                         HttpHeaders headers = new HttpHeaders();
188                         headers.add("Authorization", "Basic " + base64Creds);
189                         headers.setContentType(MediaType.APPLICATION_JSON);
190                         HttpEntity<String> entity = new HttpEntity<String>(headers);
191
192                         String url = microserviceUrlConverter(data, params);
193                         try {
194                                 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
195                         } catch (HttpClientErrorException e) {
196                                 throw e;
197                         }
198                 } else if (data.getSecurityType().equals(COOKIE_AUTH)) {
199                         HttpHeaders headers = new HttpHeaders();
200                         headers.setContentType(MediaType.APPLICATION_JSON);
201                         String rawCookie = request.getHeader("Cookie");
202                         headers.add("Cookie", rawCookie);
203                         HttpEntity<String> entity = new HttpEntity<String>(headers);
204
205                         String url = microserviceUrlConverter(data, params);
206                         try {
207                                 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
208                         } catch (HttpClientErrorException e) {
209                                 throw e;
210                         }
211                 }
212                 return response;
213         }
214
215         private String decryptedPassword(String encryptedPwd) throws Exception {
216                 String result = "";
217                 if (encryptedPwd != null & encryptedPwd.length() > 0) {
218                         try {
219                                 result = CipherUtil.decrypt(encryptedPwd,
220                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
221                         } catch (Exception e) {
222                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
223                                 throw e;
224                         }
225                 }
226                 return result;
227         }
228
229         private String microserviceUrlConverter(MicroserviceData data, List<MicroserviceParameter> params) {
230                 String url = data.getUrl();
231                 for (int i = 0; i < params.size(); i++) {
232                         if (i == 0) {
233                                 url += QUESTION_MARK;
234                         }
235                         url += params.get(i).getPara_key() + "=" + params.get(i).getPara_value();
236                         if (i != (params.size() - 1)) {
237                                 url += ADD_MARK;
238                         }
239                 }
240                 return url;
241         }
242
243 }