Search in sources :

Example 1 with UserRecordIdentifier

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

the class DataverseUserPage method save.

public String save() {
    boolean passwordChanged = false;
    if (editMode == EditMode.CHANGE_PASSWORD) {
        final AuthenticationProvider prv = getUserAuthProvider();
        if (prv.isPasswordUpdateAllowed()) {
            if (!prv.verifyPassword(currentUser.getAuthenticatedUserLookup().getPersistentUserId(), currentPassword)) {
                FacesContext.getCurrentInstance().addMessage("currentPassword", new FacesMessage(FacesMessage.SEVERITY_ERROR, BundleUtil.getStringFromBundle("user.error.wrongPassword"), null));
                return null;
            }
            prv.updatePassword(currentUser.getAuthenticatedUserLookup().getPersistentUserId(), inputPassword);
            passwordChanged = true;
        } else {
            // erroneous state - we can't change the password for this user, so should not have gotten here. Log and bail out.
            logger.log(Level.WARNING, "Attempt to change a password on {0}, whose provider ({1}) does not support password change", new Object[] { currentUser.getIdentifier(), prv });
            JH.addMessage(FacesMessage.SEVERITY_ERROR, BundleUtil.getStringFromBundle("user.error.cannotChangePassword"));
            return null;
        }
    }
    if (editMode == EditMode.CREATE) {
        // Create a new built-in user.
        BuiltinUser builtinUser = new BuiltinUser();
        builtinUser.setUserName(getUsername());
        builtinUser.applyDisplayInfo(userDisplayInfo);
        builtinUser.updateEncryptedPassword(PasswordEncryption.get().encrypt(inputPassword), PasswordEncryption.getLatestVersionNumber());
        AuthenticatedUser au = authenticationService.createAuthenticatedUser(new UserRecordIdentifier(BuiltinAuthenticationProvider.PROVIDER_ID, builtinUser.getUserName()), builtinUser.getUserName(), builtinUser.getDisplayInfo(), false);
        if (au == null) {
            // Username already exists, show an error message
            getUsernameField().setValid(false);
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, BundleUtil.getStringFromBundle("user.username.taken"), null);
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(getUsernameField().getClientId(context), message);
            return null;
        }
        // The Authenticated User was just created via the UI, add an initial login timestamp
        au = userService.updateLastLogin(au);
        // Authenticated user registered. Save the new bulitin, and log in.
        builtinUserService.save(builtinUser);
        session.setUser(au);
        /**
         * @todo Move this to
         * AuthenticationServiceBean.createAuthenticatedUser
         */
        userNotificationService.sendNotification(au, new Timestamp(new Date().getTime()), UserNotification.Type.CREATEACC, null);
        // go back to where user came from
        if ("dataverse.xhtml".equals(redirectPage)) {
            redirectPage = redirectPage + "?alias=" + dataverseService.findRootDataverse().getAlias();
        }
        try {
            redirectPage = URLDecoder.decode(redirectPage, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            logger.log(Level.SEVERE, "Server does not support 'UTF-8' encoding.", ex);
            redirectPage = "dataverse.xhtml?alias=" + dataverseService.findRootDataverse().getAlias();
        }
        logger.log(Level.FINE, "Sending user to = {0}", redirectPage);
        return redirectPage + (!redirectPage.contains("?") ? "?" : "&") + "faces-redirect=true";
    // Happens if user is logged out while editing
    } else if (!session.getUser().isAuthenticated()) {
        logger.info("Redirecting");
        return permissionsWrapper.notAuthorized() + "faces-redirect=true";
    } else {
        String emailBeforeUpdate = currentUser.getEmail();
        AuthenticatedUser savedUser = authenticationService.updateAuthenticatedUser(currentUser, userDisplayInfo);
        String emailAfterUpdate = savedUser.getEmail();
        editMode = null;
        StringBuilder msg = new StringBuilder(passwordChanged ? "Your account password has been successfully changed." : "Your account information has been successfully updated.");
        if (!emailBeforeUpdate.equals(emailAfterUpdate)) {
            String expTime = ConfirmEmailUtil.friendlyExpirationTime(systemConfig.getMinutesUntilConfirmEmailTokenExpires());
            msg.append(" Your email address has changed and must be re-verified. Please check your inbox at ").append(currentUser.getEmail()).append(" and follow the link we've sent. \n\nAlso, please note that the link will only work for the next ").append(expTime).append(" before it has expired.");
            // delete unexpired token, if it exists (clean slate)
            confirmEmailService.deleteTokenForUser(currentUser);
            try {
                confirmEmailService.beginConfirm(currentUser);
            } catch (ConfirmEmailException ex) {
                logger.log(Level.INFO, "Unable to send email confirmation link to user id {0}", savedUser.getId());
            }
            session.setUser(currentUser);
            JsfHelper.addSuccessMessage(msg.toString());
        } else {
            JsfHelper.addFlashMessage(msg.toString());
        }
        return null;
    }
}
Also used : FacesContext(javax.faces.context.FacesContext) UserRecordIdentifier(edu.harvard.iq.dataverse.authorization.UserRecordIdentifier) AuthenticationProvider(edu.harvard.iq.dataverse.authorization.AuthenticationProvider) ShibAuthenticationProvider(edu.harvard.iq.dataverse.authorization.providers.shib.ShibAuthenticationProvider) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Timestamp(java.sql.Timestamp) Date(java.util.Date) ConfirmEmailException(edu.harvard.iq.dataverse.confirmemail.ConfirmEmailException) FacesMessage(javax.faces.application.FacesMessage)

