Index: src/edu/ucsb/nceas/metacat/AuthLdap.java
===================================================================
--- src/edu/ucsb/nceas/metacat/AuthLdap.java	(revision 1004)
+++ src/edu/ucsb/nceas/metacat/AuthLdap.java	(revision 1005)
@@ -109,9 +109,30 @@
         authenticated = ldapAuthenticate(identifier, password);
         // if not found, try looking up a valid DN then auth again
         if (!authenticated) {
+            MetaCatUtil.debugMessage("Looking up DN for: " + identifier);
             identifier = getIdentifyingName(identifier,ldapUrl,ldapBase);
             System.out.println("identifier: "+identifier);
-            authenticated = ldapAuthenticate(identifier+","+ldapBase, password);
+            String refUrl = "";
+            String refBase = "";
+            if (identifier.startsWith("ldap")) {
+                refUrl = identifier.substring(0,
+                               identifier.lastIndexOf("/")+1);
+                MetaCatUtil.debugMessage("Ref ldapUrl: " + refUrl);
+                int position = identifier.indexOf(",");
+                int position2 = identifier.indexOf(",", position+1);
+                refBase = identifier.substring(position2+1);
+                MetaCatUtil.debugMessage("Ref ldapBase: " + refBase);
+                identifier = identifier.substring(
+                             identifier.lastIndexOf("/")+1);
+                MetaCatUtil.debugMessage("Trying: " + identifier);
+                authenticated = ldapAuthenticate(identifier, password,
+                                                 refUrl, refBase);
+            } else {
+                identifier = identifier+","+ldapBase;
+                MetaCatUtil.debugMessage("Trying: " + identifier);
+                authenticated = ldapAuthenticate(identifier, password);
+            }
+            //authenticated = ldapAuthenticate(identifier, password);
         }
      
     } catch (NullPointerException e) {
@@ -141,6 +162,21 @@
   private boolean ldapAuthenticate(String identifier, String password)
             throws ConnectException, NamingException, NullPointerException
   {
+      return ldapAuthenticate(identifier, password, 
+                              this.ldapsUrl, this.ldapBase);
+  }
+
+  /**
+   * Connect to the LDAP directory and do the authentication using the
+   * username and password as passed into the routine.
+   *
+   * @param identifier the distinguished name to check against LDAP
+   * @param password the password for authentication
+   */
+  private boolean ldapAuthenticate(String identifier, String password,
+            String directoryUrl, String searchBase)
+            throws ConnectException, NamingException, NullPointerException
+  {
     double totStartTime = System.currentTimeMillis();
     boolean authenticated = false;
     if (identifier != null && !password.equals("")) 
@@ -154,12 +190,12 @@
         env.put(Context.INITIAL_CONTEXT_FACTORY, 
               "com.sun.jndi.ldap.LdapCtxFactory");
         env.put(Context.REFERRAL, "throw");
-        env.put(Context.PROVIDER_URL, ldapsUrl + ldapBase);
+        env.put(Context.PROVIDER_URL, directoryUrl + searchBase);
         if ( !ldapsUrl.equals(ldapUrl) ) 
         {
           // ldap is set on default port 389
           // ldaps is set on second port - 636 by default
-          env.put(Context.SECURITY_PROTOCOL, "ssl");
+          //env.put(Context.SECURITY_PROTOCOL, "ssl");
         }
         env.put(Context.SECURITY_AUTHENTICATION, "simple");
         env.put(Context.SECURITY_PRINCIPAL, identifier);
@@ -266,8 +302,21 @@
       // Search for the user id or name using the uid, then cn and sn 
       //attributes
       // If we find a record, determine the dn for the record
+      // The following blocks need to be refactored into a subroutine
+      // they have a ridiculous amount of redundancy
 
-      String filter = "(" + user + ")";
+      // Parse out the uid and org components and look up the real DN
+      // This assumes a dn like "uid=x,o=y,dc=someinst,dc=org"
+      int position = user.indexOf(",");
+      String comp1 = user.substring(0, position);
+      MetaCatUtil.debugMessage("First comp is: " + comp1);
+      String comp2 = user.substring(position+1, 
+                                    user.indexOf(",", position+1));
+      MetaCatUtil.debugMessage("Second comp is: " + comp2);
+
+      String filter = "(&(" + comp1 + ")(" + comp2 + "))";
+      MetaCatUtil.debugMessage("Filter is: " + filter);
+      MetaCatUtil.debugMessage("Provider URL is: " + ldapUrl + ldapBase);
       NamingEnumeration answer;
       try {
         answer = ctx.search("", filter, ctls);
@@ -274,6 +323,18 @@
         if (answer.hasMore()) {
           SearchResult sr = (SearchResult)answer.next();
           identifier = sr.getName();
+          util.debugMessage("Originally Found: " + identifier);
+          return identifier;
+        }
+      } catch (InvalidSearchFilterException e) {}
+
+      // That failed, so check if it is just a username
+      filter = "(" + user + ")";
+      try {
+        answer = ctx.search("", filter, ctls);
+        if (answer.hasMore()) {
+          SearchResult sr = (SearchResult)answer.next();
+          identifier = sr.getName();
           if ( !sr.isRelative() ) { 
             this.ldapUrl = identifier.substring(0,
                                                 identifier.lastIndexOf("/")+1);
@@ -285,6 +346,8 @@
           return identifier;
         }
       } catch (InvalidSearchFilterException e) {}
+
+      // Maybe its a user id (uid)
       filter = "(uid=" + user + ")";
       answer = ctx.search("", filter, ctls);
       if (answer.hasMore()) {
@@ -298,6 +361,8 @@
         }
         util.debugMessage("Found: " + identifier);
       } else {
+
+        // maybe its just a common name
         filter = "(cn=" + user + ")";
         NamingEnumeration answer2 = ctx.search("", filter, ctls);
         if (answer2.hasMore()) {
@@ -312,6 +377,8 @@
           }
           util.debugMessage("Found: " + identifier);
         } else {
+
+          // ok, last resort, is it a surname?
           filter = "(sn=" + user + ")";
           NamingEnumeration answer3 = ctx.search("", filter, ctls);
           if (answer3.hasMore()) {
@@ -838,11 +905,13 @@
     String user = args[0];
     String password = args[1];
 
+    MetaCatUtil.debugMessage("Creating session...");
     AuthLdap authservice = new AuthLdap();
-
+    MetaCatUtil.debugMessage("Session exists...");
                 
     boolean isValid = false;
     try {
+      MetaCatUtil.debugMessage("Authenticating...");
       isValid = authservice.authenticate(user, password);
       if (isValid) {
         MetaCatUtil.debugMessage("Authentication successful for: " + user );
@@ -950,10 +1019,10 @@
         referralInfo=(String)refExc.getReferralInfo();
         env.put(Context.PROVIDER_URL,refExc.getReferralInfo());
         System.out.println("referral info: "+referralInfo);
-        if (referralInfo.indexOf("piscoweb")!=-1)
-        {
-          userName=uid+",o=PISCO,dc=piscoweb,dc=org";
-        }
+        //if (referralInfo.indexOf("piscoweb")!=-1)
+        //{
+          //userName=uid+",o=PISCO,dc=piscoweb,dc=org";
+        //}
         env.put(Context.INITIAL_CONTEXT_FACTORY, 
                 "com.sun.jndi.ldap.LdapCtxFactory");
         System.out.println("principal: "+userName);
