/*
 * JBoss, the OpenSource WebOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.web.tomcat.security;

import java.io.IOException;
import java.security.Principal;
import javax.servlet.ServletException;

import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;

/** A valve that associates the Principal as obtained from the authentication
 * layer with the request. This allows any custom principal established by
 * the authentication layer to be seen by the web app.
 *  
 * @author Scott.Stark@jboss.org
 * @version $Revision: 1.1.2.4 $
 */
public class CustomPrincipalValve
   extends ValveBase
{
   public void invoke(Request request, Response response)
      throws IOException, ServletException
   {
      Principal user = request.getUserPrincipal();
      if( user instanceof JBossGenericPrincipal )
      {
         // Restore the actual principal to the request
         JBossGenericPrincipal guser = (JBossGenericPrincipal) user;
         Principal realUser = guser.getCallerPrincipal();
         request.setUserPrincipal(realUser);
      }

      getNext().invoke(request, response);
   }
}