Search in sources :

Example 61 with AuthenticatedUser

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

the class UserListMaker method runUserSearch.

public UserListResult runUserSearch(String searchTerm, Integer itemsPerPage, Integer selectedPage, String sorKey) {
    // Initialize searchTerm
    if ((searchTerm == null) || (searchTerm.trim().isEmpty())) {
        searchTerm = null;
    }
    // Initialize itemsPerPage
    if ((itemsPerPage == null) || (itemsPerPage < MIN_ITEMS_PER_PAGE)) {
        itemsPerPage = ITEMS_PER_PAGE;
    }
    // Initialize selectedPage
    if ((selectedPage == null) || (selectedPage < 1)) {
        selectedPage = 1;
    }
    // Initialize sortKey
    String sortKey = null;
    Pager pager;
    // -------------------------------------------------
    // (1) What is the user count for this search?
    // -------------------------------------------------
    Long userCount = userService.getUserCount(searchTerm);
    // Are there any hits?  No; return info
    if ((userCount == null) || (userCount == 0)) {
        pager = new Pager(0, itemsPerPage, selectedPage);
        return new UserListResult(searchTerm, pager, null);
    }
    // -------------------------------------------------
    // (2) Do some calculations here regarding the selected page, offset, etc.
    // -------------------------------------------------
    OffsetPageValues offsetPageValues = getOffset(userCount, selectedPage, itemsPerPage);
    selectedPage = offsetPageValues.getPageNumber();
    int offset = offsetPageValues.getOffset();
    // -------------------------------------------------
    // (3) Retrieve the users
    // -------------------------------------------------
    List<AuthenticatedUser> userList = userService.getAuthenticatedUserList(searchTerm, sortKey, itemsPerPage, offset);
    if (userList == null) {
        pager = new Pager(0, itemsPerPage, selectedPage);
        return new UserListResult(searchTerm, pager, null);
    }
    pager = new Pager(userCount.intValue(), itemsPerPage, selectedPage);
    return new UserListResult(searchTerm, pager, userList);
}
Also used : Pager(edu.harvard.iq.dataverse.mydata.Pager) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Example 62 with AuthenticatedUser

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

the class SearchServiceBean method getPermissionFilterQuery.

/**
 * Moved this logic out of the "search" function
 *
 * @return
 */
