package fr.umlv.ji.security;
import java.util.*;
import javax.security.auth.spi.LoginModule;
import javax.security.auth.*;
import javax.security.auth.callback.*;
import javax.security.auth.login.*;
public abstract class SimpleLoginModule implements LoginModule {
protected Subject subject;
protected CallbackHandler loginHandler;
protected boolean debug = false;
protected boolean succeeded = false;
protected boolean commitSucceeded = false;
private String login;
private char[] password;
private String file;
private SimplePrincipal userPrincipal;
public abstract boolean verifyPasswd(String log, char[] pass, String f);
public void initialize(Subject subject, CallbackHandler loginHandler,
Map sharedState, Map options) {
this.subject = subject;
this.loginHandler = loginHandler;
debug = "true".equalsIgnoreCase((String)options.get("debug"));
file = (String)options.get("passwdFile");
}
public boolean login() throws LoginException {
if (loginHandler==null)
throw new LoginException("Error: no CallbackHandler available.");
Callback[] callbacks = new Callback[2];
callbacks[0] = new NameCallback("login: ");
callbacks[1] = new PasswordCallback("password: ", false);
try {
loginHandler.handle(callbacks);
login = ((NameCallback)callbacks[0]).getName();
char[] tmpPassword = ((PasswordCallback)callbacks[1]).getPassword();
if (tmpPassword==null) {
password = new char[0];
} else {
password = new char[tmpPassword.length];
System.arraycopy(tmpPassword,0, password,0,tmpPassword.length);
}
((PasswordCallback)callbacks[1]).clearPassword();
} catch (java.io.IOException ioe) {
throw new LoginException(ioe.toString());
} catch (UnsupportedCallbackException uce) {
throw new LoginException("Error: no authentication");
}
if (debug) {
System.err.println("Login: " + login);
System.err.println("Password: " + password);
}
succeeded = verifyPasswd(login,password,file);
if (succeeded) {
if (debug) System.out.println("Authentication succeeded");
return true;
}
if (debug) System.out.println("Authentication failed");
login = null;
password = null;
throw new FailedLoginException("Login failed");
}
public boolean commit() throws LoginException {
if (!succeeded) return false;
userPrincipal = new SimplePrincipal(login);
if (!subject.getPrincipals().contains(userPrincipal))
subject.getPrincipals().add(userPrincipal);
if (debug) System.out.println("Added SimplePrincipal to Subject");
login = null;
password = null;
commitSucceeded = true;
return true;
}
public boolean abort() throws LoginException {
if (!succeeded) return false;
if (succeeded && !commitSucceeded) {
succeeded = false;
login = null;
password = null;
userPrincipal = null;
} else
logout();
return true;
}
public boolean logout() throws LoginException {
subject.getPrincipals().remove(userPrincipal);
succeeded = commitSucceeded = false;
login = null;
password = null;
userPrincipal = null;
return true;
} }