Changes made to upgrade pom version
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / util / CommonSessionCookieUtil.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (c) 2019 Samsung. 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.util;
39
40 import java.io.IOException;
41 import java.io.UnsupportedEncodingException;
42 import java.net.URLDecoder;
43 import java.net.URLEncoder;
44 import java.util.HashMap;
45 import java.util.Map;
46
47 import javax.servlet.http.Cookie;
48 import javax.servlet.http.HttpServletRequest;
49 import javax.servlet.http.HttpServletResponse;
50 import javax.servlet.http.HttpSession;
51
52 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
53 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
54 import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
55 import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
56 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
57 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
58 import org.onap.portalsdk.core.web.support.AppUtils;
59
60 import com.fasterxml.jackson.core.JsonParseException;
61 import com.fasterxml.jackson.core.JsonProcessingException;
62 import com.fasterxml.jackson.databind.JsonMappingException;
63 import com.fasterxml.jackson.databind.ObjectMapper;
64
65 public class CommonSessionCookieUtil {
66         
67         public static final String EP_SERVICE = "EPService";
68         public static Integer cookieMaxAge = -1;
69         public static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CommonSessionCookieUtil.class);
70         public static boolean EP_SERVICE_SECURE = false;
71
72         public static void setUpEPServiceCookie(HttpServletRequest request, HttpServletResponse response) throws CipherUtilException, JsonParseException, JsonMappingException, IOException {
73                 //set up EPService cookie
74                 EP_SERVICE_SECURE = Boolean.parseBoolean(EPCommonSystemProperties.getProperty(EPCommonSystemProperties.EPSERVICE_COOKIE_SECURE));
75                 String multifactorauthfrontendurl = EPCommonSystemProperties.getProperty(EPCommonSystemProperties.MULTI_FACTOR_AUTH_FRONTEND_URL);
76                 String domainName = EPCommonSystemProperties.getProperty(EPCommonSystemProperties.COOKIE_DOMAIN);
77                 Cookie epCookie = getCookie(request, EP_SERVICE);
78                 ObjectMapper objectMapper = new ObjectMapper();
79                 if(epCookie != null) {
80                         //If cookie already exist then add the current env and jsessionId to this
81                         String jSessionId = getJessionId(request);
82                         String jsonValue = URLDecoder.decode(epCookie.getValue(),"UTF-8");
83                         Map<String,String> valueMap = null;
84                         // if the value is encoded
85                         if(jsonValue.startsWith("{")) {
86                                 valueMap = objectMapper.readValue(jsonValue, HashMap.class);
87                         }else {
88                                 valueMap = new HashMap<>();
89                         }
90                         valueMap.put(multifactorauthfrontendurl, CipherUtil.encryptPKC(jSessionId));
91                         saveOrUpdateEPServiceCookie(response, domainName, objectMapper, valueMap);
92                 }else {
93                         //If cookie does not exist create a cookie with current env and jsessionId
94                     String jSessionId = getJessionId(request);
95                     Map<String,String> valueMap = new HashMap<>();
96                         valueMap.put(multifactorauthfrontendurl, CipherUtil.encryptPKC(jSessionId));
97                         saveOrUpdateEPServiceCookie(response, domainName, objectMapper, valueMap);
98                 }
99         }
100
101         private static void saveOrUpdateEPServiceCookie(HttpServletResponse response, String domainName,
102                         ObjectMapper objectMapper, Map<String, String> valueMap)
103                         throws UnsupportedEncodingException, JsonProcessingException {
104                 Cookie cookie1 = new Cookie(EP_SERVICE, URLEncoder.encode(objectMapper.writeValueAsString(valueMap), "UTF-8"));
105                 cookie1.setMaxAge(cookieMaxAge);
106                 cookie1.setDomain(domainName);
107                 cookie1.setPath("/");
108                 cookie1.setSecure(EP_SERVICE_SECURE);
109                 response.addCookie(cookie1);
110         }
111         
112         //Get cookie from request object on the basis of cookie name
113                 private static Cookie getCookie(HttpServletRequest request, String cookieName) {
114                         Cookie[] cookies = request.getCookies();
115                         if (cookies != null)
116                                 for (Cookie cookie : cookies)
117                                         if (cookie.getName().equals(cookieName))
118                                                 return cookie;
119
120                         return null;
121                 }
122                 
123                 protected static void initateSessionMgtHandler(HttpServletRequest request) {
124                         String jSessionId = getJessionId(request);
125                         storeMaxInactiveTime(request);
126                         PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request));
127                 }
128                 
129                 protected static void storeMaxInactiveTime(HttpServletRequest request) {
130                         HttpSession session = AppUtils.getSession(request);
131                         if(session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME) == null)
132                                 session.setAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME,session.getMaxInactiveInterval());
133                 }
134                 
135                 public static void resetSessionMaxIdleTimeOut(HttpServletRequest request) {
136                         try {
137                                 HttpSession session = AppUtils.getSession(request);
138                                 final Object maxIdleAttribute = session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME);
139                                 if(session != null && maxIdleAttribute != null) {
140                                         session.setMaxInactiveInterval(Integer.parseInt(maxIdleAttribute.toString()));
141                                 }
142                         } catch (Exception e) {
143                                 logger.error(EELFLoggerDelegate.errorLogger, "resetSessionMaxIdleTimeOut failed", e);
144                         }
145                         
146                 }
147                 
148                 public static String getJessionId(HttpServletRequest request){
149                         return request.getSession().getId();
150                 }
151 }