From 871ea2592a9798aa078b19ba37cd6a87990e1712 Mon Sep 17 00:00:00 2001
From: James Moger <james.moger@gitblit.com>
Date: Mon, 08 Sep 2014 18:06:46 -0400
Subject: [PATCH] Merge branch 'ticket/174' into develop

---
 src/main/java/com/gitblit/auth/LdapAuthProvider.java |   28 +++++++++++++++++++++++++---
 1 files changed, 25 insertions(+), 3 deletions(-)

diff --git a/src/main/java/com/gitblit/auth/LdapAuthProvider.java b/src/main/java/com/gitblit/auth/LdapAuthProvider.java
index 3a688d8..5690073 100644
--- a/src/main/java/com/gitblit/auth/LdapAuthProvider.java
+++ b/src/main/java/com/gitblit/auth/LdapAuthProvider.java
@@ -119,8 +119,12 @@
 						final Map<String, UserModel> ldapUsers = new HashMap<String, UserModel>();
 
 						for (SearchResultEntry loggingInUser : result.getSearchEntries()) {
-
-							final String username = loggingInUser.getAttribute(uidAttribute).getValue();
+							Attribute uid = loggingInUser.getAttribute(uidAttribute);
+							if (uid == null) {
+								logger.error("Can not synchronize with LDAP, missing \"{}\" attribute", uidAttribute);
+								continue;
+							}
+							final String username = uid.getValue();
 							logger.debug("LDAP synchronizing: " + username);
 
 							UserModel user = userManager.getUserModel(username);
@@ -294,6 +298,20 @@
 		LDAPConnection ldapConnection = getLdapConnection();
 		if (ldapConnection != null) {
 			try {
+				boolean alreadyAuthenticated = false;
+
+				String bindPattern = settings.getString(Keys.realm.ldap.bindpattern, "");
+				if (!StringUtils.isEmpty(bindPattern)) {
+					try {
+						String bindUser = StringUtils.replace(bindPattern, "${username}", escapeLDAPSearchFilter(simpleUsername));
+						ldapConnection.bind(bindUser, new String(password));
+
+						alreadyAuthenticated = true;
+					} catch (LDAPException e) {
+						return null;
+					}
+				}
+
 				// Find the logging in user's DN
 				String accountBase = settings.getString(Keys.realm.ldap.accountBase, "");
 				String accountPattern = settings.getString(Keys.realm.ldap.accountPattern, "(&(objectClass=person)(sAMAccountName=${username}))");
@@ -304,7 +322,7 @@
 					SearchResultEntry loggingInUser = result.getSearchEntries().get(0);
 					String loggingInUserDN = loggingInUser.getDN();
 
-					if (isAuthenticated(ldapConnection, loggingInUserDN, new String(password))) {
+					if (alreadyAuthenticated || isAuthenticated(ldapConnection, loggingInUserDN, new String(password))) {
 						logger.debug("LDAP authenticated: " + username);
 
 						UserModel user = null;
@@ -409,6 +427,10 @@
 				Attribute attribute = userEntry.getAttribute(email);
 				if (attribute != null && attribute.hasValue()) {
 					user.emailAddress = attribute.getValue();
+				} else {
+					// issue-456/ticket-134
+					// allow LDAP to delete an email address
+					user.emailAddress = null;
 				}
 			}
 		}

--
Gitblit v1.9.1