df835a924f34c3a6b0c2fb4315295a0a0d012851
[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.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                 String response = null;
76
77                 // get the microservice object by the id
78                 MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId);
79
80                 // No such microservice available
81                 if (data == null) {
82                         return response;
83                 }
84                 List<MicroserviceParameter> params = data.getParameterList();
85                 MicroserviceParameter userId_param = new MicroserviceParameter();
86                 userId_param.setPara_key("userId");
87                 userId_param.setPara_value(user.getOrgUserId());
88                 params.add(userId_param);
89
90                 if (data.getSecurityType().equals(NO_AUTH)) {
91                         HttpHeaders headers = new HttpHeaders();
92                         headers.setContentType(MediaType.APPLICATION_JSON);
93                         HttpEntity<String> entity = new HttpEntity<String>(headers);
94
95                         String url = microserviceUrlConverter(data, params);
96                         logger.debug(EELFLoggerDelegate.debugLogger, "Before making no authentication call: {}", url);
97                         response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
98                         logger.debug(EELFLoggerDelegate.debugLogger, "No authentication call response: {}", response);
99
100                 } else if (data.getSecurityType().equals(BASIC_AUTH)) {
101                         // encoding the username and password
102                         String plainCreds = data.getUsername() + ":" + decryptedPassword(data.getPassword());
103                         byte[] plainCredsBytes = plainCreds.getBytes();
104                         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
105                         String base64Creds = new String(base64CredsBytes);
106
107                         HttpHeaders headers = new HttpHeaders();
108                         headers.add("Authorization", "Basic " + base64Creds);
109                         headers.setContentType(MediaType.APPLICATION_JSON);
110                         HttpEntity<String> entity = new HttpEntity<String>(headers);
111
112                         String url = microserviceUrlConverter(data, params);
113                         logger.debug(EELFLoggerDelegate.debugLogger, "Before making basic authentication call: {}", url);
114                         response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
115                         logger.debug(EELFLoggerDelegate.debugLogger, "Basic authentication call response: {}", response);
116
117                 } else if (data.getSecurityType().equals(COOKIE_AUTH)) {
118                         HttpHeaders headers = new HttpHeaders();
119                         headers.setContentType(MediaType.APPLICATION_JSON);
120                         String rawCookie = request.getHeader("Cookie");
121                         headers.add("Cookie", rawCookie);
122                         HttpEntity<String> entity = new HttpEntity<String>(headers);
123
124                         String url = microserviceUrlConverter(data, params);
125                         logger.debug(EELFLoggerDelegate.debugLogger, "Before making cookie-based authentication call: {}", url);
126                         response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
127                         logger.debug(EELFLoggerDelegate.debugLogger, "Cookie-based authentication call response: {}", response);
128                 }
129                 return response;
130         }
131
132         @Override
133         public String proxyToDestinationByWidgetId(long widgetId, EPUser user, HttpServletRequest request)
134                         throws Exception {
135
136                 String response = null;
137
138                 @SuppressWarnings({ "rawtypes", "unchecked" })
139                 ResponseEntity<Long> ans = (ResponseEntity<Long>) template.exchange(
140                                 "https://"
141                                                 + consulHealthService.getServiceLocation(whatService,
142                                                                 SystemProperties.getProperty("microservices.widget.local.port"))
143                                                 + "/widget/microservices/widgetCatalog/parameters/" + widgetId,
144                                 HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), Long.class);
145                 Long serviceId = ans.getBody();
146
147                 // get the microservice object by the id
148                 MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId);
149
150                 // No such microservice available
151                 if (data == null) {
152                         return response;
153                 }
154
155                 List<MicroserviceParameter> params = data.getParameterList();
156                 MicroserviceParameter userId_param = new MicroserviceParameter();
157                 userId_param.setPara_key("userId");
158                 userId_param.setPara_value(user.getOrgUserId());
159                 params.add(userId_param);
160
161                 for (MicroserviceParameter p : params) {
162                         WidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(),
163                                         p.getId());
164                         if (userValue != null)
165                                 p.setPara_value(userValue.getUser_value());
166                 }
167
168                 if (data.getSecurityType().equals(NO_AUTH)) {
169                         HttpHeaders headers = new HttpHeaders();
170                         headers.setContentType(MediaType.APPLICATION_JSON);
171                         HttpEntity<String> entity = new HttpEntity<String>(headers);
172
173                         String url = microserviceUrlConverter(data, params);
174                         try {
175                                 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
176                         } catch (HttpClientErrorException e) {
177                                 throw e;
178                         }
179                 } else if (data.getSecurityType().equals(BASIC_AUTH)) {
180                         // encoding the username and password
181                         String plainCreds = data.getUsername() + ":" + decryptedPassword(data.getPassword());
182                         byte[] plainCredsBytes = plainCreds.getBytes();
183                         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
184                         String base64Creds = new String(base64CredsBytes);
185
186                         HttpHeaders headers = new HttpHeaders();
187                         headers.add("Authorization", "Basic " + base64Creds);
188                         headers.setContentType(MediaType.APPLICATION_JSON);
189                         HttpEntity<String> entity = new HttpEntity<String>(headers);
190
191                         String url = microserviceUrlConverter(data, params);
192                         try {
193                                 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
194                         } catch (HttpClientErrorException e) {
195                                 throw e;
196                         }
197                 } else if (data.getSecurityType().equals(COOKIE_AUTH)) {
198                         HttpHeaders headers = new HttpHeaders();
199                         headers.setContentType(MediaType.APPLICATION_JSON);
200                         String rawCookie = request.getHeader("Cookie");
201                         headers.add("Cookie", rawCookie);
202                         HttpEntity<String> entity = new HttpEntity<String>(headers);
203
204                         String url = microserviceUrlConverter(data, params);
205                         try {
206                                 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
207                         } catch (HttpClientErrorException e) {
208                                 throw e;
209                         }
210                 }
211                 return response;
212         }
213
214         private String decryptedPassword(String encryptedPwd) throws Exception {
215                 String result = "";
216                 if (encryptedPwd != null & encryptedPwd.length() > 0) {
217                         try {
218                                 result = CipherUtil.decrypt(encryptedPwd,
219                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
220                         } catch (Exception e) {
221                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
222                                 throw e;
223                         }
224                 }
225                 return result;
226         }
227
228         private String microserviceUrlConverter(MicroserviceData data, List<MicroserviceParameter> params) {
229                 String url = data.getUrl();
230                 for (int i = 0; i < params.size(); i++) {
231                         if (i == 0) {
232                                 url += QUESTION_MARK;
233                         }
234                         url += params.get(i).getPara_key() + "=" + params.get(i).getPara_value();
235                         if (i != (params.size() - 1)) {
236                                 url += ADD_MARK;
237                         }
238                 }
239                 return url;
240         }
241
242 }