private String getPermissionFilterQuery(DataverseRequest dataverseRequest, SolrQuery solrQuery, Dataverse dataverse, boolean onlyDatatRelatedToMe) {
    User user = dataverseRequest.getUser();
    if (user == null) {
        throw new NullPointerException("user cannot be null");
    }
    if (solrQuery == null) {
        throw new NullPointerException("solrQuery cannot be null");
    }
    /**
     * @todo For people who are not logged in, should we show stuff indexed
     * with "AllUsers" group or not? If so, uncomment the allUsersString
     * stuff below.
     */
    // String allUsersString = IndexServiceBean.getGroupPrefix() + AllUsers.get().getAlias();
    // String publicOnly = "{!join from=" + SearchFields.DEFINITION_POINT + " to=id}" + SearchFields.DISCOVERABLE_BY + ":(" + IndexServiceBean.getPublicGroupString() + " OR " + allUsersString + ")";
    String publicOnly = "{!join from=" + SearchFields.DEFINITION_POINT + " to=id}" + SearchFields.DISCOVERABLE_BY + ":(" + IndexServiceBean.getPublicGroupString() + ")";
    // String publicOnly = "{!join from=" + SearchFields.GROUPS + " to=" + SearchFields.PERMS + "}id:" + IndexServiceBean.getPublicGroupString();
    // initialize to public only to be safe
    String dangerZoneNoSolrJoin = null;
    if (user instanceof PrivateUrlUser) {
        user = GuestUser.get();
    }
    // ----------------------------------------------------
    if (user instanceof GuestUser) {
        String groupsFromProviders = "";
        Set<Group> groups = groupService.collectAncestors(groupService.groupsFor(dataverseRequest));
        StringBuilder sb = new StringBuilder();
        for (Group group : groups) {
            logger.fine("found group " + group.getIdentifier() + " with alias " + group.getAlias());
            String groupAlias = group.getAlias();
            if (groupAlias != null && !groupAlias.isEmpty()) {
                sb.append(" OR ");
                // i.e. group_builtIn/all-users, ip/ipGroup3
                sb.append(IndexServiceBean.getGroupPrefix()).append(groupAlias);
            }
        }
        groupsFromProviders = sb.toString();
        logger.fine("groupsFromProviders:" + groupsFromProviders);
        String guestWithGroups = "{!join from=" + SearchFields.DEFINITION_POINT + " to=id}" + SearchFields.DISCOVERABLE_BY + ":(" + IndexServiceBean.getPublicGroupString() + groupsFromProviders + ")";
        logger.fine(guestWithGroups);
        return guestWithGroups;
    }
    // ----------------------------------------------------
    if (!(user instanceof AuthenticatedUser)) {
        logger.severe("Should never reach here. A User must be an AuthenticatedUser or a Guest");
        throw new IllegalStateException("A User must be an AuthenticatedUser or a Guest");
    }
    AuthenticatedUser au = (AuthenticatedUser) user;
    // Logged in user, has publication status facet
    // 
    solrQuery.addFacetField(SearchFields.PUBLICATION_STATUS);
    // ----------------------------------------------------
    if (au.isSuperuser()) {
        return dangerZoneNoSolrJoin;
    }
    // ----------------------------------------------------
    if (onlyDatatRelatedToMe == true) {
        if (systemConfig.myDataDoesNotUsePermissionDocs()) {
            logger.fine("old 4.2 behavior: MyData is not using Solr permission docs");
            return dangerZoneNoSolrJoin;
        } else {
            logger.fine("new post-4.2 behavior: MyData is using Solr permission docs");
        }
    }
    // ----------------------------------------------------
    // (5) Work with Authenticated User who is not a Superuser
    // ----------------------------------------------------
    /**
     * @todo all this code needs cleanup and clarification.
     */
    /**
     * Every AuthenticatedUser is part of a "User Private Group" (UGP), a
     * concept we borrow from RHEL:
     * https://access.redhat.com/site/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Deployment_Guide/ch-Managing_Users_and_Groups.html#s2-users-groups-private-groups
     */
    /**
     * @todo rename this from publicPlusUserPrivateGroup. Confusing
     */
    // safe default: public only
    String publicPlusUserPrivateGroup = publicOnly;
    // + (onlyDatatRelatedToMe ? "" : (publicOnly + " OR "))
    // + "{!join from=" + SearchFields.GROUPS + " to=" + SearchFields.PERMS + "}id:" + IndexServiceBean.getGroupPerUserPrefix() + au.getId() + ")";
    // /**
    // * @todo add onlyDatatRelatedToMe option into the experimental JOIN
    // * before enabling it.
    // */
    /**
     * From a search perspective, we don't care about if the group was
     * created within one dataverse or another. We just want a list of *all*
     * the groups the user is part of. We are greedy. We want all BuiltIn
     * Groups, Shibboleth Groups, IP Groups, "system" groups, everything.
     *
     * A JOIN on "permission documents" will determine if the user can find
     * a given "content document" (dataset version, etc) in Solr.
     */
    String groupsFromProviders = "";
    Set<Group> groups = groupService.collectAncestors(groupService.groupsFor(dataverseRequest));
    StringBuilder sb = new StringBuilder();
    for (Group group : groups) {
        logger.fine("found group " + group.getIdentifier() + " with alias " + group.getAlias());
        String groupAlias = group.getAlias();
        if (groupAlias != null && !groupAlias.isEmpty()) {
            sb.append(" OR ");
            // i.e. group_builtIn/all-users, group_builtIn/authenticated-users, group_1-explictGroup1, group_shib/2
            sb.append(IndexServiceBean.getGroupPrefix() + groupAlias);
        }
    }
    groupsFromProviders = sb.toString();
    logger.fine(groupsFromProviders);
    if (true) {
        /**
         * @todo get rid of "experimental" in name
         */
        String experimentalJoin = "{!join from=" + SearchFields.DEFINITION_POINT + " to=id}" + SearchFields.DISCOVERABLE_BY + ":(" + IndexServiceBean.getPublicGroupString() + " OR " + IndexServiceBean.getGroupPerUserPrefix() + au.getId() + groupsFromProviders + ")";
        publicPlusUserPrivateGroup = experimentalJoin;
    }
    // permissionFilterQuery = publicPlusUserPrivateGroup;
    logger.fine(publicPlusUserPrivateGroup);
    return publicPlusUserPrivateGroup;
}
Also used : GuestUser(edu.harvard.iq.dataverse.authorization.users.GuestUser) Group(edu.harvard.iq.dataverse.authorization.groups.Group) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) User(edu.harvard.iq.dataverse.authorization.users.User) PrivateUrlUser(edu.harvard.iq.dataverse.authorization.users.PrivateUrlUser) GuestUser(edu.harvard.iq.dataverse.authorization.users.GuestUser) PrivateUrlUser(edu.harvard.iq.dataverse.authorization.users.PrivateUrlUser) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Example 63 with AuthenticatedUser

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

