Removed edit attribute code
[aai/sparky-be.git] / sparkybe-onap-service / src / main / java / org / onap / aai / sparky / security / filter / LoginFilter.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.sparky.security.filter;
22
23 import java.io.IOException;
24
25 import javax.servlet.Filter;
26 import javax.servlet.FilterChain;
27 import javax.servlet.FilterConfig;
28 import javax.servlet.ServletException;
29 import javax.servlet.ServletRequest;
30 import javax.servlet.ServletResponse;
31 import javax.servlet.http.Cookie;
32 import javax.servlet.http.HttpServletRequest;
33 import javax.servlet.http.HttpServletResponse;
34 import javax.servlet.http.HttpSession;
35 import javax.ws.rs.core.HttpHeaders;
36
37 import org.onap.aai.cl.api.Logger;
38 import org.onap.aai.cl.eelf.LoggerFactory;
39 import org.onap.aai.sparky.logging.AaiUiMsgs;
40 import org.onap.aai.sparky.security.EcompSso;
41 import org.onap.aai.sparky.security.portal.config.PortalAuthenticationConfig;
42 import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
43 import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
44 import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
45 import org.openecomp.portalsdk.core.onboarding.util.SSOUtil;
46
47 /**
48  * This filter checks every request for proper ECOMP Portal single sign on initialization. The
49  * possible paths and actions:
50  * <OL>
51  * <LI>User starts at an app page via a bookmark. No ECOMP portal cookie is set. Redirect there to
52  * get one; then continue as below.
53  * <LI>User starts at ECOMP Portal and goes to app. Alternately, the user's session times out and
54  * the user hits refresh. The ECOMP Portal cookie is set, but there is no valid session. Create one
55  * and publish info.
56  * <LI>User has valid ECOMP Portal cookie and session. Reset the max idle in that session.
57  * </OL>
58  * <P>
59  * Notes:
60  * <UL>
61  * <LI>Portal Session should be up prior to App Session</LI>
62  * <LI>If App Session Expires or if EPService cookie is unavailable, we need to redirect to Portal.
63  * <LI>Method {@link #initiateSessionMgtHandler(HttpServletRequest)} should be called for Session
64  * management when the initial session is created
65  * <LI>While redirecting, the cookie "redirectUrl" should also be set so that Portal knows where to
66  * forward the request to once the Portal Session is created and EPService cookie is set.
67  * <LI>Method {@link #resetSessionMaxIdleTimeOut(HttpServletRequest)} should be called for every
68  * request to reset the MaxInactiveInterval to the right value.
69  * </UL>
70  * <P>
71  * This filter incorporates most features of the SDK application's SessionTimeoutInterceptor and
72  * SingleSignOnController classes
73  */
74 public class LoginFilter implements Filter {
75
76   private static final Logger LOG = LoggerFactory.getInstance().getLogger(LoginFilter.class);
77
78   @Override
79   public void init(FilterConfig filterConfig) throws ServletException {
80     // Validate that app has provided useful portal properties
81     if (PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL) == null) {
82       throw new ServletException("Failed to find URL in portal.properties");
83     }
84
85     PortalAuthenticationConfig appProperties;
86     try {
87       appProperties = PortalAuthenticationConfig.getInstance();
88     } catch (Exception ex) {
89       throw new ServletException("Failed to get properties", ex);
90     }
91
92     String restUser = appProperties.getUsername();
93     String restPassword = appProperties.getPassword();
94     if (restUser == null || restPassword == null) {
95       throw new ServletException("Failed to find user and/or password from properties");
96     }
97   }
98
99   @Override
100   public void destroy() {
101     // No resources to release
102   }
103
104   /*
105    * (non-Javadoc)
106    *
107    * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
108    * javax.servlet.FilterChain)
109    */
110   @Override
111   public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
112       throws ServletException, IOException {
113     HttpServletRequest request = (HttpServletRequest) req;
114     HttpServletResponse response = (HttpServletResponse) res;
115
116     // Choose authentication appropriate for the request.
117     final String restApiURI = request.getContextPath() + PortalApiConstants.API_PREFIX;
118     if (request.getRequestURI().startsWith(restApiURI)) {
119       // REST servlet checks credentials
120       LOG.debug(AaiUiMsgs.LOGIN_FILTER_DEBUG, "doFilter: delegating auth to REST servlet for request " + request.getRequestURI());
121       chain.doFilter(request, response);
122     } else {
123       // All other requests require ECOMP Portal authentication
124       if (EcompSso.validateEcompSso(request) == null) {
125         String redirectURL, logMessage;
126
127         // Redirect to Portal UI
128         redirectURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
129         logMessage = "Unauthorized login attempt.";
130         
131         LOG.debug(AaiUiMsgs.LOGIN_FILTER_DEBUG,
132             logMessage + 
133             " | Remote IP: " + request.getRemoteAddr() + 
134             " | User agent: " + request.getHeader(HttpHeaders.USER_AGENT) + 
135             " | Request URL: " + request.getRequestURL() +
136             " | Redirecting to: " + redirectURL); 
137         
138         response.sendRedirect(redirectURL);
139       } else {
140         HttpSession session = request.getSession(false);
141         if (session == null) {
142           // New session
143           session = request.getSession(true);
144           LOG.debug(AaiUiMsgs.LOGIN_FILTER_DEBUG, "doFilter: created new session " + session.getId());
145           initiateSessionMgtHandler(request);
146         } else {
147           // Existing session
148           LOG.debug(AaiUiMsgs.LOGIN_FILTER_DEBUG, "doFilter: resetting idle in existing session " + session.getId());
149           resetSessionMaxIdleTimeOut(request);
150         }
151         // Pass request back down the filter chain
152         chain.doFilter(request, response);
153       }
154     }
155   }
156
157   /**
158    * Publishes information about the session.
159    *
160    * @param request
161    */
162   private void initiateSessionMgtHandler(HttpServletRequest request) {
163     String portalJSessionId = getPortalJSessionId(request);
164     String jSessionId = getJessionId(request);
165     storeMaxInactiveTime(request);
166     PortalTimeoutHandler.sessionCreated(portalJSessionId, jSessionId, request.getSession(false));
167   }
168
169   /**
170    * Gets the ECOMP Portal service cookie value.
171    *
172    * @param request
173    * @return Cookie value, or null if not found.
174    */
175   private String getPortalJSessionId(HttpServletRequest request) {
176     Cookie ep = EcompSso.getCookie(request, EcompSso.EP_SERVICE);
177     return ep == null ? null : ep.getValue();
178   }
179
180   /**
181    * Gets the container session ID.
182    *
183    * @param request
184    * @return Session ID, or null if no session.
185    */
186   private String getJessionId(HttpServletRequest request) {
187     HttpSession session = request.getSession();
188     return session == null ? null : session.getId();
189   }
190
191   /**
192    * Sets the global session's max idle time to the session's max inactive interval.
193    *
194    * @param request
195    */
196   private void storeMaxInactiveTime(HttpServletRequest request) {
197     HttpSession session = request.getSession(false);
198     if (session != null
199         && session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME) == null) {
200       session.setAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME,
201           session.getMaxInactiveInterval());
202     }
203   }
204
205   /**
206    * Sets the session's max inactive interval.
207    *
208    * @param request
209    */
210   private void resetSessionMaxIdleTimeOut(HttpServletRequest request) {
211     try {
212       HttpSession session = request.getSession(false);
213       if (session != null) {
214         final Object maxIdleAttribute = session
215             .getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME);
216         if (maxIdleAttribute != null) {
217           session.setMaxInactiveInterval(Integer.parseInt(maxIdleAttribute.toString()));
218         }
219       }
220     } catch (Exception e) {
221       LOG.info(AaiUiMsgs.LOGIN_FILTER_INFO, "resetSessionMaxIdleTimeOut: failed to set session max inactive interval - " + e.getLocalizedMessage());
222     }
223   }
224
225 }