// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
package jaastest;

import java.io.IOException;
import java.util.Map;

import javax.security.auth.spi.LoginModule;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;

public class TestAuthenticator implements LoginModule {
    private String name = null;
    private String password = null;
    private Subject subject;
    public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
        try {
            Callback[] cb = new Callback[2];
            cb[0] = new NameCallback("Name");
            cb[1] = new PasswordCallback("Password", false);
            callbackHandler.handle(cb);
            name = ( (NameCallback) cb[0]).getName();
            password = new String( ( (PasswordCallback) cb[1]).getPassword());
            this.subject = subject;
        } catch (UnsupportedCallbackException ex) {
        } catch (IOException ex) {
        }
    }
    public boolean login() throws LoginException {
        if(name != null && name.equals("arne") &&
           password != null && password.equals("rigtig")) {
            return true;
        } else if(name != null && name.equals("system") &&
                  password != null && password.equals("rigtig")) {
            return true;
        } else {
            throw new LoginException("Bad name/password");
        }
    }
    public boolean commit() throws LoginException {
        subject.getPrincipals().add(new TestPrincipal(name));
        return true;
    }
    public boolean abort() throws LoginException {
        // nothing
        return true;
    }
    public boolean logout() throws LoginException {
        // nothing
        return true;
    }
}
