Search in sources :

Example 51 with AuthenticatedUser

use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser 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 52 with AuthenticatedUser

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

the class ManageFilePermissionsPage method grantAccess.

public void grantAccess(ActionEvent evt) {
    // Find the built in file downloader role (currently by alias)
    DataverseRole fileDownloaderRole = roleService.findBuiltinRoleByAlias(DataverseRole.FILE_DOWNLOADER);
    for (RoleAssignee roleAssignee : selectedRoleAssignees) {
        boolean sendNotification = false;
        for (DataFile file : selectedFiles) {
            if (assignRole(roleAssignee, file, fileDownloaderRole)) {
                if (file.isReleased()) {
                    sendNotification = true;
                }
                // remove request, if it exist
                if (file.getFileAccessRequesters().remove(roleAssignee)) {
                    datafileService.save(file);
                }
            }
        }
        if (sendNotification) {
            for (AuthenticatedUser au : roleAssigneeService.getExplicitUsers(roleAssignee)) {
                userNotificationService.sendNotification(au, new Timestamp(new Date().getTime()), UserNotification.Type.GRANTFILEACCESS, dataset.getId());
            }
        }
    }
    initMaps();
}
Also used : AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Timestamp(java.sql.Timestamp) Date(java.util.Date) DataverseRole(edu.harvard.iq.dataverse.authorization.DataverseRole) RoleAssignee(edu.harvard.iq.dataverse.authorization.RoleAssignee)

Example 53 with AuthenticatedUser

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

the class RoleAssigneeServiceBean method getAssigneeDataverseRoleFor.

public List<DataverseRole> getAssigneeDataverseRoleFor(DataverseRequest dataverseRequest) {
    if (dataverseRequest == null) {
        throw new NullPointerException("dataverseRequest cannot be null!");
    }
    AuthenticatedUser au = dataverseRequest.getAuthenticatedUser();
    if (au.getUserIdentifier() == null) {
        return null;
    }
    String roleAssigneeIdentifier = "@" + au.getUserIdentifier();
    List<DataverseRole> retList = new ArrayList<>();
    // remove spaces from string
    roleAssigneeIdentifier = roleAssigneeIdentifier.replaceAll("\\s", "");
    List<String> userGroups = getUserExplicitGroups(au);
    List<String> userRunTimeGroups = getUserRuntimeGroups(dataverseRequest);
    String identifierClause = " WHERE r.assigneeIdentifier= '" + roleAssigneeIdentifier + "'";
    if (userGroups != null || userRunTimeGroups != null) {
        identifierClause = getGroupIdentifierClause(roleAssigneeIdentifier, userGroups, userRunTimeGroups);
    }
    String qstr = "SELECT distinct r.role_id";
    qstr += " FROM RoleAssignment r";
    qstr += identifierClause;
    qstr += ";";
    msg("qstr: " + qstr);
    for (Object o : em.createNativeQuery(qstr).getResultList()) {
        retList.add(dataverseRoleService.find((Long) o));
    }
    return retList;
}
Also used : ArrayList(java.util.ArrayList) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) DataverseRole(edu.harvard.iq.dataverse.authorization.DataverseRole)

Example 54 with AuthenticatedUser

use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser 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 55 with AuthenticatedUser

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

the class Shib method init.

