Search in sources :

Example 1 with JpaGroup

use of org.opencastproject.security.impl.jpa.JpaGroup in project opencast by opencast.

the class UserAndSeriesLoader method loadGroup.

/**
 * Loads demo group into persistence
 *
 * @param groupId
 *          the group id
 * @param orgId
 *          the organization id
 * @param name
 *          the group name
 * @param description
 *          the group description
 * @param additionalRoles
 *          any additional roles to the group
 * @param members
 *          the members associated to this group
 */
protected void loadGroup(String groupId, String orgId, String name, String description, String[] additionalRoles, String[] members) {
    if (jpaGroupRoleProvider.loadGroup(groupId, orgId) == null) {
        Set<JpaRole> roles = new HashSet<>();
        for (String additionalRole : additionalRoles) {
            roles.add(new JpaRole(additionalRole, getOrganization(orgId)));
        }
        JpaGroup group = new JpaGroup(groupId, getOrganization(orgId), name, description, roles, new HashSet<>(Arrays.asList(members)));
        try {
            jpaGroupRoleProvider.addGroup(group);
        } catch (Exception e) {
            logger.warn("Can not add {}: {}", group, e);
        }
    }
}
Also used : JpaGroup(org.opencastproject.security.impl.jpa.JpaGroup) JpaRole(org.opencastproject.security.impl.jpa.JpaRole) SeriesException(org.opencastproject.series.api.SeriesException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) HashSet(java.util.HashSet)

Example 2 with JpaGroup

use of org.opencastproject.security.impl.jpa.JpaGroup in project opencast by opencast.

the class JpaGroupRoleProvider method repopulate.

@Override
public void repopulate(final String indexName) {
    final String destinationId = GroupItem.GROUP_QUEUE_PREFIX + WordUtils.capitalize(indexName);
    for (final Organization organization : organizationDirectoryService.getOrganizations()) {
        SecurityUtil.runAs(securityService, organization, SecurityUtil.createSystemUser(cc, organization), new Effect0() {

            @Override
            protected void run() {
                final List<JpaGroup> groups = UserDirectoryPersistenceUtil.findGroups(organization.getId(), 0, 0, emf);
                int total = groups.size();
                final int responseInterval = (total < 100) ? 1 : (total / 100);
                int current = 1;
                logger.info("Re-populating index '{}' with groups of organization {}. There are {} group(s) to add to the index.", indexName, securityService.getOrganization().getId(), total);
                for (JpaGroup group : groups) {
                    messageSender.sendObjectMessage(destinationId, MessageSender.DestinationType.Queue, GroupItem.update(JaxbGroup.fromGroup(group)));
                    if (((current % responseInterval) == 0) || (current == total)) {
                        messageSender.sendObjectMessage(IndexProducer.RESPONSE_QUEUE, MessageSender.DestinationType.Queue, IndexRecreateObject.update(indexName, IndexRecreateObject.Service.Groups, total, current));
                    }
                    current++;
                }
            }
        });
    }
    Organization organization = new DefaultOrganization();
    SecurityUtil.runAs(securityService, organization, SecurityUtil.createSystemUser(cc, organization), new Effect0() {

        @Override
        protected void run() {
            messageSender.sendObjectMessage(IndexProducer.RESPONSE_QUEUE, MessageSender.DestinationType.Queue, IndexRecreateObject.end(indexName, IndexRecreateObject.Service.Groups));
        }
    });
}
Also used : JpaGroup(org.opencastproject.security.impl.jpa.JpaGroup) Organization(org.opencastproject.security.api.Organization) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) JpaOrganization(org.opencastproject.security.impl.jpa.JpaOrganization) Effect0(org.opencastproject.util.data.Effect0) List(java.util.List) ArrayList(java.util.ArrayList) JaxbGroupList(org.opencastproject.security.api.JaxbGroupList) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization)

Example 3 with JpaGroup

use of org.opencastproject.security.impl.jpa.JpaGroup in project opencast by opencast.

the class JpaGroupRoleProvider method createGroup.

@POST
@Path("")
@RestQuery(name = "createGroup", description = "Add a group", returnDescription = "Return the status codes", restParameters = { @RestParameter(name = "name", description = "The group name", isRequired = true, type = Type.STRING), @RestParameter(name = "description", description = "The group description", isRequired = false, type = Type.STRING), @RestParameter(name = "roles", description = "A comma seperated string of additional group roles", isRequired = false, type = Type.TEXT), @RestParameter(name = "users", description = "A comma seperated string of group members", isRequired = false, type = Type.TEXT) }, reponses = { @RestResponse(responseCode = SC_CREATED, description = "Group created"), @RestResponse(responseCode = SC_BAD_REQUEST, description = "Name too long"), @RestResponse(responseCode = SC_FORBIDDEN, description = "Not enough permissions to create a group with the admin role."), @RestResponse(responseCode = SC_CONFLICT, description = "An group with this name already exists.") })
public Response createGroup(@FormParam("name") String name, @FormParam("description") String description, @FormParam("roles") String roles, @FormParam("users") String users) {
    JpaOrganization organization = (JpaOrganization) securityService.getOrganization();
    HashSet<JpaRole> roleSet = new HashSet<JpaRole>();
    if (roles != null) {
        for (String role : StringUtils.split(roles, ",")) {
            roleSet.add(new JpaRole(StringUtils.trim(role), organization));
        }
    }
    HashSet<String> members = new HashSet<String>();
    if (users != null) {
        for (String member : StringUtils.split(users, ",")) {
            members.add(StringUtils.trim(member));
        }
    }
    final String groupId = name.toLowerCase().replaceAll("\\W", "_");
    JpaGroup existingGroup = UserDirectoryPersistenceUtil.findGroup(groupId, organization.getId(), emf);
    if (existingGroup != null)
        return Response.status(SC_CONFLICT).build();
    try {
        addGroup(new JpaGroup(groupId, organization, name, description, roleSet, members));
    } catch (IllegalArgumentException e) {
        logger.warn(e.getMessage());
        return Response.status(Status.BAD_REQUEST).build();
    } catch (UnauthorizedException e) {
        return Response.status(SC_FORBIDDEN).build();
    }
    return Response.status(Status.CREATED).build();
}
Also used : JpaGroup(org.opencastproject.security.impl.jpa.JpaGroup) JpaOrganization(org.opencastproject.security.impl.jpa.JpaOrganization) JpaRole(org.opencastproject.security.impl.jpa.JpaRole) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) HashSet(java.util.HashSet) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 4 with JpaGroup

