fixes for supporting non-gui application access provisioning
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / service / sessionmgt / SessionCommunication.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.service.sessionmgt;
39
40 import java.io.BufferedReader;
41 import java.io.InputStreamReader;
42 import java.net.HttpURLConnection;
43 import java.net.URL;
44 import java.util.Base64;
45 import java.util.HashMap;
46 import java.util.Map;
47 import java.util.UUID;
48
49 import javax.servlet.http.HttpServletResponse;
50
51 import org.onap.portalapp.portal.domain.EPApp;
52 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
53 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
54 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
55 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
56 import org.onap.portalapp.portal.service.AppsCacheService;
57 import org.onap.portalapp.portal.transport.OnboardingApp;
58 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
59 import org.onap.portalapp.portal.utils.EcompPortalUtils;
60 import org.onap.portalsdk.core.exception.UrlAccessRestrictedException;
61 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
62 import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
63 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
64 import org.onap.portalsdk.core.util.SystemProperties;
65 import org.slf4j.MDC;
66 import org.springframework.beans.factory.annotation.Autowired;
67 import org.springframework.context.annotation.EnableAspectJAutoProxy;
68 import org.springframework.stereotype.Service;
69 import org.apache.commons.lang.StringUtils;
70
71 import com.att.eelf.configuration.Configuration;
72
73 @Service("sessionCommunication")
74 @org.springframework.context.annotation.Configuration
75 @EnableAspectJAutoProxy
76 public class SessionCommunication {
77         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SessionCommunication.class);
78         @Autowired
79         private AppsCacheService appsCacheService;
80         
81         private static final String BASIC_AUTHENTICATION_HEADER = "Authorization";
82
83         @EPAuditLog
84         public String sendGet(OnboardingApp app) throws Exception {
85                 String appResponse = "";
86                 String appName = "";
87                 int responseCode = 0;
88                 if (app != null && app.getAppName() != null && app.getAppName() != "") {
89                         try {
90                                 appName = app.getAppName();
91                                 String url = app.getRestUrl() + "/sessionTimeOuts";
92                                 String encriptedPwdDB = app.getAppBasicAuthPassword();
93                                 String appUserName = app.getAppBasicAuthUsername();
94
95                                 setLocalMDCContext(app, "/sessionTimeOuts", url);
96
97                                 URL obj = new URL(url);
98
99                                 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
100
101                                 // optional default is GET
102                                 con.setRequestMethod("GET");
103                                 con.setConnectTimeout(3000);
104                                 con.setReadTimeout(8000);
105                                 // add request header
106                                 Map<String,String> headers = getHeaders(app);
107                                 appUserName =headers.get("username");
108                                 encriptedPwdDB = headers.get("password");
109                                 
110                                 con.setRequestProperty("username", appUserName);
111                                 con.setRequestProperty("password", encriptedPwdDB);
112
113                                 
114                                 String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + encriptedPwdDB).getBytes());
115                                 String encodingStr = "Basic " + encoding;
116                                 con.setRequestProperty(BASIC_AUTHENTICATION_HEADER, encodingStr);
117
118                                 // con.set
119                                 responseCode = con.getResponseCode();
120                                 logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
121
122                                 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
123                                 String inputLine;
124                                 StringBuffer response = new StringBuffer();
125
126                                 while ((inputLine = in.readLine()) != null) {
127                                         response.append(inputLine);
128                                 }
129
130                                 in.close();
131                                 appResponse = response.toString();
132                         } catch (UrlAccessRestrictedException e) {
133                                 responseCode = HttpServletResponse.SC_UNAUTHORIZED;
134                                 logger.error(EELFLoggerDelegate.errorLogger, String.format(
135                                                 "SessionCommunication.sendGet received an un-authorized exception. AppName: %s", appName));
136                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
137                         } catch (Exception e) {
138                                 responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
139                                 String message = String.format(
140                                                 "SessionCommunication.sendGet encountered an Exception. AppName: %s, Details: %s", appName,
141                                                 e.toString());
142                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e);
143                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
144                         } finally {
145                                 EcompPortalUtils.setExternalAppResponseCode(responseCode);
146                         }
147                 } else {
148                         logger.error(EELFLoggerDelegate.errorLogger, "SessionCommunication sendGet: app is null");
149                 }
150                 return appResponse;
151         }
152
153         @EPAuditLog
154         public Boolean pingSession(OnboardingApp app, String sessionTimeoutMap) throws Exception {
155                 String appName = "";
156                 int responseCode = 0;
157                 try {
158                         if (app == null)
159                                 throw new Exception("SessionCommunication.pingSession: app is null");
160                         if (app != null && app.getAppName() != null && app.getAppName() != "") {
161                                 appName = app.getAppName();
162                         }
163                         String url = app.getRestUrl() + "/updateSessionTimeOuts";
164                         String encriptedPwdDB = app.getAppBasicAuthPassword();
165                         String appUserName = app.getAppBasicAuthUsername();
166
167                         setLocalMDCContext(app, "/updateSessionTimeOuts", url);
168
169                         URL obj = new URL(url);
170
171                         HttpURLConnection con = (HttpURLConnection) obj.openConnection();
172
173                         // optional default is GET
174                         con.setRequestMethod("POST");
175                         con.setConnectTimeout(3000);
176                         con.setReadTimeout(15000);
177
178                         Map<String,String> headers = getHeaders(app);
179                         appUserName =headers.get("username");
180                         encriptedPwdDB = headers.get("password");
181                         
182                         con.setRequestProperty("username", appUserName);
183                         con.setRequestProperty("password", encriptedPwdDB);
184                         
185                         String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + encriptedPwdDB).getBytes());
186                         String encodingStr = "Basic " + encoding;
187                         con.setRequestProperty(BASIC_AUTHENTICATION_HEADER, encodingStr);
188
189                         con.setRequestProperty("sessionMap", sessionTimeoutMap);
190                         con.setDoInput(true);
191                         con.setDoOutput(true);
192                         con.getOutputStream().write(sessionTimeoutMap.getBytes());
193                         con.getOutputStream().flush();
194                         con.getOutputStream().close();
195
196                         responseCode = con.getResponseCode();
197                         logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
198                 } catch (UrlAccessRestrictedException e) {
199                         responseCode = HttpServletResponse.SC_UNAUTHORIZED;
200                         String message = String.format(
201                                         "SessionCommunication.pingSession received an un-authorized exception. AppName: %s", appName);
202                         logger.error(EELFLoggerDelegate.errorLogger, message);
203                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
204                 } catch (Exception e) {
205                         responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
206                         String message = String.format(
207                                         "SessionCommunication.pingSession encountered an Exception. AppName: %s, Details: %s", appName, e.toString());
208                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e);
209                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
210                 } finally {
211                         EcompPortalUtils.setExternalAppResponseCode(responseCode);
212                 }
213
214                 return true;
215         }
216
217         @EPAuditLog
218         public Boolean timeoutSession(OnboardingApp app, String portalJSessionId) throws Exception {
219                 String appName = "Unknwon";
220                 int responseCode = 0;
221                 if (app != null && app.getAppName() != null && app.getAppName() != "") {
222                         try {
223                                 appName = app.getAppName();
224                                 String url = app.getRestUrl() + "/timeoutSession" + "?portalJSessionId=" + portalJSessionId;
225
226                                 String encriptedPwdDB = app.getAppBasicAuthPassword();
227                                 String appUserName = app.getAppBasicAuthUsername();
228                                 // String decreptedPwd = CipherUtil.decrypt(encriptedPwdDB,
229                                 // SystemProperties.getProperty(SystemProperties.Decryption_Key));
230
231                                 setLocalMDCContext(app, "/timeoutSession", url);
232
233                                 URL obj = new URL(url);
234                                 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
235
236                                 // optional default is GET
237                                 con.setRequestMethod("POST");
238                                 con.setConnectTimeout(3000);
239                                 con.setReadTimeout(15000);
240
241                                 Map<String,String> headers = getHeaders(app);
242                                 appUserName =headers.get("username");
243                                 encriptedPwdDB = headers.get("password");
244                                 
245                                 con.setRequestProperty("username", appUserName);
246                                 con.setRequestProperty("password", encriptedPwdDB);
247                                 
248                                 String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + encriptedPwdDB).getBytes());
249                                 String encodingStr = "Basic " + encoding;
250                                 con.setRequestProperty(BASIC_AUTHENTICATION_HEADER, encodingStr);
251                                 
252                                 con.setDoInput(true);
253                                 con.setDoOutput(true);
254                                 con.getOutputStream().flush();
255                                 con.getOutputStream().close();
256
257                                 responseCode = con.getResponseCode();
258                                 logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
259                         } catch (UrlAccessRestrictedException e) {
260                                 responseCode = HttpServletResponse.SC_UNAUTHORIZED;
261                                 String message = String.format(
262                                                 "SessionCommunication.timeoutSession received an un-authorized exception. AppName: %s",
263                                                 appName);
264                                 logger.error(EELFLoggerDelegate.errorLogger, message);
265                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
266                         } catch (Exception e) {
267                                 responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
268                                 String message = String.format(
269                                                 "SessionCommunication.timeoutSession encountered an Exception. AppName: %s, Details: %s", 
270                                                 appName, e.toString());
271                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e);
272                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
273                         } finally {
274                                 EcompPortalUtils.setExternalAppResponseCode(responseCode);
275                         }
276                 } else {
277                         logger.error(EELFLoggerDelegate.errorLogger, "SessionCommunication pingSession: app is null");
278                 }
279                 return true;
280         }
281
282         @EPMetricsLog
283         private void setLocalMDCContext(OnboardingApp app, String restPath, String url) {
284                 setRequestId();
285                 MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTP);
286                 if (url != null && url.contains("https")) {
287                         MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTPS);
288                 }
289                 MDC.put(EPCommonSystemProperties.FULL_URL, url);
290                 MDC.put(EPCommonSystemProperties.TARGET_ENTITY, app.getMyLoginsAppName());
291                 MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, restPath);
292         }
293
294         /**
295          * Generates request id, service name fields and loads them into MDC, as these
296          * values could be empty as these session timeout requests are generated at
297          * scheduled intervals using quartz scheduler.
298          */
299         @EPMetricsLog
300         public void setRequestId() {
301                 String requestId = MDC.get(Configuration.MDC_KEY_REQUEST_ID);
302                 if (StringUtils.isEmpty(requestId)) {
303                         MDC.put(Configuration.MDC_KEY_REQUEST_ID, UUID.randomUUID().toString());
304                 }
305
306                 MDC.put(Configuration.MDC_SERVICE_NAME, "/quartz/keepSessionAlive");
307                 MDC.put(EPCommonSystemProperties.PARTNER_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
308         }
309
310         /**
311          * Remove the values from MDC as these requests are executed at regular
312          * intervals based on quartz rather incoming REST API requests.
313          * 
314          * @param bAll
315          */
316         @EPMetricsLog
317         public void clear(Boolean bAll) {
318                 MDC.remove(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
319                 if (bAll) {
320                         MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
321                         MDC.remove(Configuration.MDC_SERVICE_NAME);
322                         MDC.remove(EPCommonSystemProperties.PARTNER_NAME);
323                 }
324         }
325         
326         public Map<String,String> getHeaders(OnboardingApp app)
327         {
328                 String encriptedPwdDB = "";
329                 String appUserName = "";
330
331                 
332                  Map<String,String> headersMap = new HashMap<>();
333                 EPApp externalApp = null;
334
335                 if(app.getAppBasicAuthPassword().isEmpty() || app.getAppBasicAuthPassword()==null){
336                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the externalApp get app password contains null : {}");
337                         externalApp = appsCacheService.getApp(1L);
338                         logger.debug(EELFLoggerDelegate.debugLogger, "external App Information : {}",externalApp);
339
340                         String mechidUsername=externalApp.getAppBasicAuthUsername();
341                         logger.debug(EELFLoggerDelegate.debugLogger, "external App mechidUsername Information : {}",mechidUsername);
342
343                         String password=externalApp.getAppBasicAuthPassword();
344                         String decreptedexternalAppPwd = StringUtils.EMPTY;
345                         try {
346                                 decreptedexternalAppPwd = CipherUtil.decryptPKC(password,
347                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
348                         } catch (CipherUtilException e) {
349                                 logger.error(EELFLoggerDelegate.errorLogger, "failed to decreptedexternalAppPwd when external app pwd is null", e);
350                         }
351                         
352                         appUserName =mechidUsername;
353                         encriptedPwdDB = decreptedexternalAppPwd;
354                 
355                 }else{
356                         appUserName = app.getAppBasicAuthUsername();
357                         encriptedPwdDB = app.getAppBasicAuthPassword();
358                 }
359                 
360                 headersMap.put("username", appUserName);
361                 headersMap.put("password", encriptedPwdDB);
362                 return headersMap;
363         }
364 }