/*
 * JBoss, Home of Professional Open Source
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.security.auth.spi;

import java.security.acl.Group;
import java.util.Map;

import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;

/**
 * A Certificate Login Module that gets its role information from a database.
 * 
 * This module is the functional equivelant of the 
 * {@link org.jboss.security.auth.spi.DatabaseServerLoginModule} minus the
 * usersQuery.
 * @see org.jboss.security.auth.spi.DatabaseServerLoginModule
 *
 * @author <a href="mailto:jasone@greenrivercomputing.com">Jason Essington</a>
 * @author Scott.Stark@jboss.org
 * @version $Revision: 1.2.4.1 $
 */
public class DatabaseCertLoginModule extends BaseCertLoginModule
{
   /** The JNDI name of the DataSource to use */
   private String dsJndiName;
   /** The sql query to obtain the user roles */
   private String rolesQuery = "select Role, RoleGroup from Roles where PrincipalID=?";
   
   /**
    * @param options -
    * dsJndiName: The name of the DataSource of the database containing the
    *    Principals, Roles tables
    * rolesQuery: The prepared statement query, equivalent to:
    *    "select Role, RoleGroup from Roles where PrincipalID=?"
    */
   public void initialize(Subject subject, CallbackHandler callbackHandler,
      Map sharedState, Map options)
   {
      super.initialize(subject, callbackHandler, sharedState, options);
      dsJndiName = (String) options.get("dsJndiName");
      if( dsJndiName == null )
         dsJndiName = "java:/DefaultDS";
      
      Object tmp = options.get("rolesQuery");
      if( tmp != null )
         rolesQuery = tmp.toString();
      
      log.trace("DatabaseServerLoginModule, dsJndiName="+dsJndiName);
      log.trace("rolesQuery="+rolesQuery);
   }

   /**
    * @see org.jboss.security.auth.spi.DatabaseServerLoginModule#getRoleSets
    */
   protected Group[] getRoleSets() throws LoginException
   {
      String username = getUsername();
      Group[] roleSets = Util.getRoleSets(username, dsJndiName, rolesQuery, this);
      return roleSets;
   }
   
}