Search in sources :

Example 46 with AuthenticatedUser

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

the class Admin method builtin2oauth.

/**
 * This is used in testing via AdminIT.java but we don't expect sysadmins to
 * use this.
 */
@Path("authenticatedUsers/convert/builtin2oauth")
@PUT
public Response builtin2oauth(String content) {
    logger.info("entering builtin2oauth...");
    try {
        AuthenticatedUser userToRunThisMethod = findAuthenticatedUserOrDie();
        if (!userToRunThisMethod.isSuperuser()) {
            return error(Response.Status.FORBIDDEN, "Superusers only.");
        }
    } catch (WrappedResponse ex) {
        return error(Response.Status.FORBIDDEN, "Superusers only.");
    }
    boolean disabled = false;
    if (disabled) {
        return error(Response.Status.BAD_REQUEST, "API endpoint disabled.");
    }
    AuthenticatedUser builtInUserToConvert = null;
    String emailToFind;
    String password;
    // could let people specify id on authuser table. probably better to let them tell us their
    String authuserId = "0";
    String newEmailAddressToUse;
    String newProviderId;
    String newPersistentUserIdInLookupTable;
    logger.info("content: " + content);
    try {
        String[] args = content.split(":");
        emailToFind = args[0];
        password = args[1];
        newEmailAddressToUse = args[2];
        newProviderId = args[3];
        newPersistentUserIdInLookupTable = args[4];
    // authuserId = args[666];
    } catch (ArrayIndexOutOfBoundsException ex) {
        return error(Response.Status.BAD_REQUEST, "Problem with content <<<" + content + ">>>: " + ex.toString());
    }
    AuthenticatedUser existingAuthUserFoundByEmail = shibService.findAuthUserByEmail(emailToFind);
    String existing = "NOT FOUND";
    if (existingAuthUserFoundByEmail != null) {
        builtInUserToConvert = existingAuthUserFoundByEmail;
        existing = existingAuthUserFoundByEmail.getIdentifier();
    } else {
        long longToLookup = Long.parseLong(authuserId);
        AuthenticatedUser specifiedUserToConvert = authSvc.findByID(longToLookup);
        if (specifiedUserToConvert != null) {
            builtInUserToConvert = specifiedUserToConvert;
        } else {
            return error(Response.Status.BAD_REQUEST, "No user to convert. We couldn't find a *single* existing user account based on " + emailToFind + " and no user was found using specified id " + longToLookup);
        }
    }
    // String shibProviderId = ShibAuthenticationProvider.PROVIDER_ID;
    Map<String, String> randomUser = authTestDataService.getRandomUser();
    // String eppn = UUID.randomUUID().toString().substring(0, 8);
    String eppn = randomUser.get("eppn");
    String idPEntityId = randomUser.get("idp");
    String notUsed = null;
    String separator = "|";
    // UserIdentifier newUserIdentifierInLookupTable = new UserIdentifier(idPEntityId + separator + eppn, notUsed);
    UserIdentifier newUserIdentifierInLookupTable = new UserIdentifier(newPersistentUserIdInLookupTable, notUsed);
    String overwriteFirstName = randomUser.get("firstName");
    String overwriteLastName = randomUser.get("lastName");
    String overwriteEmail = randomUser.get("email");
    overwriteEmail = newEmailAddressToUse;
    logger.info("overwriteEmail: " + overwriteEmail);
    boolean validEmail = EMailValidator.isEmailValid(overwriteEmail, null);
    if (!validEmail) {
        // See https://github.com/IQSS/dataverse/issues/2998
        return error(Response.Status.BAD_REQUEST, "invalid email: " + overwriteEmail);
    }
    /**
     * @todo If affiliation is not null, put it in RoleAssigneeDisplayInfo
     * constructor.
     */
    /**
     * Here we are exercising (via an API test) shibService.getAffiliation
     * with the TestShib IdP and a non-production DevShibAccountType.
     */
    // idPEntityId = ShibUtil.testShibIdpEntityId;
    // String overwriteAffiliation = shibService.getAffiliation(idPEntityId, ShibServiceBean.DevShibAccountType.RANDOM);
    String overwriteAffiliation = null;
    logger.info("overwriteAffiliation: " + overwriteAffiliation);
    /**
     * @todo Find a place to put "position" in the authenticateduser table:
     * https://github.com/IQSS/dataverse/issues/1444#issuecomment-74134694
     */
    String overwritePosition = "staff;student";
    AuthenticatedUserDisplayInfo displayInfo = new AuthenticatedUserDisplayInfo(overwriteFirstName, overwriteLastName, overwriteEmail, overwriteAffiliation, overwritePosition);
    JsonObjectBuilder response = Json.createObjectBuilder();
    JsonArrayBuilder problems = Json.createArrayBuilder();
    if (password != null) {
        response.add("password supplied", password);
        boolean knowsExistingPassword = false;
        BuiltinUser oldBuiltInUser = builtinUserService.findByUserName(builtInUserToConvert.getUserIdentifier());
        if (oldBuiltInUser != null) {
            String usernameOfBuiltinAccountToConvert = oldBuiltInUser.getUserName();
            response.add("old username", usernameOfBuiltinAccountToConvert);
            AuthenticatedUser authenticatedUser = authSvc.canLogInAsBuiltinUser(usernameOfBuiltinAccountToConvert, password);
            if (authenticatedUser != null) {
                knowsExistingPassword = true;
                AuthenticatedUser convertedUser = authSvc.convertBuiltInUserToRemoteUser(builtInUserToConvert, newProviderId, newUserIdentifierInLookupTable);
                if (convertedUser != null) {
                    /**
                     * @todo Display name is not being overwritten. Logic
                     * must be in Shib backing bean
                     */
                    AuthenticatedUser updatedInfoUser = authSvc.updateAuthenticatedUser(convertedUser, displayInfo);
                    if (updatedInfoUser != null) {
                        response.add("display name overwritten with", updatedInfoUser.getName());
                    } else {
                        problems.add("couldn't update display info");
                    }
                } else {
                    problems.add("unable to convert user");
                }
            }
        } else {
            problems.add("couldn't find old username");
        }
        if (!knowsExistingPassword) {
            String message = "User doesn't know password.";
            problems.add(message);
            /**
             * @todo Someday we should make a errorResponse method that
             * takes JSON arrays and objects.
             */
            return error(Status.BAD_REQUEST, problems.build().toString());
        }
    // response.add("knows existing password", knowsExistingPassword);
    }
    response.add("user to convert", builtInUserToConvert.getIdentifier());
    response.add("existing user found by email (prompt to convert)", existing);
    response.add("changing to this provider", newProviderId);
    response.add("value to overwrite old first name", overwriteFirstName);
    response.add("value to overwrite old last name", overwriteLastName);
    response.add("value to overwrite old email address", overwriteEmail);
    if (overwriteAffiliation != null) {
        response.add("affiliation", overwriteAffiliation);
    }
    response.add("problems", problems);
    return ok(response);
}
Also used : AuthenticatedUserDisplayInfo(edu.harvard.iq.dataverse.authorization.AuthenticatedUserDisplayInfo) BuiltinUser(edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) JsonArrayBuilder(javax.json.JsonArrayBuilder) UserIdentifier(edu.harvard.iq.dataverse.authorization.UserIdentifier) JsonObjectBuilder(javax.json.JsonObjectBuilder) Path(javax.ws.rs.Path) PUT(javax.ws.rs.PUT)