Example 2 with UserRecordIdentifier

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

the class Shib method confirmAndCreateAccount.

public String confirmAndCreateAccount() {
    ShibAuthenticationProvider shibAuthProvider = new ShibAuthenticationProvider();
    String lookupStringPerAuthProvider = userPersistentId;
    AuthenticatedUser au = null;
    try {
        au = authSvc.createAuthenticatedUser(new UserRecordIdentifier(shibAuthProvider.getId(), lookupStringPerAuthProvider), internalUserIdentifer, displayInfo, true);
    } catch (EJBException ex) {
        /**
         * @todo Show the ConstraintViolationException, if any.
         */
        logger.info("Couldn't create user " + userPersistentId + " due to exception: " + ex.getCause());
    }
    if (au != null) {
        logger.fine("created user " + au.getIdentifier());
        logInUserAndSetShibAttributes(au);
        /**
         * @todo Move this to
         * AuthenticationServiceBean.createAuthenticatedUser
         */
        userNotificationService.sendNotification(au, new Timestamp(new Date().getTime()), UserNotification.Type.CREATEACC, null);
        return "/dataverseuser.xhtml?selectTab=accountInfo&faces-redirect=true";
    } else {
        JsfHelper.addErrorMessage("Couldn't create user.");
    }
    return getPrettyFacesHomePageString(true);
}
Also used : ShibAuthenticationProvider(edu.harvard.iq.dataverse.authorization.providers.shib.ShibAuthenticationProvider) UserRecordIdentifier(edu.harvard.iq.dataverse.authorization.UserRecordIdentifier) EJBException(javax.ejb.EJBException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Timestamp(java.sql.Timestamp) Date(java.util.Date)

Example 3 with UserRecordIdentifier

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

the class Admin method createAuthenicatedUser.

/**
 * @todo Make this support creation of BuiltInUsers.
 *
 * @todo Add way more error checking. Only the happy path is tested by
 * AdminIT.
 */
@POST
@Path("authenticatedUsers")
public Response createAuthenicatedUser(JsonObject jsonObject) {
    logger.fine("JSON in: " + jsonObject);
    String persistentUserId = jsonObject.getString("persistentUserId");
    String identifier = jsonObject.getString("identifier");
    String proposedAuthenticatedUserIdentifier = identifier.replaceFirst("@", "");
    String firstName = jsonObject.getString("firstName");
    String lastName = jsonObject.getString("lastName");
    String emailAddress = jsonObject.getString("email");
    String position = null;
    String affiliation = null;
    UserRecordIdentifier userRecordId = new UserRecordIdentifier(jsonObject.getString("authenticationProviderId"), persistentUserId);
    AuthenticatedUserDisplayInfo userDisplayInfo = new AuthenticatedUserDisplayInfo(firstName, lastName, emailAddress, affiliation, position);
    boolean generateUniqueIdentifier = true;
    AuthenticatedUser authenticatedUser = authSvc.createAuthenticatedUser(userRecordId, proposedAuthenticatedUserIdentifier, userDisplayInfo, true);
    return ok(json(authenticatedUser));
}
Also used : AuthenticatedUserDisplayInfo(edu.harvard.iq.dataverse.authorization.AuthenticatedUserDisplayInfo) UserRecordIdentifier(edu.harvard.iq.dataverse.authorization.UserRecordIdentifier) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 4 with UserRecordIdentifier

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

the class BuiltinUsers method internalSave.

private Response internalSave(BuiltinUser user, String password, String key) {
    String expectedKey = settingsSvc.get(API_KEY_IN_SETTINGS);
    if (expectedKey == null) {
        return error(Status.SERVICE_UNAVAILABLE, "Dataverse config issue: No API key defined for built in user management");
    }
    if (!expectedKey.equals(key)) {
        return badApiKey(key);
    }
    ActionLogRecord alr = new ActionLogRecord(ActionLogRecord.ActionType.BuiltinUser, "create");
    try {
        if (password != null) {
            user.updateEncryptedPassword(PasswordEncryption.get().encrypt(password), PasswordEncryption.getLatestVersionNumber());
        }
        // Make sure the identifier is unique
        if ((builtinUserSvc.findByUserName(user.getUserName()) != null) || (authSvc.identifierExists(user.getUserName()))) {
            return error(Status.BAD_REQUEST, "username '" + user.getUserName() + "' already exists");
        }
        user = builtinUserSvc.save(user);
        AuthenticatedUser au = authSvc.createAuthenticatedUser(new UserRecordIdentifier(BuiltinAuthenticationProvider.PROVIDER_ID, user.getUserName()), user.getUserName(), user.getDisplayInfo(), false);
        /**
         * @todo Move this to
         * AuthenticationServiceBean.createAuthenticatedUser
         */
        boolean rootDataversePresent = false;
        try {
            Dataverse rootDataverse = dataverseSvc.findRootDataverse();
            if (rootDataverse != null) {
                rootDataversePresent = true;
            }
        } catch (Exception e) {
            logger.info("The root dataverse is not present. Don't send a notification to dataverseAdmin.");
        }
        if (rootDataversePresent) {
            userNotificationSvc.sendNotification(au, new Timestamp(new Date().getTime()), UserNotification.Type.CREATEACC, null);
        }
        ApiToken token = new ApiToken();
        token.setTokenString(java.util.UUID.randomUUID().toString());
        token.setAuthenticatedUser(au);
        Calendar c = Calendar.getInstance();
        token.setCreateTime(new Timestamp(c.getTimeInMillis()));
        c.roll(Calendar.YEAR, 1);
        token.setExpireTime(new Timestamp(c.getTimeInMillis()));
        authSvc.save(token);
        JsonObjectBuilder resp = Json.createObjectBuilder();
        resp.add("user", json(user));
        resp.add("authenticatedUser", json(au));
        resp.add("apiToken", token.getTokenString());
        alr.setInfo("builtinUser:" + user.getUserName() + " authenticatedUser:" + au.getIdentifier());
        return ok(resp);
    } catch (EJBException ejbx) {
        alr.setActionResult(ActionLogRecord.Result.InternalError);
        alr.setInfo(alr.getInfo() + "// " + ejbx.getMessage());
        if (ejbx.getCausedByException() instanceof IllegalArgumentException) {
            return error(Status.BAD_REQUEST, "Bad request: can't save user. " + ejbx.getCausedByException().getMessage());
        } else {
            logger.log(Level.WARNING, "Error saving user: ", ejbx);
            return error(Status.INTERNAL_SERVER_ERROR, "Can't save user: " + ejbx.getMessage());
        }
    } catch (Exception e) {
        logger.log(Level.WARNING, "Error saving user", e);
        alr.setActionResult(ActionLogRecord.Result.InternalError);
        alr.setInfo(alr.getInfo() + "// " + e.getMessage());
        return error(Status.INTERNAL_SERVER_ERROR, "Can't save user: " + e.getMessage());
    } finally {
        actionLogSvc.log(alr);
    }
}
Also used : UserRecordIdentifier(edu.harvard.iq.dataverse.authorization.UserRecordIdentifier) Calendar(java.util.Calendar) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Dataverse(edu.harvard.iq.dataverse.Dataverse) Timestamp(java.sql.Timestamp) EJBException(javax.ejb.EJBException) Date(java.util.Date) ActionLogRecord(edu.harvard.iq.dataverse.actionlogging.ActionLogRecord) ApiToken(edu.harvard.iq.dataverse.authorization.users.ApiToken) JsonObjectBuilder(javax.json.JsonObjectBuilder) EJBException(javax.ejb.EJBException)

Example 5 with UserRecordIdentifier

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

the class OAuth2LoginBackingBean method exchangeCodeForToken.

public void exchangeCodeForToken() throws IOException {
    HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    final String code = req.getParameter("code");
    if (code == null || code.trim().isEmpty()) {
        try (BufferedReader rdr = req.getReader()) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = rdr.readLine()) != null) {
                sb.append(line).append("\n");
            }
            error = new OAuth2Exception(-1, sb.toString(), "Remote system did not return an authorization code.");
            logger.log(Level.INFO, "OAuth2Exception getting code parameter. HTTP return code: {0}. Message: {1} Message body: {2}", new Object[] { error.getHttpReturnCode(), error.getLocalizedMessage(), error.getMessageBody() });
            return;
        }
    }
    final String state = req.getParameter("state");
    try {
        AbstractOAuth2AuthenticationProvider idp = parseState(state);
        if (idp == null) {
            throw new OAuth2Exception(-1, "", "Invalid 'state' parameter.");
        }
        oauthUser = idp.getUserRecord(code, state, getCallbackUrl());
        UserRecordIdentifier idtf = oauthUser.getUserRecordIdentifier();
        AuthenticatedUser dvUser = authenticationSvc.lookupUser(idtf);
        if (dvUser == null) {
            // need to create the user
            newAccountPage.setNewUser(oauthUser);
            FacesContext.getCurrentInstance().getExternalContext().redirect("/oauth2/firstLogin.xhtml");
        } else {
            // login the user and redirect to HOME of intended page (if any).
            session.setUser(dvUser);
            final OAuth2TokenData tokenData = oauthUser.getTokenData();
            tokenData.setUser(dvUser);
            tokenData.setOauthProviderId(idp.getId());
            oauth2Tokens.store(tokenData);
            String destination = redirectPage.orElse("/");
            HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
            String prettyUrl = response.encodeRedirectURL(destination);
            FacesContext.getCurrentInstance().getExternalContext().redirect(prettyUrl);
        }
    } catch (OAuth2Exception ex) {
        error = ex;
        logger.log(Level.INFO, "OAuth2Exception caught. HTTP return code: {0}. Message: {1}. Message body: {2}", new Object[] { error.getHttpReturnCode(), error.getLocalizedMessage(), error.getMessageBody() });
        Logger.getLogger(OAuth2LoginBackingBean.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) UserRecordIdentifier(edu.harvard.iq.dataverse.authorization.UserRecordIdentifier) BufferedReader(java.io.BufferedReader) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Aggregations

UserRecordIdentifier (edu.harvard.iq.dataverse.authorization.UserRecordIdentifier)5 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)5 Timestamp (java.sql.Timestamp)3 Date (java.util.Date)3 ShibAuthenticationProvider (edu.harvard.iq.dataverse.authorization.providers.shib.ShibAuthenticationProvider)2 EJBException (javax.ejb.EJBException)2 Dataverse (edu.harvard.iq.dataverse.Dataverse)1 ActionLogRecord (edu.harvard.iq.dataverse.actionlogging.ActionLogRecord)1 AuthenticatedUserDisplayInfo (edu.harvard.iq.dataverse.authorization.AuthenticatedUserDisplayInfo)1 AuthenticationProvider (edu.harvard.iq.dataverse.authorization.AuthenticationProvider)1 ApiToken (edu.harvard.iq.dataverse.authorization.users.ApiToken)1 ConfirmEmailException (edu.harvard.iq.dataverse.confirmemail.ConfirmEmailException)1 BufferedReader (java.io.BufferedReader)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 Calendar (java.util.Calendar)1 FacesMessage (javax.faces.application.FacesMessage)1 FacesContext (javax.faces.context.FacesContext)1 JsonObjectBuilder (javax.json.JsonObjectBuilder)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1