public void init() {
    state = State.INIT;
    ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
    request = (HttpServletRequest) context.getRequest();
    ShibUtil.printAttributes(request);
    /**
     * @todo Investigate why JkEnvVar is null since it may be useful for
     * debugging per https://github.com/IQSS/dataverse/issues/2916 . See
     * also
     * http://stackoverflow.com/questions/30193117/iterate-through-all-servletrequest-attributes#comment49933342_30193117
     * and
     * http://shibboleth.1660669.n2.nabble.com/Why-doesn-t-Java-s-request-getAttributeNames-show-Shibboleth-attributes-tp7616427p7616591.html
     */
    logger.fine("JkEnvVar: " + System.getenv("JkEnvVar"));
    shibService.possiblyMutateRequestInDev(request);
    try {
        shibIdp = getRequiredValueFromAssertion(ShibUtil.shibIdpAttribute);
    } catch (Exception ex) {
        /**
         * @todo is in an antipattern to throw exceptions to control flow?
         * http://c2.com/cgi/wiki?DontUseExceptionsForFlowControl
         *
         * All this exception handling should be handled in the new
         * ShibServiceBean so it's consistently handled by the API as well.
         */
        return;
    }
    String shibUserIdentifier;
    try {
        shibUserIdentifier = getRequiredValueFromAssertion(ShibUtil.uniquePersistentIdentifier);
    } catch (Exception ex) {
        return;
    }
    String firstName;
    try {
        firstName = getRequiredValueFromAssertion(ShibUtil.firstNameAttribute);
    } catch (Exception ex) {
        return;
    }
    String lastName;
    try {
        lastName = getRequiredValueFromAssertion(ShibUtil.lastNameAttribute);
    } catch (Exception ex) {
        return;
    }
    ShibUserNameFields shibUserNameFields = ShibUtil.findBestFirstAndLastName(firstName, lastName, null);
    if (shibUserNameFields != null) {
        String betterFirstName = shibUserNameFields.getFirstName();
        if (betterFirstName != null) {
            firstName = betterFirstName;
        }
        String betterLastName = shibUserNameFields.getLastName();
        if (betterLastName != null) {
            lastName = betterLastName;
        }
    }
    String emailAddressInAssertion = null;
    try {
        emailAddressInAssertion = getRequiredValueFromAssertion(ShibUtil.emailAttribute);
    } catch (Exception ex) {
        if (shibIdp.equals(ShibUtil.testShibIdpEntityId)) {
            logger.info("For " + shibIdp + " (which as of this writing doesn't provide the " + ShibUtil.emailAttribute + " attribute) setting email address to value of eppn: " + shibUserIdentifier);
            emailAddressInAssertion = shibUserIdentifier;
        } else {
            // forcing all other IdPs to send us an an email
            return;
        }
    }
    if (!EMailValidator.isEmailValid(emailAddressInAssertion, null)) {
        String msg = "The SAML assertion contained an invalid email address: \"" + emailAddressInAssertion + "\".";
        logger.info(msg);
        String singleEmailAddress = ShibUtil.findSingleValue(emailAddressInAssertion);
        if (EMailValidator.isEmailValid(singleEmailAddress, null)) {
            msg = "Multiple email addresses were asserted by the Identity Provider (" + emailAddressInAssertion + " ). These were sorted and the first was chosen: " + singleEmailAddress;
            logger.info(msg);
            emailAddress = singleEmailAddress;
        } else {
            msg += " A single valid address could not be found.";
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, identityProviderProblem, msg));
            return;
        }
    } else {
        emailAddress = emailAddressInAssertion;
    }
    String usernameAssertion = getValueFromAssertion(ShibUtil.usernameAttribute);
    internalUserIdentifer = ShibUtil.generateFriendlyLookingUserIdentifer(usernameAssertion, emailAddress);
    logger.fine("friendly looking identifer (backend will enforce uniqueness):" + internalUserIdentifer);
    String affiliation = shibService.getAffiliation(shibIdp, shibService.getDevShibAccountType());
    if (affiliation != null) {
        affiliationToDisplayAtConfirmation = affiliation;
        friendlyNameForInstitution = affiliation;
    }
    // emailAddress = "willFailBeanValidation"; // for testing createAuthenticatedUser exceptions
    displayInfo = new AuthenticatedUserDisplayInfo(firstName, lastName, emailAddress, affiliation, null);
    userPersistentId = shibIdp + persistentUserIdSeparator + shibUserIdentifier;
    ShibAuthenticationProvider shibAuthProvider = new ShibAuthenticationProvider();
    AuthenticatedUser au = authSvc.lookupUser(shibAuthProvider.getId(), userPersistentId);
    if (au != null) {
        state = State.REGULAR_LOGIN_INTO_EXISTING_SHIB_ACCOUNT;
        logger.fine("Found user based on " + userPersistentId + ". Logging in.");
        logger.fine("Updating display info for " + au.getName());
        authSvc.updateAuthenticatedUser(au, displayInfo);
        logInUserAndSetShibAttributes(au);
        String prettyFacesHomePageString = getPrettyFacesHomePageString(false);
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect(prettyFacesHomePageString);
        } catch (IOException ex) {
            logger.info("Unable to redirect user to homepage at " + prettyFacesHomePageString);
        }
    } else {
        state = State.PROMPT_TO_CREATE_NEW_ACCOUNT;
        displayNameToPersist = displayInfo.getTitle();
        emailToPersist = emailAddress;
        /**
         * @todo for Harvard we plan to use the value(s) from
         * eduPersonScopedAffiliation which
         * http://iam.harvard.edu/resources/saml-shibboleth-attributes says
         * can be One or more of the following values: faculty, staff,
         * student, affiliate, and member.
         *
         * http://dataverse.nl plans to use
         * urn:mace:dir:attribute-def:eduPersonAffiliation per
         * http://irclog.iq.harvard.edu/dataverse/2015-02-13#i_16265 . Can
         * they configure shibd to map eduPersonAffiliation to
         * eduPersonScopedAffiliation?
         */
        // positionToPersist = "FIXME";
        logger.fine("Couldn't find authenticated user based on " + userPersistentId);
        visibleTermsOfUse = true;
        /**
         * Using the email address from the IdP, try to find an existing
         * user. For TestShib we convert the "eppn" to an email address.
         *
         * If found, prompt for password and offer to convert.
         *
         * If not found, create a new account. It must be a new user.
         */
        String emailAddressToLookUp = emailAddress;
        if (existingEmail != null) {
            emailAddressToLookUp = existingEmail;
        }
        AuthenticatedUser existingAuthUserFoundByEmail = shibService.findAuthUserByEmail(emailAddressToLookUp);
        BuiltinUser existingBuiltInUserFoundByEmail = null;
        if (existingAuthUserFoundByEmail != null) {
            existingDisplayName = existingAuthUserFoundByEmail.getName();
            existingBuiltInUserFoundByEmail = shibService.findBuiltInUserByAuthUserIdentifier(existingAuthUserFoundByEmail.getUserIdentifier());
            if (existingBuiltInUserFoundByEmail != null) {
                state = State.PROMPT_TO_CONVERT_EXISTING_ACCOUNT;
                existingDisplayName = existingBuiltInUserFoundByEmail.getDisplayName();
                debugSummary = "getting username from the builtin user we looked up via email";
                builtinUsername = existingBuiltInUserFoundByEmail.getUserName();
            } else {
                debugSummary = "Could not find a builtin account based on the username. Here we should simply create a new Shibboleth user";
            }
        } else {
            debugSummary = "Could not find an auth user based on email address";
        }
    }
    logger.fine("Debug summary: " + debugSummary + " (state: " + state + ").");
    logger.fine("redirectPage: " + redirectPage);
}
Also used : ShibUserNameFields(edu.harvard.iq.dataverse.authorization.providers.shib.ShibUserNameFields) AuthenticatedUserDisplayInfo(edu.harvard.iq.dataverse.authorization.AuthenticatedUserDisplayInfo) ShibAuthenticationProvider(edu.harvard.iq.dataverse.authorization.providers.shib.ShibAuthenticationProvider) BuiltinUser(edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser) ExternalContext(javax.faces.context.ExternalContext) IOException(java.io.IOException) FacesMessage(javax.faces.application.FacesMessage) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) IOException(java.io.IOException) EJBException(javax.ejb.EJBException)

Aggregations

AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)125 Dataverse (edu.harvard.iq.dataverse.Dataverse)24 Timestamp (java.sql.Timestamp)24 Date (java.util.Date)24 CommandException (edu.harvard.iq.dataverse.engine.command.exception.CommandException)23 Dataset (edu.harvard.iq.dataverse.Dataset)22 DataverseRequest (edu.harvard.iq.dataverse.engine.command.DataverseRequest)21 Path (javax.ws.rs.Path)19 EJBException (javax.ejb.EJBException)16 ArrayList (java.util.ArrayList)14 User (edu.harvard.iq.dataverse.authorization.users.User)13 DataFile (edu.harvard.iq.dataverse.DataFile)11 IOException (java.io.IOException)11 JsonObjectBuilder (javax.json.JsonObjectBuilder)11 POST (javax.ws.rs.POST)11 Test (org.junit.Test)11 BuiltinUser (edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser)10 SwordError (org.swordapp.server.SwordError)10 DataverseRole (edu.harvard.iq.dataverse.authorization.DataverseRole)8 PermissionException (edu.harvard.iq.dataverse.engine.command.exception.PermissionException)8