/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2005-2008 Bull S.A.S.
 * Contact: jonas-team@objectweb.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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */
package org.objectweb.jonas.web.catalina55;

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

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

import org.apache.catalina.Session;
import org.apache.catalina.authenticator.Constants;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.realm.GenericPrincipal;
import org.apache.catalina.valves.ValveBase;
import org.objectweb.jonas.security.realm.web.catalina55.JOnASGenericPrincipal;
import org.objectweb.security.context.SecurityContext;
import org.objectweb.security.context.SecurityCurrent;

/**
 * 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();

    /**<o
     * 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(Request request, 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();

                // No principal, maybe it's in the form ?
                if (principal == null) {
                    principal = (Principal) session.getNote(Constants.FORM_PRINCIPAL_NOTE);
                }

            }
        }


        // We've found a principal (either in the request or in the session)
        if (principal != null && principal instanceof GenericPrincipal) {
            // Cast object
            GenericPrincipal genericPrincipal = (GenericPrincipal) principal;

            // Build Security Context object
            SecurityContext ctx = new SecurityContext(principal.getName(), genericPrincipal.getRoles());

            // Also a JOnAS Security principal ? try to see if there is security signature
            if (principal instanceof JOnASGenericPrincipal) {
                JOnASGenericPrincipal jOnASGenericPrincipal = (JOnASGenericPrincipal) principal;
                byte[] signature = jOnASGenericPrincipal.getSignature();
                if (signature != null) {
                    ctx.setSignature(signature);
                }
            }

            SecurityCurrent current = SecurityCurrent.getCurrent();
            current.setSecurityContext(ctx);
        }


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

}
