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