fixed code smells
[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
66
67 public final class MusicCookieCsrfTokenRepository implements CsrfTokenRepository {
68         static final String CSRF_COOKIE_NAME = "XSRF-TOKEN";
69         static final String CSRF_HEADER_NAME = "X-XSRF-TOKEN";
70         static final String CSRF_PARAMETER_NAME = "_csrf";
71         static final String EP_SERVICE = "EPService";
72         CookieCsrfTokenRepository cookieRepo = null;
73         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicCookieCsrfTokenRepository.class);
74         public MusicCookieCsrfTokenRepository() {
75         }
76         
77         public MusicCookieCsrfTokenRepository(CookieCsrfTokenRepository _cookieRepo) {
78                 this();
79                 cookieRepo = _cookieRepo;
80         }
81
82         @Override
83         public CsrfToken generateToken(HttpServletRequest request) {
84                 return cookieRepo.generateToken(request) ;
85         }
86
87         @Override
88         public void saveToken(CsrfToken token, HttpServletRequest request,
89                         HttpServletResponse response) {
90                 logger.debug(EELFLoggerDelegate.debugLogger, "initialize save csrf token ...");
91                 cookieRepo.saveToken(token, request, response);
92         }
93
94         @Override
95         public CsrfToken loadToken(HttpServletRequest request) {
96                 logger.debug(EELFLoggerDelegate.debugLogger, "initialize load csrf token ...");
97                 CsrfToken cookieRepoToken = cookieRepo.loadToken(request);
98                 if(cookieRepoToken==null){ // if cookieRepo does not has the token, check the cassandra for the values stored by other tomcats
99                         try { // todo this part of the code needs to be replaced with out depending on EPService cookie
100                                 String sessionId = getSessionIdFromCookie(request);
101                                 if(sessionId == null) 
102                                         return null;
103                                 String token = MusicService.getAttribute(CSRF_COOKIE_NAME, sessionId);
104                                 if (token==null || !StringUtils.hasLength(token)) 
105                                         return null;
106                                 cookieRepoToken = new DefaultCsrfToken(CSRF_HEADER_NAME, CSRF_PARAMETER_NAME , token); 
107                         } catch (Exception e) {
108                                 logger.error(EELFLoggerDelegate.errorLogger, "Error while calling csrf loadToken" , e);
109                         }
110                 }
111                 return cookieRepoToken;
112         }
113
114         /**
115          * Factory method to conveniently create an instance that has
116          * {@link #setCookieHttpOnly(boolean)} set to false.
117          *
118          * @return an instance of CookieCsrfTokenRepository with
119          * {@link #setCookieHttpOnly(boolean)} set to false
120          */
121         public static MusicCookieCsrfTokenRepository withHttpOnlyFalse() {
122                 CookieCsrfTokenRepository result = new CookieCsrfTokenRepository();
123                 result.setCookieHttpOnly(false);
124                 return new MusicCookieCsrfTokenRepository(result);
125         }
126         
127         private String getSessionIdFromCookie (HttpServletRequest request) throws JsonParseException, JsonMappingException, UnsupportedEncodingException, IOException, CipherUtilException{
128                 Cookie cookies[] = request.getCookies();
129                 if (cookies != null) {
130                         for (Cookie cookie : cookies) {
131                                 if (EP_SERVICE.equals(cookie.getName())) {
132                                         ObjectMapper mapper = new ObjectMapper();
133                                         Map<String,String> epServiceCookieValueMap = mapper.readValue(URLDecoder.decode(cookie.getValue(), "UTF-8"),HashMap.class);
134                                         String sessionId = null;
135                                         if(epServiceCookieValueMap!=null) {
136                                                 String multifactorauthfrontendurl = EPCommonSystemProperties.getProperty(EPCommonSystemProperties.MULTI_FACTOR_AUTH_FRONTEND_URL);
137                                                 String encryptedJSessionId = epServiceCookieValueMap.get(multifactorauthfrontendurl);
138                                                 if(encryptedJSessionId != null) {
139                                                         sessionId = CipherUtil.decryptPKC(encryptedJSessionId);
140                                                 }
141                                         }
142                                         return sessionId;
143                                 }
144                         }
145                 }
146                 return null;
147         }
148 }