/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sample.loginmodule;

import javax.security.auth.login.LoginException;
import sample.realm.LDAPRealm;

/**
 * Extension of the common glassfish LDAPLoginModule just to use my
 * LDAPRealm with permits to find a user without password. 
 *
 * @author ricky
 * 
 */
public class LDAPLoginModule extends com.sun.enterprise.security.auth.login.LDAPLoginModule {

    private LDAPRealm _ldapRealm;

    /**
     * Performs authentication for the current user. It searches
     * the user with the method that do the bind (checking password).
     *
     */
    @Override
    protected void authenticate()
            throws LoginException {
        // now checked and casted against my new LDAPRealm
        if (!(_currentRealm instanceof LDAPRealm)) {
            String msg = sm.getString("ldaplm.badrealm");
            throw new LoginException(msg);
        }
        _ldapRealm = (LDAPRealm) _currentRealm;
        // enforce that password cannot be empty.
        // ldap may grant login on empty password!
        if (getPasswordChar() == null || getPasswordChar().length == 0) {
            String msg = sm.getString("ldaplm.emptypassword", _username);
            throw new LoginException(msg);
        }
        String mode = _currentRealm.getProperty(LDAPRealm.PARAM_MODE);
        if (LDAPRealm.MODE_FIND_BIND.equals(mode)) {
            String[] grpList = _ldapRealm.findAndBind(_username, getPasswordChar(), true);
            commitAuthentication(_username, getPasswordChar(),
                    _currentRealm, grpList);
        } else {
            String msg = sm.getString("ldaplm.badmode", mode);
            throw new LoginException(msg);
        }
    }
}
