public synchronized void modifyPassword(String userName, String currentUserPassword, String newPassword) throws AmbariException {
SecurityContext securityContext = SecurityContextHolder.getContext();
String currentUserName = securityContext.getAuthentication().getName();
if (currentUserName == null) {
throw new AmbariException("Authentication required. Please sign in.");
}
UserEntity currentUserEntity = userDAO.findLocalUserByName(currentUserName);
//Authenticate LDAP admin user
boolean isLdapAdmin = false;
if (currentUserEntity == null) {
currentUserEntity = userDAO.findLdapUserByName(currentUserName);
try {
ldapAuthenticationProvider.authenticate(
new UsernamePasswordAuthenticationToken(currentUserName, currentUserPassword));
isLdapAdmin = true;
} catch (BadCredentialsException ex) {
throw new AmbariException("Incorrect password provided for LDAP user " +
currentUserName);
}
}
UserEntity userEntity = userDAO.findLocalUserByName(userName);
if ((userEntity != null) && (currentUserEntity != null)) {
if (isLdapAdmin || passwordEncoder.matches(currentUserPassword, currentUserEntity.getUserPassword())) {
userEntity.setUserPassword(passwordEncoder.encode(newPassword));
userDAO.merge(userEntity);
} else {
throw new AmbariException("Wrong password provided");
}
} else {
userEntity = userDAO.findLdapUserByName(userName);
if (userEntity != null) {
throw new AmbariException("Password of LDAP user cannot be modified");
} else {
throw new AmbariException("User " + userName + " not found");
}
}
}