package gov.va.med.esr.common.security;

import gov.va.med.esr.service.AbstractSecurityTestCase;

import java.net.URL;

import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;

import gov.va.med.fw.security.UserPrincipal;

/**
 * TestCase to test EDBLoginModule.
 * It inherits all the methods from AbstractSecurityTestCase 
 * and provide the implementation of authenticate method to use 
 * jaas authentication.
 * 
 * @author DNS   MANSOG
 */
public class LoginModuleTest extends AbstractSecurityTestCase {
    private static final String EDB_LOGINCONTEXT = "edb.loginContext";
    private static final String JAAS_LOGIN_CONF = "/test.jaas.login.conf";
    private static final String PROP_LOGIN_CONFIG = "java.security.auth.login.config";
    
    protected void customSetUp() throws Exception {
        URL confFileUrl = getClass().getResource(JAAS_LOGIN_CONF);
        System.setProperty(PROP_LOGIN_CONFIG, confFileUrl.toString());
        super.customSetUp();
    }

    /* 
     * Delegate the authentication request to JAAS.
     * 
     * @see gov.va.med.esr.service.AbstractSecurityTestCase#authenticate(java.lang.String, java.lang.String)
     */
    protected UserPrincipal authenticate(String userName, String password)
            throws LoginException {
        UserPasswordCallbackHandler callbackHandler = new UserPasswordCallbackHandler(userName, password);
        LoginContext lc = new LoginContext(EDB_LOGINCONTEXT, callbackHandler);
        lc.login();
        Subject subject = lc.getSubject();
        return  (UserPrincipal) subject.getPrincipals().iterator().next();

    }
}