the class DestroyDatasetCommand method executeImpl.

@Override
protected void executeImpl(CommandContext ctxt) throws CommandException {
    // first check if dataset is released, and if so, if user is a superuser
    if (doomed.isReleased() && (!(getUser() instanceof AuthenticatedUser) || !getUser().isSuperuser())) {
        throw new PermissionException("Destroy can only be called by superusers.", this, Collections.singleton(Permission.DeleteDatasetDraft), doomed);
    }
    // If there is a dedicated thumbnail DataFile, it needs to be reset
    // explicitly, or we'll get a constraint violation when deleting:
    doomed.setThumbnailFile(null);
    final Dataset managedDoomed = ctxt.em().merge(doomed);
    List<String> datasetAndFileSolrIdsToDelete = new ArrayList<>();
    // files need to iterate through and remove 'by hand' to avoid
    // optimistic lock issues... (plus the physical files need to be
    // deleted too!)
    Iterator<DataFile> dfIt = doomed.getFiles().iterator();
    while (dfIt.hasNext()) {
        DataFile df = dfIt.next();
        // Gather potential Solr IDs of files. As of this writing deaccessioned files are never indexed.
        String solrIdOfPublishedFile = IndexServiceBean.solrDocIdentifierFile + df.getId();
        datasetAndFileSolrIdsToDelete.add(solrIdOfPublishedFile);
        String solrIdOfDraftFile = IndexServiceBean.solrDocIdentifierFile + df.getId() + IndexServiceBean.draftSuffix;
        datasetAndFileSolrIdsToDelete.add(solrIdOfDraftFile);
        ctxt.engine().submit(new DeleteDataFileCommand(df, getRequest(), true));
        dfIt.remove();
    }
    // also, lets delete the uploaded thumbnails!
    deleteDatasetLogo(doomed);
    // ASSIGNMENTS
    for (RoleAssignment ra : ctxt.roles().directRoleAssignments(doomed)) {
        ctxt.em().remove(ra);
    }
    // ROLES
    for (DataverseRole ra : ctxt.roles().findByOwnerId(doomed.getId())) {
        ctxt.em().remove(ra);
    }
    IdServiceBean idServiceBean = IdServiceBean.getBean(ctxt);
    try {
        if (idServiceBean.alreadyExists(doomed)) {
            idServiceBean.deleteIdentifier(doomed);
        }
    } catch (Exception e) {
        logger.log(Level.WARNING, "Identifier deletion was not successfull:", e.getMessage());
    }
    Dataverse toReIndex = managedDoomed.getOwner();
    // dataset
    ctxt.em().remove(managedDoomed);
    // add potential Solr IDs of datasets to list for deletion
    String solrIdOfPublishedDatasetVersion = IndexServiceBean.solrDocIdentifierDataset + doomed.getId();
    datasetAndFileSolrIdsToDelete.add(solrIdOfPublishedDatasetVersion);
    String solrIdOfDraftDatasetVersion = IndexServiceBean.solrDocIdentifierDataset + doomed.getId() + IndexServiceBean.draftSuffix;
    datasetAndFileSolrIdsToDelete.add(solrIdOfDraftDatasetVersion);
    String solrIdOfDeaccessionedDatasetVersion = IndexServiceBean.solrDocIdentifierDataset + doomed.getId() + IndexServiceBean.deaccessionedSuffix;
    datasetAndFileSolrIdsToDelete.add(solrIdOfDeaccessionedDatasetVersion);
    IndexResponse resultOfSolrDeletionAttempt = ctxt.solrIndex().deleteMultipleSolrIds(datasetAndFileSolrIdsToDelete);
    logger.log(Level.FINE, "Result of attempt to delete dataset and file IDs from the search index: {0}", resultOfSolrDeletionAttempt.getMessage());
    ctxt.index().indexDataverse(toReIndex);
}
Also used : PermissionException(edu.harvard.iq.dataverse.engine.command.exception.PermissionException) Dataset(edu.harvard.iq.dataverse.Dataset) RoleAssignment(edu.harvard.iq.dataverse.RoleAssignment) ArrayList(java.util.ArrayList) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Dataverse(edu.harvard.iq.dataverse.Dataverse) PermissionException(edu.harvard.iq.dataverse.engine.command.exception.PermissionException) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) DataverseRole(edu.harvard.iq.dataverse.authorization.DataverseRole) DataFile(edu.harvard.iq.dataverse.DataFile) IndexResponse(edu.harvard.iq.dataverse.search.IndexResponse) IdServiceBean(edu.harvard.iq.dataverse.IdServiceBean)

