}
config.setName(ldapSettings.getSystemUserName());
config.setCredentials(ldapSettings.getSystemPassword());
final String principal = String.valueOf(token.getPrincipal());
LdapNetworkConnection connection = null;
try {
connection = ldapConnector.connect(config);
if(null == connection) {
LOG.error("Couldn't connect to LDAP directory");
return null;
}
final String password = String.valueOf(token.getPassword());
final LdapEntry userEntry = ldapConnector.search(connection,
ldapSettings.getSearchBase(),
ldapSettings.getSearchPattern(),
principal,
ldapSettings.isActiveDirectory());
if (userEntry == null) {
LOG.debug("User {} not found in LDAP", principal);
return null;
}
// needs to use the DN of the entry, not the parameter for the lookup filter we used to find the entry!
final boolean authenticated = ldapConnector.authenticate(connection,
userEntry.getDn(),
password);
if (!authenticated) {
LOG.info("Invalid credentials for user {} (DN {})", principal, userEntry.getDn());
return null;
}
// user found and authenticated, sync the user entry with mongodb
final User user = userService.syncFromLdapEntry(userEntry, ldapSettings, principal);
if (user == null) {
// in case there was an error reading, creating or modifying the user in mongodb, we do not authenticate the user.
LOG.error("Unable to sync LDAP user {}", userEntry.getDn());
return null;
}
} catch (LdapException e) {
LOG.error("LDAP error", e);
return null;
} catch (CursorException e) {
LOG.error("Unable to read LDAP entry", e);
return null;
} finally {
if (connection != null) {
try {
connection.close();
} catch (IOException e) {
LOG.error("Unable to close LDAP connection", e);
}
}
}