Changes made to upgrade pom version
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / utils / MusicCookieCsrfTokenRepository.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 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
39 package org.onap.portalapp.portal.utils;
40
41 import javax.servlet.http.Cookie;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.servlet.http.HttpServletResponse;
44
45 import org.onap.music.eelf.logging.EELFLoggerDelegate;
46 import org.onap.portalapp.music.service.MusicService;
47 import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
48 import org.springframework.security.web.csrf.CsrfToken;
49 import org.springframework.security.web.csrf.CsrfTokenRepository;
50 import org.springframework.security.web.csrf.DefaultCsrfToken;
51 import org.springframework.util.StringUtils;
52
53 import com.fasterxml.jackson.core.JsonParseException;
54 import com.fasterxml.jackson.databind.JsonMappingException;
55 import com.fasterxml.jackson.databind.ObjectMapper;
56
57 import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
58 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
59
60 import java.io.IOException;
61 import java.io.UnsupportedEncodingException;
62 import java.net.URLDecoder;
63 import java.util.HashMap;
64 import java.util.Map;
65 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
66
67
68 public final class MusicCookieCsrfTokenRepository implements CsrfTokenRepository {
69         static final String CSRF_COOKIE_NAME = "XSRF-TOKEN";
70         static final String CSRF_HEADER_NAME = "X-XSRF-TOKEN";
71         static final String CSRF_PARAMETER_NAME = "_csrf";
72         static final String EP_SERVICE = "EPService";
73         CookieCsrfTokenRepository cookieRepo = null;
74         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicCookieCsrfTokenRepository.class);
75         public MusicCookieCsrfTokenRepository() {
76         }
77         
78         public MusicCookieCsrfTokenRepository(CookieCsrfTokenRepository _cookieRepo) {
79                 this();
80                 cookieRepo = _cookieRepo;
81         }
82
83         @Override
84         public CsrfToken generateToken(HttpServletRequest request) {
85                 return cookieRepo.generateToken(request) ;
86         }
87
88         @Override
89         public void saveToken(CsrfToken token, HttpServletRequest request,
90                         HttpServletResponse response) {
91                 logger.debug(EELFLoggerDelegate.debugLogger, "initialize save csrf token ...");
92                 cookieRepo.saveToken(token, request, response);
93         }
94
95         @Override
96         public CsrfToken loadToken(HttpServletRequest request) {
97                 logger.debug(EELFLoggerDelegate.debugLogger, "initialize load csrf token ...");
98                 CsrfToken cookieRepoToken = cookieRepo.loadToken(request);
99                 if(cookieRepoToken==null){ // if cookieRepo does not has the token, check the cassandra for the values stored by other tomcats
100                         try { // todo this part of the code needs to be replaced with out depending on EPService cookie
101                                 String sessionId = getSessionIdFromCookie(request);
102                                 if(sessionId == null) 
103                                         return null;
104                                 String token = MusicService.getAttribute(CSRF_COOKIE_NAME, sessionId);
105                                 if (token==null || !StringUtils.hasLength(token)) 
106                                         return null;
107                                 cookieRepoToken = new DefaultCsrfToken(CSRF_HEADER_NAME, CSRF_PARAMETER_NAME , token); 
108                         } catch (Exception e) {
109                                 logger.error(EELFLoggerDelegate.errorLogger, "Error while calling csrf loadToken" , e);
110                         }
111                 }
112                 return cookieRepoToken;
113         }
114
115         /**
116          * Factory method to conveniently create an instance that has
117          * {@link #setCookieHttpOnly(boolean)} set to false.
118          *
119          * @return an instance of CookieCsrfTokenRepository with
120          * {@link #setCookieHttpOnly(boolean)} set to false
121          */
122         public static MusicCookieCsrfTokenRepository withHttpOnlyFalse() {
123                 CookieCsrfTokenRepository result = new CookieCsrfTokenRepository();
124                 result.setCookieHttpOnly(false);
125                 return new MusicCookieCsrfTokenRepository(result);
126         }
127         
128         private String getSessionIdFromCookie (HttpServletRequest request) throws JsonParseException, JsonMappingException, UnsupportedEncodingException, IOException, CipherUtilException{
129                 Cookie cookies[] = request.getCookies();
130                 if (cookies != null) {
131                         for (Cookie cookie : cookies) {
132                                 if (EP_SERVICE.equals(cookie.getName())) {
133                                         ObjectMapper mapper = new ObjectMapper();
134                                         Map<String,String> epServiceCookieValueMap = mapper.readValue(URLDecoder.decode(cookie.getValue(), "UTF-8"),HashMap.class);
135                                         String sessionId = null;
136                                         if(epServiceCookieValueMap!=null) {
137                                                 String multifactorauthfrontendurl = EPCommonSystemProperties.getProperty(EPCommonSystemProperties.MULTI_FACTOR_AUTH_FRONTEND_URL);
138                                                 String encryptedJSessionId = epServiceCookieValueMap.get(multifactorauthfrontendurl);
139                                                 if(encryptedJSessionId != null) {
140                                                         sessionId = CipherUtil.decryptPKC(encryptedJSessionId);
141                                                 }
142                                         }
143                                         return sessionId;
144                                 }
145                         }
146                 }
147                 return null;
148         }
149 }