Search in sources :

Example 1 with BuiltinUser

use of edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser 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 BuiltinUser

use of edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser in project dataverse by IQSS.

the class AuthenticationServiceBean method convertBuiltInToShib.

// TODO should probably be moved to the Shib provider - this is a classic Shib-specific
// use case. This class should deal with general autnetications.
@Deprecated
public /**
 * @deprecated. Switch to convertBuiltInUserToRemoteUser instead.
 * @todo. Switch to convertBuiltInUserToRemoteUser instead.
 */
AuthenticatedUser convertBuiltInToShib(AuthenticatedUser builtInUserToConvert, String shibProviderId, UserIdentifier newUserIdentifierInLookupTable) {
    logger.info("converting user " + builtInUserToConvert.getId() + " from builtin to shib");
    String builtInUserIdentifier = builtInUserToConvert.getIdentifier();
    logger.info("builtin user identifier: " + builtInUserIdentifier);
    TypedQuery<AuthenticatedUserLookup> typedQuery = em.createQuery("SELECT OBJECT(o) FROM AuthenticatedUserLookup AS o WHERE o.authenticatedUser = :auid", AuthenticatedUserLookup.class);
    typedQuery.setParameter("auid", builtInUserToConvert);
    AuthenticatedUserLookup authuserLookup;
    try {
        authuserLookup = typedQuery.getSingleResult();
    } catch (NoResultException | NonUniqueResultException ex) {
        logger.info("exception caught: " + ex);
        return null;
    }
    if (authuserLookup == null) {
        return null;
    }
    String oldProviderId = authuserLookup.getAuthenticationProviderId();
    logger.info("we expect this to be 'builtin': " + oldProviderId);
    authuserLookup.setAuthenticationProviderId(shibProviderId);
    String oldUserLookupIdentifier = authuserLookup.getPersistentUserId();
    logger.info("this should be 'pete' or whatever the old builtin username was: " + oldUserLookupIdentifier);
    String perUserShibIdentifier = newUserIdentifierInLookupTable.getLookupStringPerAuthProvider();
    authuserLookup.setPersistentUserId(perUserShibIdentifier);
    /**
     * @todo this should be a transaction of some kind. We want to update
     * the authenticateduserlookup and also delete the row from the
     * builtinuser table in a single transaction.
     */
    em.persist(authuserLookup);
    String builtinUsername = builtInUserIdentifier.replaceFirst(AuthenticatedUser.IDENTIFIER_PREFIX, "");
    BuiltinUser builtin = builtinUserServiceBean.findByUserName(builtinUsername);
    if (builtin != null) {
        // These were created by AuthenticationResponse.Status.BREAKOUT in canLogInAsBuiltinUser
        List<PasswordResetData> oldTokens = passwordResetServiceBean.findPasswordResetDataByDataverseUser(builtin);
        for (PasswordResetData oldToken : oldTokens) {
            em.remove(oldToken);
        }
        em.remove(builtin);
    } else {
        logger.info("Couldn't delete builtin user because could find it based on username " + builtinUsername);
    }
    AuthenticatedUser shibUser = lookupUser(shibProviderId, perUserShibIdentifier);
    if (shibUser != null) {
        return shibUser;
    }
    return null;
}
Also used : NonUniqueResultException(javax.persistence.NonUniqueResultException) PasswordResetData(edu.harvard.iq.dataverse.passwordreset.PasswordResetData) BuiltinUser(edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser) NoResultException(javax.persistence.NoResultException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Example 3 with BuiltinUser

use of edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser in project dataverse by IQSS.

the class AuthenticationServiceBean method convertBuiltInUserToRemoteUser.

public AuthenticatedUser convertBuiltInUserToRemoteUser(AuthenticatedUser builtInUserToConvert, String newProviderId, UserIdentifier newUserIdentifierInLookupTable) {
    logger.info("converting user " + builtInUserToConvert.getId() + " from builtin to remote");
    String builtInUserIdentifier = builtInUserToConvert.getIdentifier();
    logger.info("builtin user identifier: " + builtInUserIdentifier);
    TypedQuery<AuthenticatedUserLookup> typedQuery = em.createQuery("SELECT OBJECT(o) FROM AuthenticatedUserLookup AS o WHERE o.authenticatedUser = :auid", AuthenticatedUserLookup.class);
    typedQuery.setParameter("auid", builtInUserToConvert);
    AuthenticatedUserLookup authuserLookup;
    try {
        authuserLookup = typedQuery.getSingleResult();
    } catch (NoResultException | NonUniqueResultException ex) {
        logger.info("exception caught: " + ex);
        return null;
    }
    if (authuserLookup == null) {
        return null;
    }
    String oldProviderId = authuserLookup.getAuthenticationProviderId();
    logger.info("we expect this to be 'builtin': " + oldProviderId);
    authuserLookup.setAuthenticationProviderId(newProviderId);
    String oldUserLookupIdentifier = authuserLookup.getPersistentUserId();
    logger.info("this should be 'pete' or whatever the old builtin username was: " + oldUserLookupIdentifier);
    String perUserIdentifier = newUserIdentifierInLookupTable.getLookupStringPerAuthProvider();
    authuserLookup.setPersistentUserId(perUserIdentifier);
    /**
     * @todo this should be a transaction of some kind. We want to update
     * the authenticateduserlookup and also delete the row from the
     * builtinuser table in a single transaction.
     */
    em.persist(authuserLookup);
    String builtinUsername = builtInUserIdentifier.replaceFirst(AuthenticatedUser.IDENTIFIER_PREFIX, "");
    BuiltinUser builtin = builtinUserServiceBean.findByUserName(builtinUsername);
    if (builtin != null) {
        // These were created by AuthenticationResponse.Status.BREAKOUT in canLogInAsBuiltinUser
        List<PasswordResetData> oldTokens = passwordResetServiceBean.findPasswordResetDataByDataverseUser(builtin);
        for (PasswordResetData oldToken : oldTokens) {
            em.remove(oldToken);
        }
        em.remove(builtin);
    } else {
        logger.info("Couldn't delete builtin user because could find it based on username " + builtinUsername);
    }
    AuthenticatedUser nonBuiltinUser = lookupUser(newProviderId, perUserIdentifier);
    if (nonBuiltinUser != null) {
        return nonBuiltinUser;
    }
    return null;
}
Also used : NonUniqueResultException(javax.persistence.NonUniqueResultException) PasswordResetData(edu.harvard.iq.dataverse.passwordreset.PasswordResetData) BuiltinUser(edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser) NoResultException(javax.persistence.NoResultException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Example 4 with BuiltinUser

use of edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser in project dataverse by IQSS.

the class PasswordResetServiceBean method attemptPasswordReset.

public PasswordChangeAttemptResponse attemptPasswordReset(BuiltinUser user, String newPassword, String token) {
    final String messageSummarySuccess = "Password Reset Successfully";
    final String messageDetailSuccess = "";
    // optimistic defaults :)
    String messageSummary = messageSummarySuccess;
    String messageDetail = messageDetailSuccess;
    final String messageSummaryFail = "Password Reset Problem";
    if (user == null) {
        messageSummary = messageSummaryFail;
        messageDetail = "User could not be found.";
        return new PasswordChangeAttemptResponse(false, messageSummary, messageDetail);
    }
    if (newPassword == null) {
        messageSummary = messageSummaryFail;
        messageDetail = "New password not provided.";
        return new PasswordChangeAttemptResponse(false, messageSummary, messageDetail);
    }
    if (token == null) {
        logger.info("No token provided... won't be able to delete it. Let the user change the password though.");
    }
    List<String> errors = passwordValidatorService.validate(newPassword);
    if (!errors.isEmpty()) {
        messageSummary = PasswordValidatorServiceBean.parseMessages(errors);
        logger.info(messageDetail);
        return new PasswordChangeAttemptResponse(false, messageSummary, messageSummaryFail);
    }
    String newHashedPass = PasswordEncryption.get().encrypt(newPassword);
    int latestVersionNumber = PasswordEncryption.getLatestVersionNumber();
    user.updateEncryptedPassword(newHashedPass, latestVersionNumber);
    BuiltinUser savedUser = dataverseUserService.save(user);
    if (savedUser != null) {
        messageSummary = messageSummarySuccess;
        messageDetail = messageDetailSuccess;
        boolean tokenDeleted = deleteToken(token);
        if (!tokenDeleted) {
            // suboptimal but when it expires it should be deleted
            logger.info("token " + token + " for user id " + user.getId() + " was not deleted");
        }
        String toAddress = user.getEmail();
        String subject = "Dataverse Password Reset Successfully Changed";
        String messageBody = "Hi " + user.getDisplayName() + ",\n\n" + "Your Dataverse account password was successfully changed.\n\n" + "Please contact us if you did not request this password reset or need further help.\n\n";
        mailService.sendSystemEmail(toAddress, subject, messageBody);
        return new PasswordChangeAttemptResponse(true, messageSummary, messageDetail);
    } else {
        messageSummary = messageSummaryFail;
        messageDetail = "Your password was not reset. Please contact support.";
        logger.info("Enable to save user " + user.getId());
        return new PasswordChangeAttemptResponse(false, messageSummary, messageDetail);
    }
}
Also used : BuiltinUser(edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser)

Example 5 with BuiltinUser

use of edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser in project dataverse by IQSS.

the class Admin method convertOAuthUserToBuiltin.

@PUT
@Path("authenticatedUsers/id/{id}/convertRemoteToBuiltIn")
public Response convertOAuthUserToBuiltin(@PathParam("id") Long id, String newEmailAddress) {
    try {
        AuthenticatedUser user = findAuthenticatedUserOrDie();
        if (!user.isSuperuser()) {
            return error(Response.Status.FORBIDDEN, "Superusers only.");
        }
    } catch (WrappedResponse ex) {
        return error(Response.Status.FORBIDDEN, "Superusers only.");
    }
    try {
        BuiltinUser builtinUser = authSvc.convertRemoteToBuiltIn(id, newEmailAddress);
        if (builtinUser == null) {
            return error(Response.Status.BAD_REQUEST, "User id " + id + " could not be converted from remote to BuiltIn. An Exception was not thrown.");
        }
        JsonObjectBuilder output = Json.createObjectBuilder();
        output.add("email", builtinUser.getEmail());
        output.add("username", builtinUser.getUserName());
        return ok(output);
    } catch (Throwable ex) {
        StringBuilder sb = new StringBuilder();
        sb.append(ex + " ");
        while (ex.getCause() != null) {
            ex = ex.getCause();
            sb.append(ex + " ");
        }
        String msg = "User id " + id + " could not be converted from remote to BuiltIn. Details from Exception: " + sb;
        logger.info(msg);
        return error(Response.Status.BAD_REQUEST, msg);
    }
}
Also used : BuiltinUser(edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser) JsonObjectBuilder(javax.json.JsonObjectBuilder) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Path(javax.ws.rs.Path) PUT(javax.ws.rs.PUT)

Aggregations

BuiltinUser (edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser)15 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)10 Path (javax.ws.rs.Path)6 JsonObjectBuilder (javax.json.JsonObjectBuilder)4 PUT (javax.ws.rs.PUT)4 AuthenticatedUserDisplayInfo (edu.harvard.iq.dataverse.authorization.AuthenticatedUserDisplayInfo)3 EJBException (javax.ejb.EJBException)3 NoResultException (javax.persistence.NoResultException)3 NonUniqueResultException (javax.persistence.NonUniqueResultException)3 UserIdentifier (edu.harvard.iq.dataverse.authorization.UserIdentifier)2 AuthenticationFailedException (edu.harvard.iq.dataverse.authorization.exceptions.AuthenticationFailedException)2 PasswordResetData (edu.harvard.iq.dataverse.passwordreset.PasswordResetData)2 FacesMessage (javax.faces.application.FacesMessage)2 JsonArrayBuilder (javax.json.JsonArrayBuilder)2 JsonObject (javax.json.JsonObject)2 ActionLogRecord (edu.harvard.iq.dataverse.actionlogging.ActionLogRecord)1 AuthenticationProviderFactoryNotFoundException (edu.harvard.iq.dataverse.authorization.exceptions.AuthenticationProviderFactoryNotFoundException)1 AuthorizationSetupException (edu.harvard.iq.dataverse.authorization.exceptions.AuthorizationSetupException)1 ShibAuthenticationProvider (edu.harvard.iq.dataverse.authorization.providers.shib.ShibAuthenticationProvider)1 ShibUserNameFields (edu.harvard.iq.dataverse.authorization.providers.shib.ShibUserNameFields)1