Example 64 with AuthenticatedUser

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

the class CreateDataverseCommand method execute.

@Override
public Dataverse execute(CommandContext ctxt) throws CommandException {
    if (created.getOwner() == null) {
        if (ctxt.dataverses().isRootDataverseExists()) {
            throw new IllegalCommandException("Root Dataverse already exists. Cannot create another one", this);
        }
    }
    if (created.getCreateDate() == null) {
        created.setCreateDate(new Timestamp(new Date().getTime()));
    }
    if (created.getCreator() == null) {
        final User user = getRequest().getUser();
        if (user.isAuthenticated()) {
            created.setCreator((AuthenticatedUser) user);
        } else {
            throw new IllegalCommandException("Guest users cannot create a Dataverse.", this);
        }
    }
    if (created.getDataverseType() == null) {
        created.setDataverseType(Dataverse.DataverseType.UNCATEGORIZED);
    }
    if (created.getDefaultContributorRole() == null) {
        created.setDefaultContributorRole(ctxt.roles().findBuiltinRoleByAlias(DataverseRole.EDITOR));
    }
    // @todo for now we are saying all dataverses are permission root
    created.setPermissionRoot(true);
    if (ctxt.dataverses().findByAlias(created.getAlias()) != null) {
        throw new IllegalCommandException("A dataverse with alias " + created.getAlias() + " already exists", this);
    }
    // Save the dataverse
    Dataverse managedDv = ctxt.dataverses().save(created);
    // Find the built in admin role (currently by alias)
    DataverseRole adminRole = ctxt.roles().findBuiltinRoleByAlias(DataverseRole.ADMIN);
    String privateUrlToken = null;
    ctxt.roles().save(new RoleAssignment(adminRole, getRequest().getUser(), managedDv, privateUrlToken));
    managedDv.setPermissionModificationTime(new Timestamp(new Date().getTime()));
    managedDv = ctxt.dataverses().save(managedDv);
    ctxt.index().indexDataverse(managedDv);
    if (facetList != null) {
        ctxt.facets().deleteFacetsFor(managedDv);
        int i = 0;
        for (DatasetFieldType df : facetList) {
            ctxt.facets().create(i++, df, managedDv);
        }
    }
    if (inputLevelList != null) {
        ctxt.fieldTypeInputLevels().deleteFacetsFor(managedDv);
        for (DataverseFieldTypeInputLevel obj : inputLevelList) {
            obj.setDataverse(managedDv);
            ctxt.fieldTypeInputLevels().create(obj);
        }
    }
    return managedDv;
}
Also used : AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) User(edu.harvard.iq.dataverse.authorization.users.User) IllegalCommandException(edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException) RoleAssignment(edu.harvard.iq.dataverse.RoleAssignment) DataverseFieldTypeInputLevel(edu.harvard.iq.dataverse.DataverseFieldTypeInputLevel) Timestamp(java.sql.Timestamp) Dataverse(edu.harvard.iq.dataverse.Dataverse) DatasetFieldType(edu.harvard.iq.dataverse.DatasetFieldType) Date(java.util.Date) DataverseRole(edu.harvard.iq.dataverse.authorization.DataverseRole)

Example 65 with AuthenticatedUser

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

the class GrantSuperuserStatusCommand method executeImpl.

@Override
protected void executeImpl(CommandContext ctxt) throws CommandException {
    if (!(getUser() instanceof AuthenticatedUser) || !getUser().isSuperuser()) {
        throw new PermissionException("Revoke Superuser status command can only be called by superusers.", this, null, null);
    }
    try {
        targetUser.setSuperuser(true);
        ctxt.em().merge(targetUser);
        ctxt.em().flush();
    } catch (Exception e) {
        throw new CommandException("Failed to grant the superuser status to user " + targetUser.getIdentifier(), this);
    }
}
Also used : PermissionException(edu.harvard.iq.dataverse.engine.command.exception.PermissionException) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) PermissionException(edu.harvard.iq.dataverse.engine.command.exception.PermissionException) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException)

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