/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2005-2007 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id: ResetAuthenticationValve.java 20987 2011-03-14 12:10:10Z benoitf $
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.web.tomcat7;

import java.io.IOException;
import java.security.Principal;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

import org.ow2.jonas.lib.security.context.SecurityContext;
import org.ow2.jonas.lib.security.context.SecurityCurrent;

import org.apache.catalina.Session;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.realm.GenericPrincipal;
import org.apache.catalina.valves.ValveBase;

/**
 * This valve reset the authentication and propagate the cached principal
 * Authenticator valve will be called after (if an authentication is needed
 * further).
 * @author Florent Benoit
 */
public class ResetAuthenticationValve extends ValveBase {

    /**
     * Unauthenticated security context.
     */
    private static final SecurityContext UNAUTHENTICATED = new SecurityContext();

    /**
     * Remove the current authenticated user by setting the anonymous user.
     * @param request The servlet request to be processed
     * @param response The servlet response to be created
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    public void invoke(final Request request, final Response response) throws IOException, ServletException {

        // First, check if there is a principal in the current request
        Principal principal = request.getPrincipal();
        if (principal == null) {
            // No principal in the request, check if there is a session
            HttpSession httpSession = request.getSession(false);
            if (httpSession != null) {
                // There is a session, check if there is a principal associated
                // to this session.
                Session session = getContainer().getManager().findSession(httpSession.getId());
                principal = session.getPrincipal();
            }
        }

        // We've found a principal (either in the request or in the session)
        if (principal != null) {
            // Cast if it is a generic principal
            if (principal instanceof GenericPrincipal) {
                GenericPrincipal genericPrincipal = (GenericPrincipal) principal;
                SecurityContext ctx = new SecurityContext(principal.getName(), genericPrincipal.getRoles());
                SecurityCurrent current = SecurityCurrent.getCurrent();
                current.setSecurityContext(ctx);
            }

            // Call next valve
            try {
                getNext().invoke(request, response);
            } finally {
                // Reset authentication
                SecurityCurrent.getCurrent().setSecurityContext(UNAUTHENTICATED);
            }
        } else {
            // call the next valve
            getNext().invoke(request, response);
        }
    }
}
