// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package custom;

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

import javax.jcr.Credentials;
import javax.jcr.SimpleCredentials;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;

import org.apache.jackrabbit.core.security.authentication.CredentialsCallback;
import org.apache.jackrabbit.core.security.principal.AdminPrincipal;

public class JRBLoginModule implements LoginModule {
	private Subject subject;
	private CallbackHandler callbackHandler;
	private Principal principal;
	@Override
	public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) {
		this.subject = subject;
		this.callbackHandler = callbackHandler;
	}
	@Override
	public boolean login() throws LoginException {
		try {
			CredentialsCallback ccb = new CredentialsCallback();
			callbackHandler.handle(new Callback[] { ccb });
			Credentials cred = ccb.getCredentials();
			if(cred instanceof SimpleCredentials) {
				SimpleCredentials scred = (SimpleCredentials)cred;
				String usr = scred.getUserID();
				String pwd = new String(scred.getPassword());
				if(usr.equals("jcradmin") && pwd.equals("secret")) {
					principal = new AdminPrincipal(usr);
					return true;
				} else {
					throw new LoginException();
				}
			} else {
				return false;
			}
		} catch (IOException e) {
			return false;
		} catch (UnsupportedCallbackException e) {
			return false;
		}
	}
	@Override
	public boolean commit() throws LoginException {
		subject.getPrincipals().add(principal);
		return true;
	}
	@Override
	public boolean abort() throws LoginException {
		return true;
	}
	@Override
	public boolean logout() throws LoginException {
		return true;
	}
}
