package edu.yale.its.tp.cas.auth.provider;

import java.io.*;
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;
import edu.yale.its.tp.cas.auth.*;

/**
 * Authenticate by binding against an LDAP directory.
 * Some code borrowed from uPortal SimpleLdapSecurityContext
 * and LdapServices
 *
 * @author Andrew Draskoy
 */

public class LdapHandler extends WatchfulPasswordHandler {

    private static String url = "ldap://test.mun.ca:389";
    //private static String baseDN = "dc=mun,dc=ca";
    private static String baseDN = "ou=users,dc=mun,dc=ca";
    private static String uidAttribute = "uid";

    public boolean authenticate(javax.servlet.ServletRequest request,
                                String username,
                                String password)
    {
      StringBuffer dnBuffer = new StringBuffer("uid=");
      dnBuffer.append(username).append(",").append(baseDN);
      DirContext conn = null;
      boolean status;
      PrintStream log = null;

      try {
	File logFile = new File("/tmp/ldap_handler.log");
	log = new PrintStream(new FileOutputStream(logFile));
	log.println("Provider URL is" + url);
	log.println("DN is: " + dnBuffer.toString());
	log.println("Trying to auth " + username);
	log.flush();
      } catch(IOException e) {
      }

      try {
	Hashtable env = new Hashtable(5, 0.75f);
	env.put(Context.INITIAL_CONTEXT_FACTORY,
		"com.sun.jndi.ldap.LdapCtxFactory");
	env.put(Context.PROVIDER_URL, url);
	env.put(Context.SECURITY_AUTHENTICATION, "simple");
	env.put(Context.SECURITY_PRINCIPAL, dnBuffer.toString());
	env.put(Context.SECURITY_CREDENTIALS, password);;
	// env.put(Context.SECURITY_PROTOCOL,"ssl");
	conn = new InitialDirContext(env);
	log.println("Successfully authenticated" + username); log.flush();
	status = true;
      } catch (Exception e) {
	status = false;
	if ( log != null)
	  log.println(e.toString()); log.flush();
      } finally {
	if ( conn != null )
	  try {
            conn.close();
	    if ( log != null)
	      log.close();
	  } catch (Exception e) {
	    // we don't care
	  }
      }

      return status;
    }
}
