/*
   * (non-Javadoc)
   * @see
   * org.exoplatform.services.security.Authenticator#validateUser(org.exoplatform
   * .services.security.Credential[])
   */
  public String validateUser(Credential[] credentials) throws LoginException, Exception {
    String username = null;
    String password = null;
    Map<String, String> passwordContext = null;
    for (Credential cred : credentials) {
      if (cred instanceof UsernameCredential) {
        username = ((UsernameCredential) cred).getUsername();
      }
      if (cred instanceof PasswordCredential) {
        password = ((PasswordCredential) cred).getPassword();
        passwordContext = ((PasswordCredential) cred).getPasswordContext();
      }
    }
    if (username == null || password == null)
      throw new LoginException("Username or Password is not defined");

    if (this.encrypter != null) password = new String(encrypter.encrypt(password.getBytes()));

    begin(orgService);
    boolean success;
    try {
      UserHandler userHandler = orgService.getUserHandler();
      if (passwordContext != null && userHandler instanceof ExtendedUserHandler) {
        PasswordEncrypter pe = new DigestPasswordEncrypter(username, passwordContext);
        success = ((ExtendedUserHandler) userHandler).authenticate(username, password, pe);
      } else {
        success = userHandler.authenticate(username, password);
      }
      // No exception occurred
      lastExceptionOnValidateUser.remove();
    } catch (DisabledUserException e) {
      lastExceptionOnValidateUser.set(e);
      throw new LoginException(
          "The user account " + username.replace("\n", " ").replace("\r", " ") + " is disabled");
    } catch (Exception e) {
      lastExceptionOnValidateUser.set(e);
      throw e;
    } finally {
      end(orgService);
    }

    if (!success)
      throw new LoginException(
          "Login failed for " + username.replace("\n", " ").replace("\r", " "));

    return username;
  }