Search in sources :

Example 11 with BuiltinUser

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

the class AuthenticationServiceBean method convertRemoteToBuiltIn.

/**
 * @param idOfAuthUserToConvert The id of the remote AuthenticatedUser
 * (Shibboleth user or OAuth user) to convert to a BuiltinUser.
 * @param newEmailAddress The new email address that will be used instead of
 * the user's old email address from the institution that they have left.
 * @return BuiltinUser
 * @throws java.lang.Exception You must catch and report back to the user (a
 * superuser) any Exceptions.
 */
public BuiltinUser convertRemoteToBuiltIn(Long idOfAuthUserToConvert, String newEmailAddress) throws Exception {
    AuthenticatedUser authenticatedUser = findByID(idOfAuthUserToConvert);
    if (authenticatedUser == null) {
        throw new Exception("User id " + idOfAuthUserToConvert + " not found.");
    }
    AuthenticatedUser existingUserWithSameEmail = getAuthenticatedUserByEmail(newEmailAddress);
    if (existingUserWithSameEmail != null) {
        throw new Exception("User id " + idOfAuthUserToConvert + " (" + authenticatedUser.getIdentifier() + ") cannot be converted from remote to BuiltIn because the email address " + newEmailAddress + " is already in use by user id " + existingUserWithSameEmail.getId() + " (" + existingUserWithSameEmail.getIdentifier() + ").");
    }
    BuiltinUser builtinUser = new BuiltinUser();
    builtinUser.setUserName(authenticatedUser.getUserIdentifier());
    builtinUser.setFirstName(authenticatedUser.getFirstName());
    builtinUser.setLastName(authenticatedUser.getLastName());
    // Bean Validation will check for null and invalid email addresses
    builtinUser.setEmail(newEmailAddress);
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<BuiltinUser>> violations = validator.validate(builtinUser);
    int numViolations = violations.size();
    if (numViolations > 0) {
        StringBuilder logMsg = new StringBuilder();
        for (ConstraintViolation<?> violation : violations) {
            logMsg.append(" Invalid value: <<<").append(violation.getInvalidValue()).append(">>> for ").append(violation.getPropertyPath()).append(" at ").append(violation.getLeafBean()).append(" - ").append(violation.getMessage());
        }
        throw new Exception("User id " + idOfAuthUserToConvert + " cannot be converted from remote to BuiltIn because of constraint violations on the BuiltIn user that would be created: " + numViolations + ". Details: " + logMsg);
    }
    try {
        builtinUser = builtinUserServiceBean.save(builtinUser);
    } catch (IllegalArgumentException ex) {
        throw new Exception("User id " + idOfAuthUserToConvert + " cannot be converted from remote to BuiltIn because of an IllegalArgumentException creating the row in the builtinuser table: " + ex);
    }
    AuthenticatedUserLookup lookup = authenticatedUser.getAuthenticatedUserLookup();
    if (lookup == null) {
        throw new Exception("User id " + idOfAuthUserToConvert + " does not have an 'authenticateduserlookup' row");
    }
    String providerId = lookup.getAuthenticationProviderId();
    if (providerId == null) {
        throw new Exception("User id " + idOfAuthUserToConvert + " provider id is null.");
    }
    String builtinProviderId = BuiltinAuthenticationProvider.PROVIDER_ID;
    if (providerId.equals(builtinProviderId)) {
        throw new Exception("User id " + idOfAuthUserToConvert + " cannot be converted from remote to BuiltIn because current provider id is '" + providerId + "' which is the same as '" + builtinProviderId + "'. This user is already a BuiltIn user.");
    }
    lookup.setAuthenticationProviderId(BuiltinAuthenticationProvider.PROVIDER_ID);
    lookup.setPersistentUserId(authenticatedUser.getUserIdentifier());
    em.persist(lookup);
    authenticatedUser.setEmail(newEmailAddress);
    em.persist(authenticatedUser);
    em.flush();
    return builtinUser;
}
Also used : BuiltinUser(edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser) ValidatorFactory(javax.validation.ValidatorFactory) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) NoResultException(javax.persistence.NoResultException) NonUniqueResultException(javax.persistence.NonUniqueResultException) AuthenticationProviderFactoryNotFoundException(edu.harvard.iq.dataverse.authorization.exceptions.AuthenticationProviderFactoryNotFoundException) EJBException(javax.ejb.EJBException) AuthorizationSetupException(edu.harvard.iq.dataverse.authorization.exceptions.AuthorizationSetupException) AuthenticationFailedException(edu.harvard.iq.dataverse.authorization.exceptions.AuthenticationFailedException) ConstraintViolation(javax.validation.ConstraintViolation) Validator(javax.validation.Validator)

Example 12 with BuiltinUser

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

the class Admin method convertUserFromBcryptToSha1.

/**
 * This method is used by an integration test in UsersIT.java to exercise
 * bug https://github.com/IQSS/dataverse/issues/3287 . Not for use by users!
 */
