// 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.util.Map;

import javax.jcr.Credentials;
import javax.jcr.SimpleCredentials;

import org.modeshape.jcr.ExecutionContext;
import org.modeshape.jcr.security.AuthenticationProvider;
import org.modeshape.jcr.security.SecurityContext;

public class MSLoginModule implements  AuthenticationProvider {
	public static class MSSecurityContext implements SecurityContext {
		private String usr;
		public MSSecurityContext(String usr) {
			this.usr = usr;
		}
		@Override
		public String getUserName() {
			return usr;
		}
		@Override
		public boolean hasRole(String roleName) {
			return true;
		}
		@Override
		public boolean isAnonymous() {
			return false;
		}
		@Override
		public void logout() {
		}
	}
	@Override
	public ExecutionContext authenticate(Credentials credentials, String repositoryName, String workspaceName, ExecutionContext repositoryContext, Map<String, Object> sessionAttributes) {
		if(credentials instanceof SimpleCredentials) {
			SimpleCredentials simpcred = (SimpleCredentials)credentials;
			String usr = simpcred.getUserID();
			String pwd = new String(simpcred.getPassword());
			if(usr.equals("jcradmin") && pwd.equals("secret")) {
				return repositoryContext.with(new MSSecurityContext(usr));
			} else {
				return null;
			}
		} else {
			return null;
		}
	}
}
