private void createUserIfNeeded(LDAPResource ldap, String cn) throws LdapException { Entry ldapUser = ldap.getUser(cn); String email = ldap.getAttribute(ldapUser, emailAttr); User user = users.findByEmail(email); if (user == null) { String fullName = ldap.getAttribute(ldapUser, nameAttr); if (isNotEmpty(surnameAttr)) { fullName += " " + ldap.getAttribute(ldapUser, surnameAttr); } user = new User(fromTrustedText(fullName.trim()), email); LoginMethod brutalLogin = LoginMethod.brutalLogin(user, email, PLACHOLDER_PASSWORD); user.add(brutalLogin); users.save(user); loginMethods.save(brutalLogin); } // update moderator status // if (isNotEmpty(moderatorGroup) && ldap.getGroups(ldapUser).contains(moderatorGroup)) { // user = user.asModerator(); // } else { // user.removeModerator(); // } // updateAvatarImage(ldap, ldapUser, user); users.save(user); }
/** * Find the email address for a given username * * @param username * @return */ public String getEmail(String username) { try (LDAPResource ldap = new LDAPResource()) { Entry ldapUser = ldap.getUser(userCn(username)); return ldap.getAttribute(ldapUser, emailAttr); } catch (LdapException | IOException e) { logger.debug("LDAP connection error", e); throw new AuthenticationException(LDAP_AUTH, "LDAP connection error", e); } }
/** * Attempt to authenticate against LDAP directory. Accepts email addresses as well as plain * usernames; emails will have the '@mail.com' portion stripped off before read. * * @param username * @param password * @return */ public boolean authenticate(String username, String password) { try (LDAPResource ldap = new LDAPResource()) { String cn = userCn(username); ldap.verifyCredentials(cn, password); createUserIfNeeded(ldap, cn); return true; } catch (LdapAuthenticationException e) { logger.debug("LDAP auth attempt failed"); return false; } catch (LdapException | IOException e) { logger.debug("LDAP connection error", e); throw new AuthenticationException(LDAP_AUTH, "LDAP connection error", e); } }
private String userCn(String username) { if (lookupAttrs.length > 0) { try (LDAPResource ldap = new LDAPResource()) { Entry user = ldap.lookupUser(username); if (user != null) { return user.getDn().getName(); } } catch (LdapException | IOException e) { logger.debug("LDAP connection error", e); throw new AuthenticationException(LDAP_AUTH, "LDAP connection error", e); } } // fallback: assume lookup by CN String sanitizedUser = username.replaceAll("[,=]", ""); String cn = "cn=" + sanitizedUser + "," + userDn; return cn; }
private byte[] getAvatarImage(LDAPResource ldap, Entry entry) throws LdapException { if (avatarImageAttr != null && avatarImageAttr.length() > 0) { try { return ldap.getByteAttribute(entry, avatarImageAttr); } catch (InvalidAttributeValueException ex) { throw new LdapException("Invalid attribute value while looking up " + avatarImageAttr, ex); } } return null; }