@Path("convertUserFromBcryptToSha1")
@POST
public Response convertUserFromBcryptToSha1(String json) {
    JsonReader jsonReader = Json.createReader(new StringReader(json));
    JsonObject object = jsonReader.readObject();
    jsonReader.close();
    BuiltinUser builtinUser = builtinUserService.find(new Long(object.getInt("builtinUserId")));
    // password is "sha-1Pass", 0 means SHA-1
    builtinUser.updateEncryptedPassword("4G7xxL9z11/JKN4jHPn4g9iIQck=", 0);
    BuiltinUser savedUser = builtinUserService.save(builtinUser);
    return ok("foo: " + savedUser);
}
Also used : BuiltinUser(edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser) StringReader(java.io.StringReader) JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 13 with BuiltinUser

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

the class BuiltinUsers method getApiToken.

@GET
@Path("{username}/api-token")
public Response getApiToken(@PathParam("username") String username, @QueryParam("password") String password) {
    boolean disabled = true;
    boolean lookupAllowed = settingsSvc.isTrueForKey(SettingsServiceBean.Key.AllowApiTokenLookupViaApi, false);
    if (lookupAllowed) {
        disabled = false;
    }
    if (disabled) {
        return error(Status.FORBIDDEN, "This API endpoint has been disabled.");
    }
    BuiltinUser u = null;
    if (retrievingApiTokenViaEmailEnabled) {
        u = builtinUserSvc.findByUsernameOrEmail(username);
    } else {
        u = builtinUserSvc.findByUserName(username);
    }
    if (u == null)
        return badRequest("Bad username or password");
    boolean passwordOk = PasswordEncryption.getVersion(u.getPasswordEncryptionVersion()).check(password, u.getEncryptedPassword());
    if (!passwordOk)
        return badRequest("Bad username or password");
    AuthenticatedUser authUser = authSvc.lookupUser(BuiltinAuthenticationProvider.PROVIDER_ID, u.getUserName());
    ApiToken t = authSvc.findApiTokenByUser(authUser);
    return (t != null) ? ok(t.getTokenString()) : notFound("User " + username + " does not have an API token");
}
Also used : BuiltinUser(edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser) ApiToken(edu.harvard.iq.dataverse.authorization.users.ApiToken) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 14 with BuiltinUser

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

the class PasswordResetServiceBean method requestReset.

/**
 * Initiate the password reset process.
 *
 * @param emailAddress
 * @return {@link PasswordResetInitResponse}
 * @throws edu.harvard.iq.dataverse.passwordreset.PasswordResetException
 */
// inspired by Troy Hunt: Everything you ever wanted to know about building a secure password reset feature - http://www.troyhunt.com/2012/05/everything-you-ever-wanted-to-know.html
public PasswordResetInitResponse requestReset(String emailAddress) throws PasswordResetException {
    deleteAllExpiredTokens();
    BuiltinUser user = dataverseUserService.findByEmail(emailAddress);
    if (user != null) {
        return requestPasswordReset(user, true, PasswordResetData.Reason.FORGOT_PASSWORD);
    } else {
        return new PasswordResetInitResponse(false);
    }
}
Also used : BuiltinUser(edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser)

Example 15 with BuiltinUser

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

the class PasswordResetPage method sendPasswordResetLink.

public String sendPasswordResetLink() {
    actionLogSvc.log(new ActionLogRecord(ActionLogRecord.ActionType.BuiltinUser, "passwordResetRequest").setInfo("Email Address: " + emailAddress));
    try {
        PasswordResetInitResponse passwordResetInitResponse = passwordResetService.requestReset(emailAddress);
        PasswordResetData passwordResetData = passwordResetInitResponse.getPasswordResetData();
        if (passwordResetData != null) {
            BuiltinUser foundUser = passwordResetData.getBuiltinUser();
            passwordResetUrl = passwordResetInitResponse.getResetUrl();
            actionLogSvc.log(new ActionLogRecord(ActionLogRecord.ActionType.BuiltinUser, "passwordResetSent").setInfo("Email Address: " + emailAddress));
        } else {
            /**
             * @todo remove "single" when it's no longer necessary. See
             * https://github.com/IQSS/dataverse/issues/844 and
             * https://github.com/IQSS/dataverse/issues/1141
             */
            logger.log(Level.INFO, "Couldn''t find single account using {0}", emailAddress);
        }
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Password Reset Initiated", ""));
    } catch (PasswordResetException ex) {
        /**
         * @todo do we really need a special exception for this??
         */
        logger.log(Level.WARNING, "Error While resetting password: " + ex.getMessage(), ex);
    }
    return "";
}
Also used : ActionLogRecord(edu.harvard.iq.dataverse.actionlogging.ActionLogRecord) BuiltinUser(edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser) FacesMessage(javax.faces.application.FacesMessage)

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