package com.mit.mimax.realm;

import java.io.Serializable;
import java.util.Hashtable;
import java.util.Set;

import javax.naming.Context;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import sun.security.acl.PrincipalImpl;

import com.mit.configuration.CustomProps;
import com.mit.logging.Logger;
import com.mit.mimax.roles.RoleManager;
import com.sun.appserv.security.AppservPasswordLoginModule;
import com.sun.enterprise.security.LoginException;

public class MiMaxLoginModule extends AppservPasswordLoginModule implements Serializable
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 2795930177653281597L;
	@SuppressWarnings("unchecked")
	protected void authenticateUser() throws LoginException 
	{
		Logger.info("MiMaxLoginModule : authenticateUser for " + _username);
		@SuppressWarnings("unused")
		MiMaxRealm realm = (MiMaxRealm) _currentRealm;
	
		try
		{
			if(CustomProps.isLive())
			{
				if (lDapLogin(_username,_password))
				{
					//_logger.info("User authenticated");
					Set principals = _subject.getPrincipals();
					principals.add(new PrincipalImpl(_username));
					String grpList[] = RoleManager.getUserRoles(_username);	
					this.commitUserAuthentication(grpList);
				}
				else
				{
					_logger.info("Invalid credentials.");
					throw new LoginException ("Invalid credentials.");
				}
			}
			else
			{
				Set principals = _subject.getPrincipals();
				principals.add(new PrincipalImpl(_username));
				String grpList[] = RoleManager.getUserRoles(_username);	
				this.commitUserAuthentication(grpList);
			}
		}
		catch(Exception ex)
		{
			throw new LoginException("Invalid Login");
		}
	}
	private boolean lDapLogin(String userName, String password)throws Exception
	{
		String ip;
        String port;
        ip = CustomProps.getLDapURL();
        port = CustomProps.getLDapPort();
        String fullUrl = ip + ":" + port;
        
        Hashtable<String,String> env = new Hashtable<String,String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, fullUrl);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, "uid=" + userName + ",ou=People,o=millenniumit.com,o=isp");
        env.put(Context.SECURITY_CREDENTIALS, password);

        DirContext dctx = new InitialDirContext(env);
        dctx.close();
        return true;
    }
}
