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

import org.jboss.security.RealmMapping;
import org.jboss.security.RunAsIdentity;
import org.jboss.security.SecurityAssociation;
import org.jboss.security.SimplePrincipal;

import java.security.Principal;
import java.util.HashSet;

/**
 * Obtain security information based on the current security domain.
 *
 * 
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.2.2.6 $
 */
public class SecurityContext
{
   protected static ThreadLocal currentDomain = new ThreadLocal();

   /**
    * Get the caller's principal
    * @return
    */
   public static Principal getCallerPrincipal()
   {
      return SecurityAssociation.getCallerPrincipal();
   }

   /**
    * Get the current principal.  Could be run-as, or propagated
    * @return
    */
   public static Principal getCurrentPrincipal()
   {
     return SecurityAssociation.getPrincipal();
   }

   /**
    * Is the caller's security identity within the role
    *
    * Does not include current run-as
    * @param roleName
    * @return
    */
   public static boolean isCallerInRole(String roleName)
   {
      return isInRole(getCallerPrincipal(), roleName);
   }

   /**
    * Checks current identity is within roleName
    *
    * Does include current run-as
    * 
    * @param roleName
    * @return
    */
   public static boolean isCurrentInRole(String roleName)
   {
      return isInRole(getCurrentPrincipal(), roleName);
   }

   private static boolean isInRole(Principal principal, String roleName)
   {
      RealmMapping rm = (RealmMapping)currentDomain.get();
      if (rm == null) return false;

      HashSet set = new HashSet();
      set.add(new SimplePrincipal(roleName));

      if (principal instanceof RunAsIdentity)
      {
         return ((RunAsIdentity)principal).doesUserHaveRole(set);
      }
      else
      {
         return rm.doesUserHaveRole(principal, set);
      }
   }


}