use of org.opencastproject.security.impl.jpa.JpaGroup in project opencast by opencast.

the class JpaGroupRoleProvider method updateGroupMembershipFromRoles.

/**
 * Updates a user's group membership
 *
 * @param userName
 *          the username
 * @param orgId
 *          the user's organization
 * @param roleList
 *          the list of group role names
 */
public void updateGroupMembershipFromRoles(String userName, String orgId, List<String> roleList) {
    logger.debug("updateGroupMembershipFromRoles({}, size={})", userName, roleList.size());
    // The list of groups for this user represented by the roleList is considered authoritative,
    // so remove the user from any groups which aren't represented in the roleList, and add the
    // user to all groups which are in the roleList.
    Set<String> membershipRoles = new HashSet<String>();
    // List of the user's groups
    List<JpaGroup> membership = UserDirectoryPersistenceUtil.findGroupsByUser(userName, orgId, emf);
    for (JpaGroup group : membership) {
        try {
            if (roleList.contains(group.getRole())) {
                // record this membership
                membershipRoles.add(group.getRole());
            } else {
                // remove user from this group
                logger.debug("Removing user {} from group {}", userName, group.getRole());
                group.getMembers().remove(userName);
                addGroup(group);
            }
        } catch (UnauthorizedException e) {
            logger.warn("Unable to add or remove user {} from group {} - unauthorized", userName, group.getRole());
        }
    }
    // Now add the user to any groups that they are not already a member of
    for (String rolename : roleList) {
        if (!membershipRoles.contains(rolename)) {
            JpaGroup group = UserDirectoryPersistenceUtil.findGroupByRole(rolename, orgId, emf);
            try {
                if (group != null) {
                    logger.debug("Adding user {} to group {}", userName, rolename);
                    group.getMembers().add(userName);
                    addGroup(group);
                } else {
                    logger.warn("Cannot add user {} to group {} - no group found with that role", userName, rolename);
                }
            } catch (UnauthorizedException e) {
                logger.warn("Unable to add user {} to group {} - unauthorized", userName, group.getRole());
            }
        }
    }
}
Also used : JpaGroup(org.opencastproject.security.impl.jpa.JpaGroup) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) HashSet(java.util.HashSet)

Example 5 with JpaGroup

use of org.opencastproject.security.impl.jpa.JpaGroup in project opencast by opencast.

the class UserDirectoryPersistenceUtil method findGroup.

/**
 * Returns the persisted group by the group id and organization id
 *
 * @param groupId
 *          the group id
 * @param orgId
 *          the organization id
 * @param emf
 *          the entity manager factory
 * @return the group or <code>null</code> if not found
 */
public static JpaGroup findGroup(String groupId, String orgId, EntityManagerFactory emf) {
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("Group.findById");
        q.setParameter("groupId", groupId);
        q.setParameter("organization", orgId);
        return (JpaGroup) q.getSingleResult();
    } catch (NoResultException e) {
        return null;
    } finally {
        if (em != null)
            em.close();
    }
}
Also used : JpaGroup(org.opencastproject.security.impl.jpa.JpaGroup) EntityManager(javax.persistence.EntityManager) Query(javax.persistence.Query) NoResultException(javax.persistence.NoResultException)

Aggregations

JpaGroup (org.opencastproject.security.impl.jpa.JpaGroup)20 JpaRole (org.opencastproject.security.impl.jpa.JpaRole)14 HashSet (java.util.HashSet)9 Test (org.junit.Test)8 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)7 Group (org.opencastproject.security.api.Group)5 Role (org.opencastproject.security.api.Role)5 NotFoundException (org.opencastproject.util.NotFoundException)5 EntityManager (javax.persistence.EntityManager)4 JpaOrganization (org.opencastproject.security.impl.jpa.JpaOrganization)4 ArrayList (java.util.ArrayList)3 NoResultException (javax.persistence.NoResultException)3 Path (javax.ws.rs.Path)3 SecurityService (org.opencastproject.security.api.SecurityService)3 JpaUser (org.opencastproject.security.impl.jpa.JpaUser)3 RestQuery (org.opencastproject.util.doc.rest.RestQuery)3 EntityTransaction (javax.persistence.EntityTransaction)2 Query (javax.persistence.Query)2 Response (javax.ws.rs.core.Response)2 JaxbGroup (org.opencastproject.security.api.JaxbGroup)2