Search in sources :

Example 1 with AuthenticationFailedException

use of edu.harvard.iq.dataverse.authorization.exceptions.AuthenticationFailedException in project dataverse by IQSS.

the class AuthenticationServiceBean method canLogInAsBuiltinUser.

public AuthenticatedUser canLogInAsBuiltinUser(String username, String password) {
    logger.fine("checking to see if " + username + " knows the password...");
    if (password == null) {
        logger.info("password was null");
        return null;
    }
    AuthenticationRequest authReq = new AuthenticationRequest();
    /**
     * @todo Should this really be coming from a bundle like this? Added
     * because that's what BuiltinAuthenticationProvider does.
     */
    authReq.putCredential(BundleUtil.getStringFromBundle("login.builtin.credential.usernameOrEmail"), username);
    authReq.putCredential(BundleUtil.getStringFromBundle("login.builtin.credential.password"), password);
    /**
     * @todo Should probably set IP address here.
     */
    // authReq.setIpAddress(session.getUser().getRequestMetadata().getIpAddress());
    String credentialsAuthProviderId = BuiltinAuthenticationProvider.PROVIDER_ID;
    try {
        AuthenticatedUser au = getCreateAuthenticatedUser(credentialsAuthProviderId, authReq);
        logger.fine("User authenticated:" + au.getEmail());
        return au;
    } catch (AuthenticationFailedException ex) {
        logger.info("The username and/or password entered is invalid: " + ex.getResponse().getMessage());
        if (AuthenticationResponse.Status.BREAKOUT.equals(ex.getResponse().getStatus())) {
            /**
             * Note that this "BREAKOUT" status creates PasswordResetData!
             * We'll delete it just before blowing away the BuiltinUser in
             * AuthenticationServiceBean.convertBuiltInToShib
             */
            logger.info("AuthenticationFailedException caught in canLogInAsBuiltinUser: The username and/or password entered is invalid: " + ex.getResponse().getMessage() + " - Maybe the user (" + username + ") hasn't upgraded their password? Checking the old password...");
            BuiltinUser builtinUser = builtinUserServiceBean.findByUsernameOrEmail(username);
            if (builtinUser != null) {
                boolean userAuthenticated = PasswordEncryption.getVersion(builtinUser.getPasswordEncryptionVersion()).check(password, builtinUser.getEncryptedPassword());
                if (userAuthenticated == true) {
                    AuthenticatedUser authUser = lookupUser(BuiltinAuthenticationProvider.PROVIDER_ID, builtinUser.getUserName());
                    if (authUser != null) {
                        return authUser;
                    } else {
                        logger.info("canLogInAsBuiltinUser: Couldn't find AuthenticatedUser based on BuiltinUser username " + builtinUser.getUserName());
                    }
                } else {
                    logger.info("canLogInAsBuiltinUser: User doesn't know old pre-bcrypt password either.");
                }
            } else {
                logger.info("canLogInAsBuiltinUser: Couldn't run `check` because no BuiltinUser found with username " + username);
            }
        }
        return null;
    } catch (EJBException ex) {
        Throwable cause = ex;
        StringBuilder sb = new StringBuilder();
        sb.append(ex + " ");
        while (cause.getCause() != null) {
            cause = cause.getCause();
            sb.append(cause.getClass().getCanonicalName() + " ");
            sb.append(cause.getMessage()).append(" ");
            /**
             * @todo Investigate why authSvc.authenticate is throwing
             * NullPointerException. If you convert a Shib user or an OAuth
             * user to a Builtin user, the password will be null.
             */
            if (cause instanceof NullPointerException) {
                for (int i = 0; i < 2; i++) {
                    StackTraceElement stacktrace = cause.getStackTrace()[i];
                    if (stacktrace != null) {
                        String classCanonicalName = stacktrace.getClass().getCanonicalName();
                        String methodName = stacktrace.getMethodName();
                        int lineNumber = stacktrace.getLineNumber();
                        String error = "at " + stacktrace.getClassName() + "." + stacktrace.getMethodName() + "(" + stacktrace.getFileName() + ":" + lineNumber + ") ";
                        sb.append(error);
                    }
                }
            }
        }
        logger.info("When trying to validate password, exception calling authSvc.authenticate: " + sb.toString());
        return null;
    }
}
Also used : BuiltinUser(edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser) AuthenticationFailedException(edu.harvard.iq.dataverse.authorization.exceptions.AuthenticationFailedException) EJBException(javax.ejb.EJBException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Example 2 with AuthenticationFailedException

use of edu.harvard.iq.dataverse.authorization.exceptions.AuthenticationFailedException in project dataverse by IQSS.

the class LoginPage method login.

public String login() {
    AuthenticationRequest authReq = new AuthenticationRequest();
    List<FilledCredential> filledCredentialsList = getFilledCredentials();
    if (filledCredentialsList == null) {
        logger.info("Credential list is null!");
        return null;
    }
    for (FilledCredential fc : filledCredentialsList) {
        if (fc.getValue() == null || fc.getValue().isEmpty()) {
            JH.addMessage(FacesMessage.SEVERITY_ERROR, "Please enter a " + fc.getCredential().getTitle());
        }
        authReq.putCredential(fc.getCredential().getTitle(), fc.getValue());
    }
    authReq.setIpAddress(dvRequestService.getDataverseRequest().getSourceAddress());
    try {
        AuthenticatedUser r = authSvc.getCreateAuthenticatedUser(credentialsAuthProviderId, authReq);
        logger.log(Level.FINE, "User authenticated: {0}", r.getEmail());
        session.setUser(r);
        if ("dataverse.xhtml".equals(redirectPage)) {
            redirectPage = redirectToRoot();
        }
        try {
            redirectPage = URLDecoder.decode(redirectPage, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(LoginPage.class.getName()).log(Level.SEVERE, null, ex);
            redirectPage = redirectToRoot();
        }
        logger.log(Level.FINE, "Sending user to = {0}", redirectPage);
        return redirectPage + (!redirectPage.contains("?") ? "?" : "&") + "faces-redirect=true";
    } catch (AuthenticationFailedException ex) {
        numFailedLoginAttempts++;
        op1 = new Long(random.nextInt(10));
        op2 = new Long(random.nextInt(10));
        AuthenticationResponse response = ex.getResponse();
        switch(response.getStatus()) {
            case FAIL:
                JsfHelper.addErrorMessage(BundleUtil.getStringFromBundle("login.builtin.invalidUsernameEmailOrPassword"));
                return null;
            case ERROR:
                /**
                 * @todo How do we exercise this part of the code? Something
                 * with password upgrade? See
                 * https://github.com/IQSS/dataverse/pull/2922
                 */
                JsfHelper.addErrorMessage(BundleUtil.getStringFromBundle("login.error"));
                logger.log(Level.WARNING, "Error logging in: " + response.getMessage(), response.getError());
                return null;
            case BREAKOUT:
                return response.getMessage();
            default:
                JsfHelper.addErrorMessage("INTERNAL ERROR");
                return null;
        }
    }
}
Also used : AuthenticationFailedException(edu.harvard.iq.dataverse.authorization.exceptions.AuthenticationFailedException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AuthenticationRequest(edu.harvard.iq.dataverse.authorization.AuthenticationRequest) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) AuthenticationResponse(edu.harvard.iq.dataverse.authorization.AuthenticationResponse)

Example 3 with AuthenticationFailedException

use of edu.harvard.iq.dataverse.authorization.exceptions.AuthenticationFailedException in project dataverse by IQSS.

the class AuthenticationServiceBean method getCreateAuthenticatedUser.

/**
 * Returns an {@link AuthenticatedUser} matching the passed provider id and the authentication request. If
 *  no such user exist, it is created and then returned.
 *
 * <strong>Invariant:</strong> upon successful return from this call, an {@link AuthenticatedUser} record
 * matching the request and provider exists in the database.
 *
 * @param authenticationProviderId
 * @param req
 * @return The authenticated user for the passed provider id and authentication request.
 * @throws AuthenticationFailedException
 */
public AuthenticatedUser getCreateAuthenticatedUser(String authenticationProviderId, AuthenticationRequest req) throws AuthenticationFailedException {
    AuthenticationProvider prv = getAuthenticationProvider(authenticationProviderId);
    if (prv == null)
        throw new IllegalArgumentException("No authentication provider listed under id " + authenticationProviderId);
    if (!(prv instanceof CredentialsAuthenticationProvider)) {
        throw new IllegalArgumentException(authenticationProviderId + " does not support credentials-based authentication.");
    }
    AuthenticationResponse resp = ((CredentialsAuthenticationProvider) prv).authenticate(req);
    if (resp.getStatus() == AuthenticationResponse.Status.SUCCESS) {
        // yay! see if we already have this user.
        AuthenticatedUser user = lookupUser(authenticationProviderId, resp.getUserId());
        if (user != null) {
            user = userService.updateLastLogin(user);
        }
        if (user == null) {
            return createAuthenticatedUser(new UserRecordIdentifier(authenticationProviderId, resp.getUserId()), resp.getUserId(), resp.getUserDisplayInfo(), true);
        } else {
            if (BuiltinAuthenticationProvider.PROVIDER_ID.equals(user.getAuthenticatedUserLookup().getAuthenticationProviderId())) {
                return user;
            } else {
                return updateAuthenticatedUser(user, resp.getUserDisplayInfo());
            }
        }
    } else {
        throw new AuthenticationFailedException(resp, "Authentication Failed: " + resp.getMessage());
    }
}
Also used : AuthenticationFailedException(edu.harvard.iq.dataverse.authorization.exceptions.AuthenticationFailedException) BuiltinAuthenticationProvider(edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinAuthenticationProvider) AbstractOAuth2AuthenticationProvider(edu.harvard.iq.dataverse.authorization.providers.oauth2.AbstractOAuth2AuthenticationProvider) ShibAuthenticationProvider(edu.harvard.iq.dataverse.authorization.providers.shib.ShibAuthenticationProvider) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Example 4 with AuthenticationFailedException

use of edu.harvard.iq.dataverse.authorization.exceptions.AuthenticationFailedException in project dataverse by IQSS.

the class OAuth2FirstLoginPage method convertExistingAccount.

public String convertExistingAccount() {
    BuiltinAuthenticationProvider biap = new BuiltinAuthenticationProvider(builtinUserSvc, passwordValidatorService);
    AuthenticationRequest auReq = new AuthenticationRequest();
    final List<CredentialsAuthenticationProvider.Credential> creds = biap.getRequiredCredentials();
    auReq.putCredential(creds.get(0).getTitle(), getUsername());
    auReq.putCredential(creds.get(1).getTitle(), getPassword());
    try {
        AuthenticatedUser existingUser = authenticationSvc.getCreateAuthenticatedUser(BuiltinAuthenticationProvider.PROVIDER_ID, auReq);
        authenticationSvc.updateProvider(existingUser, newUser.getServiceId(), newUser.getIdInService());
        builtinUserSvc.removeUser(existingUser.getUserIdentifier());
        session.setUser(existingUser);
        AuthenticationProvider newUserAuthProvider = authenticationSvc.getAuthenticationProvider(newUser.getServiceId());
        JsfHelper.addSuccessMessage(BundleUtil.getStringFromBundle("oauth2.convertAccount.success", Arrays.asList(newUserAuthProvider.getInfo().getTitle())));
        return "/dataverse.xhtml?faces-redirect=true";
    } catch (AuthenticationFailedException ex) {
        setAuthenticationFailed(true);
        return null;
    }
}
Also used : AuthenticationFailedException(edu.harvard.iq.dataverse.authorization.exceptions.AuthenticationFailedException) BuiltinAuthenticationProvider(edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinAuthenticationProvider) CredentialsAuthenticationProvider(edu.harvard.iq.dataverse.authorization.CredentialsAuthenticationProvider) AuthenticationProvider(edu.harvard.iq.dataverse.authorization.AuthenticationProvider) BuiltinAuthenticationProvider(edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinAuthenticationProvider) AuthenticationRequest(edu.harvard.iq.dataverse.authorization.AuthenticationRequest) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Aggregations

AuthenticationFailedException (edu.harvard.iq.dataverse.authorization.exceptions.AuthenticationFailedException)4 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)4 AuthenticationRequest (edu.harvard.iq.dataverse.authorization.AuthenticationRequest)2 BuiltinAuthenticationProvider (edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinAuthenticationProvider)2 AuthenticationProvider (edu.harvard.iq.dataverse.authorization.AuthenticationProvider)1 AuthenticationResponse (edu.harvard.iq.dataverse.authorization.AuthenticationResponse)1 CredentialsAuthenticationProvider (edu.harvard.iq.dataverse.authorization.CredentialsAuthenticationProvider)1 BuiltinUser (edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser)1 AbstractOAuth2AuthenticationProvider (edu.harvard.iq.dataverse.authorization.providers.oauth2.AbstractOAuth2AuthenticationProvider)1 ShibAuthenticationProvider (edu.harvard.iq.dataverse.authorization.providers.shib.ShibAuthenticationProvider)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 EJBException (javax.ejb.EJBException)1