login and Certman AAF Integration changes
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / utils / EcompPortalUtils.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017-2018 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.utils;
39
40 import java.io.IOException;
41 import java.net.InetAddress;
42 import java.net.UnknownHostException;
43 import java.nio.charset.Charset;
44 import java.text.SimpleDateFormat;
45 import java.util.ArrayList;
46 import java.util.Base64;
47 import java.util.Date;
48 import java.util.List;
49
50 import javax.servlet.http.HttpServletResponse;
51 import javax.xml.bind.DatatypeConverter;
52
53 import org.apache.commons.lang.StringUtils;
54 import org.hibernate.Session;
55 import org.hibernate.Transaction;
56 import org.onap.portalapp.portal.domain.EPUser;
57 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
58 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
59 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
60 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
61 import org.onap.portalsdk.core.util.SystemProperties;
62 import org.slf4j.MDC;
63 import org.springframework.http.HttpHeaders;
64 import org.springframework.http.MediaType;
65
66 import com.fasterxml.jackson.core.JsonProcessingException;
67 import com.fasterxml.jackson.databind.ObjectMapper;
68
69 public class EcompPortalUtils {
70
71         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EcompPortalUtils.class);
72         
73         private static final String FUNCTION_PIPE = "|";
74         
75         // TODO: GLOBAL_LOGIN_URL is the same as in SessionTimeoutInterceptor.
76         // It should be defined in SystemProperties.
77         private static final String GLOBAL_LOGIN_URL = "global-login-url";
78         
79         // It is a regular expression used for while creating a External Central Auth Role 
80         public static final String EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS = "([^A-Z^a-z^0-9^\\.^%^(^)^=^:])";
81         
82         /**
83          * @param orgUserId
84          *            User ID to validate
85          * @return true if orgUserId is not empty and contains only alphanumeric, false
86          *         otherwise
87          */
88         public static boolean legitimateUserId(String orgUserId) {
89                 return orgUserId.matches("^[a-zA-Z0-9]+$");
90         }
91
92         /**
93          * Splits the string into a list of tokens using the specified regular
94          * expression
95          * 
96          * @param source
97          *            String to split
98          * @param regex
99          *            tokens
100          * @return List of tokens split from the source
101          */
102         public static List<String> parsingByRegularExpression(String source, String regex) {
103                 List<String> tokens = new ArrayList<String>();
104                 if (source != null && source.length() > 0) {
105                         String[] parsed = source.split(regex);
106                         for (String token : parsed) {
107                                 if (token.length() > 0) {
108                                         tokens.add(token);
109                                 }
110                         }
111                 }
112                 return tokens;
113         }
114
115         /**
116          * Builds a JSON object with error code and message information.
117          * 
118          * @param errorCode
119          *            error code
120          * @param errorMessage
121          *            message
122          * @return JSON object as a String
123          */
124         public static String jsonErrorMessageResponse(int errorCode, String errorMessage) {
125                 return "{\"error\":{\"code\":" + errorCode + "," + "\"message\":\"" + errorMessage + "\"}}";
126         }
127
128         /**
129          * Builds a JSON object with the specified message
130          * 
131          * @param message
132          *            Message to embed
133          * @return JSON object as a String
134          */
135         public static String jsonMessageResponse(String message) {
136                 return String.format("{\"message\":\"%s\"}", message);
137         }
138
139         /**
140          * Serializes the specified object as JSON and writes the result to the debug
141          * log. If serialization fails, logs a message to the error logger.
142          * 
143          * @param logger
144          *            Logger for the class where the object was built; the logger
145          *            carries the class name.
146          * @param source
147          *            First portion of the log message
148          * @param msg
149          *            Second portion of the log message
150          * @param obj
151          *            Object to serialize as JSON
152          */
153         public static void logAndSerializeObject(EELFLoggerDelegate logger, String source, String msg, Object obj) {
154                 try {
155                         String objectAsJson = new ObjectMapper().writeValueAsString(obj);
156                         logger.debug(EELFLoggerDelegate.debugLogger,
157                                         String.format("source= [%s]; %s [%s];", source, msg, objectAsJson));
158                 } catch (JsonProcessingException e) {
159                         logger.warn(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed to serialize", e);
160                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
161                 } catch (Exception e) {
162                         logger.error(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed", e);
163                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
164                 }
165         }
166
167         /**
168          * Serializes the specified object as JSON and writes the result to the debug
169          * log. If serialization fails, logs a message to the error logger.
170          * 
171          * @param source
172          *            First portion of the log message
173          * @param msg
174          *            Second portion of the log message
175          * @param obj
176          *            Object to serialize as JSON
177          */
178         public static void logAndSerializeObject(String source, String msg, Object obj) {
179                 logAndSerializeObject(logger, source, msg, obj);
180         }
181
182         public static void rollbackTransaction(Transaction transaction, String errorMessage) {
183                 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
184                 try {
185                         if (transaction != null) {
186                                 transaction.rollback();
187                         }
188                 } catch (Exception e) {
189                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
190                         logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing a rollback transaction",
191                                         e);
192                 }
193         }
194
195         public static void closeLocalSession(Session localSession, String errorMessage) {
196                 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
197                 try {
198                         if (localSession != null) {
199                                 localSession.close();
200                         }
201                 } catch (Exception e) {
202                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
203                         logger.error(EELFLoggerDelegate.errorLogger, errorMessage + ", closeLocalSession exception", e);
204                 }
205         }
206
207         /**
208          * Set response status to Unauthorized if user == null and to Forbidden in all
209          * (!) other cases. Logging is not performed if invocator == null
210          * 
211          * @param user
212          *            User object
213          * @param response
214          *            HttpServletResponse
215          * @param invocator
216          *            may be null
217          */
218         public static void setBadPermissions(EPUser user, HttpServletResponse response, String invocator) {
219                 if (user == null) {
220                         String loginUrl = SystemProperties.getProperty(EPCommonSystemProperties.LOGIN_URL_NO_RET_VAL);
221                         response.setHeader(GLOBAL_LOGIN_URL, loginUrl);
222                         response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
223                         MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_UNAUTHORIZED));
224                 } else {
225                         response.setStatus(HttpServletResponse.SC_FORBIDDEN);
226                         MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_FORBIDDEN));
227                 }
228                 if (invocator != null) {
229                         logger.warn(EELFLoggerDelegate.errorLogger,
230                                         invocator + ", permissions problem, response status = " + response.getStatus());
231                 }
232         }
233
234         public static int getExternalAppResponseCode() {
235                 String responseCode = MDC.get(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
236                 int responseCodeInt = 0;
237                 try {
238                         if (responseCode != null && responseCode != "") {
239                                 responseCodeInt = Integer.valueOf(responseCode);
240                         }
241                 } catch (Exception e) {
242                         logger.error(EELFLoggerDelegate.errorLogger, "getExternalAppResponseCode failed", e);
243                 }
244                 return responseCodeInt;
245         }
246
247         // This method might be just for testing purposes.
248         public static void setExternalAppResponseCode(int responseCode) {
249                 try {
250                         String code = String.valueOf(responseCode);
251                         MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,code );
252                         code=StringUtils.EMPTY;
253                 } catch (Exception e) {
254                         logger.error(EELFLoggerDelegate.errorLogger, "setExternalAppResponseCode failed", e);
255                 }
256         }
257
258         public static String getHTTPStatusString(int httpStatusCode) {
259                 String httpStatusString = "unknown_error";
260                 try {
261                         httpStatusString = org.springframework.http.HttpStatus.valueOf(httpStatusCode).name();
262                         if (httpStatusString != null) {
263                                 httpStatusString = httpStatusString.toLowerCase();
264                         }
265                 } catch (Exception e) {
266                         logger.error(EELFLoggerDelegate.errorLogger, "getHTTPStatusString failed", e);
267                 }
268                 return httpStatusString;
269         }
270
271         public static String getFEErrorString(Boolean internal, int responseCode) {
272                 // Return a String like the following:
273                 // "Internal Onap Error: 500 internal_server_error" or
274                 // "External App Error: 404 not_found"
275                 // TODO: create our own Ecomp error codes, starting with 1000 and up.
276                 String internalExternalString = internal ? "Ecomp Error: " : "App Error: ";
277                 String httpStatusString = "unknown_error";
278                 try {
279                         if (responseCode < 1000) {
280                                 httpStatusString = getHTTPStatusString(responseCode);
281                         }
282                 } catch (Exception e) {
283                         logger.error(EELFLoggerDelegate.errorLogger, "getFEErrorString failed", e);
284                 }
285                 String responseString = internalExternalString + responseCode + " " + httpStatusString;
286                 return responseString;
287         }
288
289         public static boolean isProductionBuild() {
290                 boolean productionBuild = true;
291                 String epVersion = EcompVersion.buildNumber;
292                 if (epVersion != null) {
293                         int buildNum = epVersion.lastIndexOf('.');
294                         if (buildNum > 0) {
295                                 int buildNumber = Integer.parseInt(epVersion.substring(buildNum + 1));
296                                 if (buildNumber < 3000) // Production versions are 3000+, (ie
297                                                                                 // 1.0.3003)
298                                 {
299                                         productionBuild = false;
300                                 }
301                         }
302                 }
303                 return productionBuild;
304         }
305
306         public static String getMyIpAdddress() {
307                 InetAddress ip;
308                 String localIp;
309                 try {
310                         ip = InetAddress.getLocalHost();
311                         localIp = ip.getHostAddress();
312                 } catch (UnknownHostException e) {
313                         localIp = "unknown";
314                         logger.error(EELFLoggerDelegate.errorLogger, "getMyIpAdddress failed ", e);
315                 }
316                 return localIp;
317         }
318
319         public static String getMyHostName() {
320                 InetAddress ip;
321                 String hostName;
322                 try {
323                         ip = InetAddress.getLocalHost();
324                         hostName = ip.getHostName();
325                 } catch (UnknownHostException e) {
326                         hostName = "unknown";
327                         logger.error(EELFLoggerDelegate.errorLogger, "getMyHostName failed", e);
328                 }
329                 return hostName;
330         }
331
332         /**
333          * Returns a default property if the expected one is not available
334          * 
335          * @param property
336          *            Key
337          * @param defaultValue
338          *            default Value
339          * @return Default value if property is not defined or yields the empty string;
340          *         else the property value.
341          */
342         public static String getPropertyOrDefault(String property, String defaultValue) {
343                 if (!SystemProperties.containsProperty(property))
344                         return defaultValue;
345                 String value = SystemProperties.getProperty(property);
346                 if (value == null || "".equals(value))
347                         return defaultValue;
348                 return value;
349         }
350
351         /**
352          * Calculates the time duration of a function call for logging purpose. It
353          * stores the result by using "MDC.put(SystemProperties.MDC_TIMER,
354          * timeDifference);" It is important to call
355          * "MDC.remove(SystemProperties.MDC_TIMER);" after this method call to clean up
356          * the record in MDC
357          *
358          * @param beginDateTime
359          *            the given begin time for the call
360          * @param endDateTime
361          *            the given end time for the call
362          * 
363          */
364         public static void calculateDateTimeDifferenceForLog(String beginDateTime, String endDateTime) {
365                 if (beginDateTime != null && endDateTime != null) {
366                         try {
367                                 SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
368
369                                 Date beginDate = ecompLogDateFormat.parse(beginDateTime);
370                                 Date endDate = ecompLogDateFormat.parse(endDateTime);
371                                 String timeDifference = String.format("%d", endDate.getTime() - beginDate.getTime());
372                                 MDC.put(SystemProperties.MDC_TIMER, timeDifference);
373                         } catch (Exception e) {
374                                 logger.error(EELFLoggerDelegate.errorLogger, "calculateDateTimeDifferenceForLog failed", e);
375                         }
376                 }
377         }
378
379         /**
380          * Answers the protocol to use.
381          * 
382          * @return Protocol name from property file; defaults to https.
383          */
384         public static String widgetMsProtocol() {
385                 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_PROTOCOL, "https");
386         }
387
388         /**
389          * Answers the host to use.
390          * 
391          * @return Host name from property file; defaults to localhost.
392          */
393         public static String localOrDockerHost() {
394                 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_HOSTNAME, "localhost");
395         }
396
397         /**
398          * It returns headers where username and password of external central auth is
399          * encoded to base64
400          * 
401          * @return header which contains external central auth username and password
402          *         base64 encoded
403          * @throws Exception
404          *             if unable to decrypt the password
405          */
406         public static HttpHeaders base64encodeKeyForAAFBasicAuth() throws Exception {
407                 String userName = "";
408                 String decryptedPass = "";
409                 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME)
410                                 && EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD)) {
411                         decryptedPass = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD);
412                         userName = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
413                 }
414                 String decPass = decrypted(decryptedPass);
415                 String usernamePass = userName + ":" + decPass;
416                 String encToBase64 = String.valueOf((DatatypeConverter.printBase64Binary(usernamePass.getBytes())));
417                 HttpHeaders headers = new HttpHeaders();
418                 headers.add("Authorization", "Basic " + encToBase64);
419                 headers.setContentType(MediaType.APPLICATION_JSON);
420                 return headers;
421         }
422
423         private static String decrypted(String encrypted) throws Exception {
424                 String result = "";
425                 if (encrypted != null && encrypted.length() > 0) {
426                         try {
427                                 result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
428                         } catch (Exception e) {
429                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
430                                 throw e;
431                         }
432                 }
433                 return result;
434         }
435
436         public static String truncateString(String originString, int size){
437                 if(originString.length()>=size){
438                         StringBuilder stringBuilder = new StringBuilder();
439                         stringBuilder.append(originString);
440                         stringBuilder.setLength(size);
441                         stringBuilder.append("...");
442                         return stringBuilder.toString();
443                 }
444                 return originString;
445         }
446         
447         /**
448          * 
449          * If function code value has any pipes it does pipe filter and 
450          * returns value.
451          * 
452          * @param functionCode
453          * @return function instance without pipe
454          */
455         public static String getFunctionCode(String functionCode) {
456                 String finalFunctionCodeVal = "";
457                 if (functionCode.contains(FUNCTION_PIPE)) {
458                         int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
459                         if (count == 2)
460                                 finalFunctionCodeVal = functionCode.substring(
461                                                 functionCode.indexOf(FUNCTION_PIPE) + 1,
462                                                 functionCode.lastIndexOf(FUNCTION_PIPE));
463                         else
464                                 finalFunctionCodeVal = functionCode
465                                                 .substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1);
466                 } else{
467                         finalFunctionCodeVal = functionCode;
468                 }
469                 return finalFunctionCodeVal;
470         }
471         
472         /**
473          * 
474          * If function code value has any pipes it does pipe filter and 
475          * returns value.
476          * 
477          * @param functionCode
478          * @return function Type without pipe
479          */
480         public static String getFunctionType(String functionCode) {
481                 String finalFunctionCodeVal = "";
482                 if (functionCode.contains(FUNCTION_PIPE)) {
483                         int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
484                         if (count == 2){
485                                 String[] getTypeValue = functionCode.split("\\"+FUNCTION_PIPE);         
486                                 finalFunctionCodeVal = getTypeValue[0];
487                         }
488                 } else{
489                         finalFunctionCodeVal = functionCode;
490                 }
491                 return finalFunctionCodeVal;
492         }
493         
494         /**
495          * 
496          * If function code value has any pipes it does pipe filter and 
497          * returns value.
498          * 
499          * @param functionCode
500          * @return function Action without pipe
501          */
502         public static String getFunctionAction(String functionCode) {
503                 String finalFunctionCodeVal = "";
504                 if (functionCode.contains(FUNCTION_PIPE)) {
505                         int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE);
506                         if (count == 2)
507                                 finalFunctionCodeVal = functionCode.substring(
508                                                 functionCode.lastIndexOf(FUNCTION_PIPE)+1);
509                 } else{
510                         finalFunctionCodeVal = functionCode;
511                 }
512                 return finalFunctionCodeVal;
513         }
514         
515         /**
516          * 
517          * It check whether the external auth namespace is matching with current namespace exists in local DB
518          * 
519          * @param permTypeVal
520          * @param appNamespaceVal
521          * @return true or false
522          */
523         public static boolean checkNameSpaceMatching(String permTypeVal, String appNamespaceVal) {
524                 String[] typeNamespace = permTypeVal.split("\\.");
525                 String[] appNamespace = appNamespaceVal.split("\\.");
526                 boolean isNamespaceMatching = true;
527                 if (appNamespace.length <= typeNamespace.length) {
528                         for (int k = 0; k < appNamespace.length; k++) {
529                                 if (!appNamespace[k].equals(typeNamespace[k]))
530                                         isNamespaceMatching = false;
531                         }
532                 } else {
533                         isNamespaceMatching = false;
534                 }
535                 return isNamespaceMatching;
536         }
537         
538         public static boolean checkIfRemoteCentralAccessAllowed() {
539                 boolean result = false;
540                 String rmtCentralAccess = SystemProperties.getProperty(EPCommonSystemProperties.REMOTE_CENTRALISED_SYSTEM_ACCESS);
541                 if(rmtCentralAccess == null) {
542                 logger.error(EELFLoggerDelegate.errorLogger, "Please check in system.properties whether the property exists or not!");
543                         return false;
544                 }else if(new Boolean(rmtCentralAccess)){
545                 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRemoteCentralAccessAllowed: {}",rmtCentralAccess);
546                         result = true;
547                 }
548                 return result;
549         }
550         
551         /**
552          * 
553          * It validates whether given string is JSON or not
554          * 
555          * @param jsonInString
556          * @return true or false
557          */
558           public static boolean isJSONValid(String jsonInString ) {
559                     try {
560                        final ObjectMapper mapper = new ObjectMapper();
561                        mapper.readTree(jsonInString);
562                        return true;
563                     } catch (IOException e) {
564                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse Json!", e);
565                        return false;
566                     }
567                   }
568           /**
569            * 
570            *  It retrieves account information from input String
571            * 
572            * @param authValue
573            * @return Array of Account information
574            * 
575            */
576           public static String[] getUserNamePassword(String authValue) {
577                         String base64Credentials = authValue.substring("Basic".length()).trim();
578                         String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
579                         final String[] values = credentials.split(":", 2);
580                         return values;
581                 }
582 }