class Users {

  @Transactional
  public synchronized void modifyAuthentication(UserAuthenticationEntity userAuthenticationEntity, String currentKey, String newKey, boolean isSelf) throws AmbariException {

    if (userAuthenticationEntity != null) {
      if (userAuthenticationEntity.getAuthenticationType() == UserAuthenticationType.LOCAL) {

        String expectedCurrentKey = isSelf
          ? userAuthenticationEntity.getAuthenticationKey()
          : getAuthenticatedUserLocalAuthenticationMethod().
              orElseThrow(() -> new AmbariException("Authentication error")).getAuthenticationKey();

        if (StringUtils.isEmpty(currentKey) || !passwordEncoder.matches(currentKey, expectedCurrentKey)) {
          throw new AmbariException("Wrong current password provided");
        }

        validatePassword(newKey);

        // If we get here the authenticated user is authorized to change the password for the subject
        // user and the correct current password was supplied (if required).
        userAuthenticationEntity.setAuthenticationKey(passwordEncoder.encode(newKey));
      } else {
        // If we get here the authenticated user is authorized to change the key for the subject.
        userAuthenticationEntity.setAuthenticationKey(newKey);
      }

      userAuthenticationDAO.merge(userAuthenticationEntity);
    }
  }

}