2 * ================================================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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 * ================================================================================
20 package org.openecomp.portalapp.portal.service;
22 import java.util.List;
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;
47 @Service("microserviceProxyService")
48 @EnableAspectJAutoProxy
50 public class MicroserviceProxyServiceImpl implements MicroserviceProxyService {
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 = "&";
59 String whatService = "widgets-service";
62 private ConsulHealthService consulHealthService;
65 MicroserviceService microserviceService;
68 WidgetParameterService widgetParameterService;
70 RestTemplate template = new RestTemplate();
73 public String proxyToDestination(long serviceId, EPUser user, HttpServletRequest request) throws Exception {
75 //get the microservice object by the id
76 MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId);
78 // No such microservice available
80 //can we return a better response than null?
84 return authenticateAndRespond(data, request, composeParams(data, user));
88 public String proxyToDestinationByWidgetId(long widgetId, EPUser user, HttpServletRequest request)
91 String response = null;
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();
102 // get the microservice object by the id
103 MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId);
105 // No such microservice available
110 List<MicroserviceParameter> params = composeParams(data, user);
111 for (MicroserviceParameter p : params) {
112 WidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(),
114 if (userValue != null)
115 p.setPara_value(userValue.getUser_value());
118 return authenticateAndRespond(data, request, params);
122 private String authenticateAndRespond(MicroserviceData data, HttpServletRequest request, List<MicroserviceParameter> params){
124 String response = null;
126 if (data.getSecurityType().equals(NO_AUTH)) {
127 HttpEntity<String> entity = new HttpEntity<String>(headersForNoAuth());
129 String url = microserviceUrlConverter(data, params);
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);
135 } catch (HttpClientErrorException e) {
138 } else if (data.getSecurityType().equals(BASIC_AUTH)) {
139 // encoding the username and password
140 String plainCreds = null;
142 plainCreds = data.getUsername() + ":" + decryptedPassword(data.getPassword());
145 logger.error("problem decrypting password ... check if decryption key is correct in system.properties: ", e);
147 byte[] plainCredsBytes = plainCreds.getBytes();
148 byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
149 String base64Creds = new String(base64CredsBytes);
151 HttpEntity<String> entity = new HttpEntity<String>(headersForBasicAuth(request, base64Creds));
153 String url = microserviceUrlConverter(data, params);
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());
160 } else if (data.getSecurityType().equals(COOKIE_AUTH)) {
161 HttpEntity<String> entity = new HttpEntity<String>(headersForCookieAuth(request));
162 String url = microserviceUrlConverter(data, params);
164 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
165 } catch (HttpClientErrorException e) {
173 private String decryptedPassword(String encryptedPwd) throws Exception {
175 if (encryptedPwd != null & encryptedPwd.length() > 0) {
177 result = CipherUtil.decrypt(encryptedPwd,
178 SystemProperties.getProperty(SystemProperties.Decryption_Key));
179 } catch (Exception e) {
180 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
188 private String microserviceUrlConverter(MicroserviceData data, List<MicroserviceParameter> params) {
189 String url = data.getUrl();
190 for (int i = 0; i < params.size(); i++) {
192 url += QUESTION_MARK;
194 url += params.get(i).getPara_key() + "=" + params.get(i).getPara_value();
195 if (i != (params.size() - 1)) {
203 private HttpHeaders headersForNoAuth(){
204 HttpHeaders headers = new HttpHeaders();
205 headers.setContentType(MediaType.APPLICATION_JSON);
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);
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);
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);