/* Copyright 2004, 2005 Acegi Technology Pty Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.sf.acegisecurity.ui.rememberme;

import net.sf.acegisecurity.context.SecurityContextHolder;
import net.sf.acegisecurity.ui.InteractiveAuthenticationSuccesEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.InitializingBean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import org.springframework.util.Assert;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Detects if there is no <code>Authentication</code> object in the
 * <code>SecurityContext</code>, and populates it with a remember-me
 * authentication token if a {@link
 * net.sf.acegisecurity.ui.rememberme.RememberMeServices} implementation so
 * requests.
 * 
 * <p>
 * Concrete <code>RememberMeServices</code> implementations will have their
 * {@link
 * net.sf.acegisecurity.ui.rememberme.RememberMeServices#autoLogin(HttpServletRequest,
 * HttpServletResponse)} method called by this filter. The
 * <code>Authentication</code> or <code>null</code> returned by that method
 * will be placed into the <code>SecurityContext</code>.
 * </p>
 * 
 * <p>
 * If authentication is successful, an {@link
 * net.sf.acegisecurity.ui.InteractiveAuthenticationSuccesEvent} will be
 * published to the application context. No events will be published if
 * authentication was unsuccessful, because this would generally be recorded
 * via an <code>AuthenticationManager</code>-specific application event.
 * </p>
 * 
 * <P>
 * <B>Do not use this class directly.</B> Instead configure
 * <code>web.xml</code> to use the {@link
 * net.sf.acegisecurity.util.FilterToBeanProxy}.
 * </p>
 *
 * @author Ben Alex
 * @version $Id$
 */
public class RememberMeProcessingFilter implements Filter, InitializingBean,
    ApplicationContextAware {
    //~ Static fields/initializers =============================================

    private static final Log logger = LogFactory.getLog(RememberMeProcessingFilter.class);

    //~ Instance fields ========================================================

    private ApplicationContext context;
    private RememberMeServices rememberMeServices = new NullRememberMeServices();

    //~ Methods ================================================================

    public void setApplicationContext(ApplicationContext context) {
        this.context = context;
    }

    public void setRememberMeServices(RememberMeServices rememberMeServices) {
        this.rememberMeServices = rememberMeServices;
    }

    public RememberMeServices getRememberMeServices() {
        return rememberMeServices;
    }

    public void afterPropertiesSet() throws Exception {
        Assert.notNull(rememberMeServices);
    }

    /**
     * Does nothing - we reply on IoC lifecycle services instead.
     */
    public void destroy() {}

    public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
        if (!(request instanceof HttpServletRequest)) {
            throw new ServletException("Can only process HttpServletRequest");
        }

        if (!(response instanceof HttpServletResponse)) {
            throw new ServletException("Can only process HttpServletResponse");
        }

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        if (SecurityContextHolder.getContext().getAuthentication() == null) {
            SecurityContextHolder.getContext().setAuthentication(rememberMeServices
                .autoLogin(httpRequest, httpResponse));

            if (logger.isDebugEnabled()) {
                logger.debug(
                    "Replaced SecurityContextHolder with remember-me token: '"
                    + SecurityContextHolder.getContext().getAuthentication()
                    + "'");
            }

            // Fire event
            if (this.context != null) {
                context.publishEvent(new InteractiveAuthenticationSuccesEvent(
                        SecurityContextHolder.getContext().getAuthentication(),
                        this.getClass()));
            }
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug(
                    "SecurityContextHolder not replaced with remember-me token, as SecurityContextHolder already contained: '"
                    + SecurityContextHolder.getContext().getAuthentication()
                    + "'");
            }
        }

        chain.doFilter(request, response);
    }

    /**
     * Does nothing - we reply on IoC lifecycle services instead.
     *
     * @param arg0 not used
     *
     * @throws ServletException not thrown
     */
    public void init(FilterConfig arg0) throws ServletException {}
}

@@ -781,16 +781,60 @@
 esEvent;
+%0Aimport net.sf.acegisecurity.Authentication;
 %0A%0Aimport
@@ -3737,33 +3737,32 @@
  nothing - we re
-p
 ly on IoC lifecy
@@ -4498,46 +4498,8 @@
     
-SecurityContextHolder.getContext().set
 Auth
@@ -4508,17 +4508,17 @@
 tication
-(
+ 
 remember
@@ -4519,24 +4519,22 @@
 memberMe
-Services
+Auth =
 %0A       
@@ -4542,16 +4542,38 @@
         
+    rememberMeServices
 .autoLog
@@ -4601,20 +4601,151 @@
 esponse)
-)
 ;%0A%0A
+            if(rememberMeAuth != null) %7B%0A                SecurityContextHolder.getContext().setAuthentication(rememberMeAuth);%0A%0A    
         
@@ -4787,32 +4787,36 @@
                 
+ 
+   
 logger.debug(%0A  
@@ -4805,32 +4805,36 @@
   logger.debug(%0A
+    
                 
@@ -4908,32 +4908,36 @@
                 
+ 
+   
 + SecurityContex
@@ -4989,32 +4989,36 @@
                 
+    
 + %22'%22);%0A        
@@ -5013,35 +5013,43 @@
 %22);%0A            
+   
+ 
 %7D%0A%0A
+    
             // F
@@ -5066,24 +5066,28 @@
             
+ 
+   
 if (this.con
@@ -5094,32 +5094,36 @@
 text != null) %7B%0A
+    
                 
@@ -5201,32 +5201,36 @@
                 
+  
+  
 SecurityContextH
@@ -5289,24 +5289,28 @@
             
+    
 this.getClas
@@ -5316,16 +5316,34 @@
 ss()));%0A
+                %7D%0A
         
@@ -5780,17 +5780,16 @@
  - we re
-p
 ly on Io

Fix for SEC-27. Now checks for a null authentication before proceeding to fire the success event.