PageRenderTime 28ms CodeModel.GetById 17ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/java/com/google/ie/web/filter/AuthenticationFilter.java

http://thoughtsite.googlecode.com/
Java | 151 lines | 82 code | 25 blank | 44 comment | 17 complexity | d8b417ed4f0339f2b643ce515beed212 MD5 | raw file
  1/* Copyright 2010 Google Inc.
  2 * 
  3 * Licensed under the Apache License, Version 2.0 (the "License");
  4 * you may not use this file except in compliance with the License.
  5 * You may obtain a copy of the License at
  6 * 
  7 *      http://www.apache.org/licenses/LICENSE-2.0
  8 * 
  9 * Unless required by applicable law or agreed to in writing, software
 10 * distributed under the License is distributed on an "AS IS" BASIS.
 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 12 * See the License for the specific language governing permissions and
 13 * limitations under the License
 14 */
 15
 16package com.google.ie.web.filter;
 17
 18import com.google.ie.common.constants.IdeaExchangeConstants;
 19
 20import org.apache.log4j.Logger;
 21
 22import java.io.IOException;
 23import java.io.PrintWriter;
 24
 25import javax.servlet.Filter;
 26import javax.servlet.FilterChain;
 27import javax.servlet.FilterConfig;
 28import javax.servlet.ServletException;
 29import javax.servlet.ServletRequest;
 30import javax.servlet.ServletResponse;
 31import javax.servlet.http.Cookie;
 32import javax.servlet.http.HttpServletRequest;
 33import javax.servlet.http.HttpServletResponse;
 34
 35/**
 36 * Temporary class to allow site access based on access code
 37 * 
 38 * @author adahiya
 39 * 
 40 */
 41public class AuthenticationFilter implements Filter {
 42
 43    private static final Logger LOGGER = Logger.getLogger(AuthenticationFilter.class);
 44    private FilterConfig filterConfig;
 45
 46    private String accessCode;
 47    private String exclusionUrls;
 48
 49    private static String FORM = "<HTML> <HEAD>  <TITLE> Access Token </TITLE> </HEAD> <BODY>  <FORM METHOD=\"POST\" ACTION=\"Service_URL\">  <TABLE> <TR>        <TD>Enter Access Code</TD>      <TD>            <INPUT TYPE=\"password\" NAME=\"accessToken\">      </TD>   </TR>   <TR>        <TD></TD>       <TD><INPUT TYPE=\"submit\" value=\"Submit\"></TD>   </TR>   </TABLE>  </FORM> </BODY></HTML>";
 50
 51    public static final String ACCESS_TOKEN = "accessToken";
 52    private static final String EXCLUSION_URL = "exclusionURLs";
 53
 54    /**
 55     * Default constructor.
 56     */
 57    public AuthenticationFilter() {
 58    }
 59
 60    /**
 61     * @see Filter#destroy()
 62     */
 63    public void destroy() {
 64        this.filterConfig = null;
 65    }
 66
 67    /**
 68     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 69     */
 70    public void doFilter(ServletRequest request, ServletResponse response,
 71                    FilterChain chain) throws IOException, ServletException {
 72        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
 73
 74        if (!isAccessCookiePresent(httpServletRequest)) {
 75
 76            String accessCodeFromUSer = httpServletRequest.getParameter(ACCESS_TOKEN);
 77
 78            if (accessCodeFromUSer != null && accessCodeFromUSer.equalsIgnoreCase(this.accessCode)) {
 79                /*
 80                 * Create cookie and set it in response
 81                 */
 82                Cookie cookie = new Cookie(ACCESS_TOKEN, ACCESS_TOKEN);
 83                // Max age of 12 hours
 84                cookie.setMaxAge(43200);
 85                ((HttpServletResponse) response).addCookie(cookie);
 86            } else {
 87                if (!urlForExclusion(httpServletRequest.getRequestURI(), exclusionUrls)) {
 88
 89                    PrintWriter writer = response.getWriter();
 90                    String updatedForm = FORM.replaceAll("Service_URL", httpServletRequest
 91                                    .getRequestURI());
 92                    writer.print(updatedForm);
 93                    LOGGER.debug("Access token not found");
 94                    return;
 95                }
 96            }
 97
 98        }
 99        LOGGER.debug("Access token found");
100        // pass the request along the filter chain
101        chain.doFilter(request, response);
102    }
103
104    private boolean urlForExclusion(String requestURL, String exclusionURLs) {
105        boolean flag = false;
106        if (exclusionURLs != null && exclusionURLs.contains(IdeaExchangeConstants.COMMA)) {
107            String[] urls = exclusionURLs.split(IdeaExchangeConstants.COMMA);
108            for (int i = 0; i < urls.length; i++) {
109                if (requestURL.contains(urls[i])) {
110                    flag = true;
111                    LOGGER.debug("Allowing URL without access tocken due to exclusion policy");
112                    break;
113                }
114            }
115        }
116
117        return flag;
118    }
119
120    /**
121     * Checks if the access token cookie is present with a non empty value
122     * 
123     * @param request
124     * @return true if a valid access token cookie is present in the request,
125     *         else false
126     */
127    private boolean isAccessCookiePresent(HttpServletRequest request) {
128        Cookie[] cookies = request.getCookies();
129        if (cookies != null) {
130            for (int i = 0; i < cookies.length; i++) {
131                Cookie cookie = cookies[i];
132                if (cookie != null && cookie.getName().equals(ACCESS_TOKEN)) {
133                    return true;
134                }
135            }
136        }
137        return false;
138    }
139
140    /**
141     * @see Filter#init(FilterConfig)
142     */
143    public void init(FilterConfig fConfig) throws ServletException {
144        this.filterConfig = fConfig;
145
146        this.accessCode = filterConfig.getInitParameter(ACCESS_TOKEN);
147        this.exclusionUrls = filterConfig.getInitParameter(EXCLUSION_URL);
148    }
149
150}
151