package org.jboss.security.auth.spi;
import java.security.acl.Group;
import java.util.Map;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;
import javax.security.auth.login.FailedLoginException;
public class DatabaseServerLoginModule extends UsernamePasswordLoginModule
{
protected String dsJndiName;
protected String principalsQuery = "select Password from Principals where PrincipalID=?";
protected String rolesQuery = "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("principalsQuery");
if( tmp != null )
principalsQuery = tmp.toString();
tmp = options.get("rolesQuery");
if( tmp != null )
rolesQuery = tmp.toString();
log.trace("DatabaseServerLoginModule, dsJndiName="+dsJndiName);
log.trace("principalsQuery="+principalsQuery);
log.trace("rolesQuery="+rolesQuery);
}
protected String getUsersPassword() throws LoginException
{
String username = getUsername();
String password = null;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup(dsJndiName);
conn = ds.getConnection();
ps = conn.prepareStatement(principalsQuery);
ps.setString(1, username);
rs = ps.executeQuery();
if( rs.next() == false )
throw new FailedLoginException("No matching username found in Principals");
password = rs.getString(1);
password = convertRawPassword(password);
}
catch(NamingException ex)
{
throw new LoginException(ex.toString(true));
}
catch(SQLException ex)
{
log.error("Query failed", ex);
throw new LoginException(ex.toString());
}
finally
{
if (rs != null)
{
try
{
rs.close();
}
catch(SQLException e)
{}
}
if( ps != null )
{
try
{
ps.close();
}
catch(SQLException e)
{}
}
if( conn != null )
{
try
{
conn.close();
}
catch (SQLException ex)
{}
}
}
return password;
}
protected Group[] getRoleSets() throws LoginException
{
String username = getUsername();
Group[] roleSets = Util.getRoleSets(username, dsJndiName, rolesQuery, this);
return roleSets;
}
protected String convertRawPassword(String rawPassword)
{
return rawPassword;
}
}