Example 47 with AuthenticatedUser

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

the class Admin method convertShibUserToBuiltin.

/**
 * curl -X PUT -d "shib@mailinator.com"
 * http://localhost:8080/api/admin/authenticatedUsers/id/11/convertShibToBuiltIn
 *
 * @deprecated We have documented this API endpoint so we'll keep in around
 * for a while but we should encourage everyone to switch to the
 * "convertRemoteToBuiltIn" endpoint and then remove this Shib-specfic one.
 */
@PUT
@Path("authenticatedUsers/id/{id}/convertShibToBuiltIn")
@Deprecated
public Response convertShibUserToBuiltin(@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 Shibboleth 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 Shibboleth 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)

Example 48 with AuthenticatedUser

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

the class ContainerManagerImpl method replaceMetadata.

@Override
public DepositReceipt replaceMetadata(String uri, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration swordConfiguration) throws SwordError, SwordServerException, SwordAuthException {
    AuthenticatedUser user = swordAuth.auth(authCredentials);
    DataverseRequest dvReq = new DataverseRequest(user, httpRequest);
    logger.fine("replaceMetadata called with url: " + uri);
    urlManager.processUrl(uri);
    String targetType = urlManager.getTargetType();
    if (!targetType.isEmpty()) {
        logger.fine("operating on target type: " + urlManager.getTargetType());
        if ("dataverse".equals(targetType)) {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Metadata replace of dataverse is not supported.");
        } else if ("study".equals(targetType)) {
            logger.fine("replacing metadata for dataset");
            // do a sanity check on the XML received
            try {
                SwordEntry swordEntry = deposit.getSwordEntry();
                logger.fine("deposit XML received by replaceMetadata():\n" + swordEntry);
            } catch (ParseException ex) {
                throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Can not replace dataset metadata due to malformed Atom entry: " + ex);
            }
            String globalId = urlManager.getTargetIdentifier();
            Dataset dataset = datasetService.findByGlobalId(globalId);
            if (dataset != null) {
                Dataverse dvThatOwnsDataset = dataset.getOwner();
                UpdateDatasetCommand updateDatasetCommand = new UpdateDatasetCommand(dataset, dvReq);
                if (!permissionService.isUserAllowedOn(user, updateDatasetCommand, dataset)) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "User " + user.getDisplayInfo().getTitle() + " is not authorized to modify dataverse " + dvThatOwnsDataset.getAlias());
                }
                DatasetVersion datasetVersion = dataset.getEditVersion();
                // erase all metadata before creating populating dataset version
                List<DatasetField> emptyDatasetFields = new ArrayList<>();
                datasetVersion.setDatasetFields(emptyDatasetFields);
                String foreignFormat = SwordUtil.DCTERMS;
                try {
                    importGenericService.importXML(deposit.getSwordEntry().toString(), foreignFormat, datasetVersion);
                } catch (Exception ex) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "problem calling importXML: " + ex);
                }
                swordService.addDatasetContact(datasetVersion, user);
                swordService.addDatasetDepositor(datasetVersion, user);
                swordService.addDatasetSubjectIfMissing(datasetVersion);
                swordService.setDatasetLicenseAndTermsOfUse(datasetVersion, deposit.getSwordEntry());
                try {
                    engineSvc.submit(updateDatasetCommand);
                } catch (CommandException ex) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "problem updating dataset: " + ex);
                }
                ReceiptGenerator receiptGenerator = new ReceiptGenerator();
                String baseUrl = urlManager.getHostnamePlusBaseUrlPath(uri);
                DepositReceipt depositReceipt = receiptGenerator.createDatasetReceipt(baseUrl, dataset);
                return depositReceipt;
            } else {
                throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not find dataset based on global id (" + globalId + ") in URL: " + uri);
            }
        } else {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unknown target type specified on which to replace metadata: " + uri);
        }
    } else {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "No target specified on which to replace metadata: " + uri);
    }
}
Also used : SwordError(org.swordapp.server.SwordError) Dataset(edu.harvard.iq.dataverse.Dataset) DatasetVersion(edu.harvard.iq.dataverse.DatasetVersion) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Dataverse(edu.harvard.iq.dataverse.Dataverse) SwordAuthException(org.swordapp.server.SwordAuthException) SwordServerException(org.swordapp.server.SwordServerException) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) EJBException(javax.ejb.EJBException) CommandExecutionException(edu.harvard.iq.dataverse.engine.command.exception.CommandExecutionException) ParseException(org.apache.abdera.parser.ParseException) DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) DepositReceipt(org.swordapp.server.DepositReceipt) SwordEntry(org.swordapp.server.SwordEntry) ArrayList(java.util.ArrayList) List(java.util.List) ParseException(org.apache.abdera.parser.ParseException) UpdateDatasetCommand(edu.harvard.iq.dataverse.engine.command.impl.UpdateDatasetCommand)

