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