/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.ejb3.security;

import java.util.HashSet;
import java.util.Set;
import javax.annotation.security.DenyAll;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJBAccessException;
import org.jboss.aop.joinpoint.Invocation;
import org.jboss.logging.Logger;
import org.jboss.security.AnybodyPrincipal;
import org.jboss.security.AuthenticationManager;
import org.jboss.security.NobodyPrincipal;
import org.jboss.security.RealmMapping;
import org.jboss.security.SimplePrincipal;

/**
 * The RoleBasedAuthorizationInterceptor checks that the caller principal is
 * authorized to call a method by verifing that it contains at least one
 * of the required roled.
 *
 * @author <a href="bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.3.4.4 $
 */
public final class RoleBasedAuthorizationInterceptor extends org.jboss.aspects.security.RoleBasedAuthorizationInterceptor
{
   private static final Logger log = Logger.getLogger(RoleBasedAuthorizationInterceptor.class);
   
   public RoleBasedAuthorizationInterceptor(AuthenticationManager manager, RealmMapping realmMapping)
   {
      super(manager, realmMapping);
   }

   protected Set getRoleSet(Invocation invocation)
   {
      HashSet set = new HashSet();

      Class[] classes = new Class[]{DenyAll.class, PermitAll.class, RolesAllowed.class};

      Object annotation = invocation.resolveAnnotation(classes);
      
      int classIndex = 0;
      while (annotation == null && classIndex < 3)
      {
         annotation = invocation.resolveClassAnnotation(classes[classIndex++]);
      }
      
      if (annotation != null)
      {
         if (annotation instanceof DenyAll)
         {
            set.add(NobodyPrincipal.NOBODY_PRINCIPAL);
         }
         else if (annotation instanceof PermitAll)
         {
            set.add(AnybodyPrincipal.ANYBODY_PRINCIPAL);
         }
         else if (annotation instanceof RolesAllowed)
         {
            RolesAllowed permissions = (RolesAllowed) annotation;
            for (int i = 0; i < permissions.value().length; i++)
            {
               set.add(new SimplePrincipal(permissions.value()[i]));
            }
         }
         else
            set.add(AnybodyPrincipal.ANYBODY_PRINCIPAL);
      }
      else
         set.add(AnybodyPrincipal.ANYBODY_PRINCIPAL);

      return set;
   }

   public Object invoke(Invocation invocation) throws Throwable
   {
      try
      {
         return super.invoke(invocation);
      }
      catch (SecurityException throwable)
      {
         throw new EJBAccessException("Authorization failure", throwable);
      } finally {
      }
   }

}