Example 49 with AuthenticatedUser

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

the class SwordServiceBean method addDatasetDepositor.

/**
 * Mutate the dataset version, adding a depositor for the dataset.
 */
public void addDatasetDepositor(DatasetVersion newDatasetVersion, User user) {
    if (!user.isAuthenticated()) {
        logger.info("returning early since user is not authenticated");
        return;
    }
    AuthenticatedUser au = (AuthenticatedUser) user;
    DatasetFieldType depositorDatasetFieldType = datasetFieldService.findByNameOpt(DatasetFieldConstant.depositor);
    DatasetField depositorDatasetField = DatasetField.createNewEmptyDatasetField(depositorDatasetFieldType, newDatasetVersion);
    depositorDatasetField.setSingleValue(au.getLastName() + ", " + au.getFirstName());
    newDatasetVersion.getDatasetFields().add(depositorDatasetField);
}
Also used : DatasetField(edu.harvard.iq.dataverse.DatasetField) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) DatasetFieldType(edu.harvard.iq.dataverse.DatasetFieldType)

Example 50 with AuthenticatedUser

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

the class WorldMapTokenTest method makeNewToken.

private WorldMapToken makeNewToken(TokenApplicationType tat) {
    WorldMapToken token;
    token = new WorldMapToken();
    token.setApplication(tat);
    token.setDatafile(new DataFile());
    token.setDataverseUser(new AuthenticatedUser());
    token.refreshToken();
    token.setToken();
    return token;
}
Also used : DataFile(edu.harvard.iq.dataverse.DataFile) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

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