f5a542bf54708570e868feb13ad12d68331c97ab
[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 import org.apache.commons.codec.binary.Base64;
26 import org.openecomp.portalapp.portal.domain.EPUser;
27 import org.openecomp.portalapp.portal.domain.MicroserviceData;
28 import org.openecomp.portalapp.portal.domain.MicroserviceParameter;
29 import org.openecomp.portalapp.portal.domain.WidgetCatalogParameter;
30 import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders;
31 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
32 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
33 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
34 import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
35 import org.openecomp.portalsdk.core.util.SystemProperties;
36 import org.springframework.beans.factory.annotation.Autowired;
37 import org.springframework.context.annotation.EnableAspectJAutoProxy;
38 import org.springframework.http.HttpEntity;
39 import org.springframework.http.HttpHeaders;
40 import org.springframework.http.HttpMethod;
41 import org.springframework.http.MediaType;
42 import org.springframework.http.ResponseEntity;
43 import org.springframework.stereotype.Service;
44 import org.springframework.web.client.HttpClientErrorException;
45 import org.springframework.web.client.RestTemplate;
46
47 @Service("microserviceProxyService")
48 @EnableAspectJAutoProxy
49 @EPMetricsLog
50 public class MicroserviceProxyServiceImpl implements MicroserviceProxyService {
51
52         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MicroserviceProxyServiceImpl.class);
53         private static final String BASIC_AUTH = "Basic Authentication";
54         private static final String NO_AUTH = "No Authentication";
55         private static final String COOKIE_AUTH = "Cookie based Authentication";
56         private static final String QUESTION_MARK = "?";
57         private static final String ADD_MARK = "&";
58
59         String whatService = "widgets-service";
60
61         @Autowired
62         private ConsulHealthService consulHealthService;
63
64         @Autowired
65         MicroserviceService microserviceService;
66
67         @Autowired
68         WidgetParameterService widgetParameterService;
69
70         RestTemplate template = new RestTemplate();
71
72         @Override
73         public String proxyToDestination(long serviceId, EPUser user, HttpServletRequest request) throws Exception {
74
75                 //get the microservice object by the id
76                 MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId);
77
78                 // No such microservice available
79                 if (data == null) {
80                         //can we return a better response than null?
81                         return null;
82                 }
83         
84                 return authenticateAndRespond(data, request, composeParams(data, user));
85         }
86         
87         @Override
88         public String proxyToDestinationByWidgetId(long widgetId, EPUser user, HttpServletRequest request)
89                         throws Exception {
90
91                 String response = null;
92
93                 @SuppressWarnings({ "rawtypes", "unchecked" })
94                 ResponseEntity<Long> ans = (ResponseEntity<Long>) template.exchange(
95                                 EcompPortalUtils.widgetMsProtocol() + "://"
96                                                 + consulHealthService.getServiceLocation(whatService,
97                                                                 SystemProperties.getProperty("microservices.widget.local.port"))
98                                                 + "/widget/microservices/widgetCatalog/parameters/" + widgetId,
99                                 HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), Long.class);
100                 Long serviceId = ans.getBody();
101
102                 // get the microservice object by the id
103                 MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId);
104
105                 // No such microservice available
106                 if (data == null) {
107                         return response;
108                 }
109
110                 List<MicroserviceParameter> params = composeParams(data, user);
111                 for (MicroserviceParameter p : params) {
112                         WidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(),
113                                         p.getId());
114                         if (userValue != null)
115                                 p.setPara_value(userValue.getUser_value());
116                 }
117                 
118                 return authenticateAndRespond(data, request, params);
119
120         }
121
122         private String authenticateAndRespond(MicroserviceData data, HttpServletRequest request, List<MicroserviceParameter> params){
123                 
124                 String response = null;
125                 
126                 if (data.getSecurityType().equals(NO_AUTH)) {
127                         HttpEntity<String> entity = new HttpEntity<String>(headersForNoAuth());
128
129                         String url = microserviceUrlConverter(data, params);
130                         try {
131                                 logger.debug(EELFLoggerDelegate.debugLogger, "Before making no authentication call: {}", url);
132                                 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
133                                 logger.debug(EELFLoggerDelegate.debugLogger, "No authentication call response: {}", response);
134
135                         } catch (HttpClientErrorException e) {
136                                 throw e;
137                         }
138                 } else if (data.getSecurityType().equals(BASIC_AUTH)) {
139                         // encoding the username and password
140                         String plainCreds = null;
141                         try{
142                                 plainCreds = data.getUsername() + ":" + decryptedPassword(data.getPassword());
143                         }
144                         catch(Exception e){
145                                 logger.error("problem decrypting password ... check if decryption key is correct in system.properties: ", e);
146                         }
147                         byte[] plainCredsBytes = plainCreds.getBytes();
148                         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
149                         String base64Creds = new String(base64CredsBytes);
150
151                         HttpEntity<String> entity = new HttpEntity<String>(headersForBasicAuth(request, base64Creds));
152
153                         String url = microserviceUrlConverter(data, params);
154                         try {
155                                 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
156                         } catch (HttpClientErrorException e) {
157                                 logger.error("Problem while talking to {1} - message: {2} ", url, e.getMessage());
158                                 throw e;
159                         }
160                 } else if (data.getSecurityType().equals(COOKIE_AUTH)) {
161                         HttpEntity<String> entity = new HttpEntity<String>(headersForCookieAuth(request));
162                         String url = microserviceUrlConverter(data, params);
163                         try {
164                                 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
165                         } catch (HttpClientErrorException e) {
166                                 throw e;
167                         }
168                 }
169                 
170                 return response;
171         }
172         
173         private String decryptedPassword(String encryptedPwd) throws Exception {
174                 String result = "";
175                 if (encryptedPwd != null & encryptedPwd.length() > 0) {
176                         try {
177                                 result = CipherUtil.decrypt(encryptedPwd,
178                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
179                         } catch (Exception e) {
180                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
181                                 throw e;
182                         }
183                 }
184                 
185                 return result;
186         }
187
188         private String microserviceUrlConverter(MicroserviceData data, List<MicroserviceParameter> params) {
189                 String url = data.getUrl();
190                 for (int i = 0; i < params.size(); i++) {
191                         if (i == 0) {
192                                 url += QUESTION_MARK;
193                         }
194                         url += params.get(i).getPara_key() + "=" + params.get(i).getPara_value();
195                         if (i != (params.size() - 1)) {
196                                 url += ADD_MARK;
197                         }
198                 }
199
200                 return url;
201         }
202         
203         private HttpHeaders headersForNoAuth(){
204                 HttpHeaders headers = new HttpHeaders();
205                 headers.setContentType(MediaType.APPLICATION_JSON);
206
207                 return headers;
208         }
209         
210         private HttpHeaders headersForBasicAuth(HttpServletRequest request, String base64Creds){
211                 HttpHeaders headers = new HttpHeaders();
212                 headers.add("Authorization", "Basic " + base64Creds);
213                 headers.setContentType(MediaType.APPLICATION_JSON);
214                 String rawCookie = request.getHeader("Cookie");
215                 headers.add("Cookie", rawCookie);
216                 
217                 return headers;
218         }
219
220         private HttpHeaders headersForCookieAuth(HttpServletRequest request){
221                 HttpHeaders headers = new HttpHeaders();
222                 headers.setContentType(MediaType.APPLICATION_JSON);
223                 String rawCookie = request.getHeader("Cookie");
224                 headers.add("Cookie", rawCookie);
225                 
226                 return headers;
227         }
228         
229         private List<MicroserviceParameter> composeParams(MicroserviceData data, EPUser user){
230                 List<MicroserviceParameter> params = data.getParameterList();
231                 MicroserviceParameter userId_param = new MicroserviceParameter();
232                 userId_param.setPara_key("userId");
233                 userId_param.setPara_value(user.getOrgUserId());
234                 params.add(userId_param);
235                 
236                 return params;
237         }
238 }