Search in sources :

Example 21 with JpaRole

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

the class JpaUserAndRoleProvider method updateUser.

/**
 * Updates a user to the persistence
 *
 * @param user
 *          the user to save
 * @throws NotFoundException
 * @throws org.opencastproject.security.api.UnauthorizedException
 *          if the current user is not allowed to update user with the given roles
 */
public User updateUser(JpaUser user) throws NotFoundException, UnauthorizedException {
    if (!UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, user.getRoles()))
        throw new UnauthorizedException("The user is not allowed to set the admin role on other users");
    JpaUser updateUser = UserDirectoryPersistenceUtil.findUser(user.getUsername(), user.getOrganization().getId(), emf);
    if (updateUser == null)
        throw new NotFoundException("User " + user.getUsername() + " not found.");
    logger.debug("updateUser({})", user.getUsername());
    if (!UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, updateUser.getRoles()))
        throw new UnauthorizedException("The user is not allowed to update an admin user");
    String encodedPassword = null;
    // only update Password if a value is set
    if (user.getPassword().isEmpty()) {
        JpaUser old = UserDirectoryPersistenceUtil.findUser(user.getUsername(), user.getOrganization().getId(), emf);
        encodedPassword = old.getPassword();
    } else {
        // Update an JPA user with an encoded password.
        encodedPassword = PasswordEncoder.encode(user.getPassword(), user.getUsername());
    }
    // Only save internal roles
    Set<JpaRole> roles = UserDirectoryPersistenceUtil.saveRoles(filterRoles(user.getRoles()), emf);
    JpaOrganization organization = UserDirectoryPersistenceUtil.saveOrganization((JpaOrganization) user.getOrganization(), emf);
    JpaUser updatedUser = UserDirectoryPersistenceUtil.saveUser(new JpaUser(user.getUsername(), encodedPassword, organization, user.getName(), user.getEmail(), user.getProvider(), true, roles), emf);
    cache.put(user.getUsername() + DELIMITER + organization.getId(), updatedUser);
    updateGroupMembership(user);
    return updatedUser;
}
Also used : JpaOrganization(org.opencastproject.security.impl.jpa.JpaOrganization) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) JpaRole(org.opencastproject.security.impl.jpa.JpaRole) NotFoundException(org.opencastproject.util.NotFoundException) JpaUser(org.opencastproject.security.impl.jpa.JpaUser)

Example 22 with JpaRole

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

the class JpaGroupRoleProvider method updateGroup.

@PUT
@Path("{id}")
@RestQuery(name = "updateGroup", description = "Update a group", returnDescription = "Return the status codes", pathParameters = { @RestParameter(name = "id", description = "The group identifier", isRequired = true, type = Type.STRING) }, 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 = true, type = Type.TEXT) }, reponses = { @RestResponse(responseCode = SC_OK, description = "Group updated"), @RestResponse(responseCode = SC_FORBIDDEN, description = "Not enough permissions to update a group with the admin role."), @RestResponse(responseCode = SC_NOT_FOUND, description = "Group not found"), @RestResponse(responseCode = SC_BAD_REQUEST, description = "Name too long") })
public Response updateGroup(@PathParam("id") String groupId, @FormParam("name") String name, @FormParam("description") String description, @FormParam("roles") String roles, @FormParam("users") String users) throws NotFoundException {
    JpaOrganization organization = (JpaOrganization) securityService.getOrganization();
    JpaGroup group = UserDirectoryPersistenceUtil.findGroup(groupId, organization.getId(), emf);
    if (group == null)
        throw new NotFoundException();
    if (StringUtils.isNotBlank(name))
        group.setName(StringUtils.trim(name));
    if (StringUtils.isNotBlank(description))
        group.setDescription(StringUtils.trim(description));
    if (StringUtils.isNotBlank(roles)) {
        HashSet<JpaRole> roleSet = new HashSet<JpaRole>();
        for (String role : StringUtils.split(roles, ",")) {
            roleSet.add(new JpaRole(StringUtils.trim(role), organization));
        }
        group.setRoles(roleSet);
    } else {
        group.setRoles(new HashSet<JpaRole>());
    }
    if (users != null) {
        HashSet<String> members = new HashSet<String>();
        HashSet<String> invalidateUsers = new HashSet<String>();
        Set<String> groupMembers = group.getMembers();
        for (String member : StringUtils.split(users, ",")) {
            String newMember = StringUtils.trim(member);
            members.add(newMember);
            if (!groupMembers.contains(newMember)) {
                invalidateUsers.add(newMember);
            }
        }
        for (String member : groupMembers) {
            if (!members.contains(member)) {
                invalidateUsers.add(member);
            }
        }
        group.setMembers(members);
        // Invalidate cache entries for users who have been added or removed
        for (String member : invalidateUsers) {
            userDirectoryService.invalidate(member);
        }
    }
    try {
        addGroup(group);
    } catch (IllegalArgumentException e) {
        logger.warn(e.getMessage());
        return Response.status(Status.BAD_REQUEST).build();
    } catch (UnauthorizedException ex) {
        return Response.status(SC_FORBIDDEN).build();
    }
    return Response.ok().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) NotFoundException(org.opencastproject.util.NotFoundException) HashSet(java.util.HashSet) Path(javax.ws.rs.Path) RestQuery(org.opencastproject.util.doc.rest.RestQuery) PUT(javax.ws.rs.PUT)

Example 23 with JpaRole

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

the class JpaGroupRoleProvider method addGroup.

/**
 * Adds or updates a group to the persistence.
 *
 * @param group
 *          the group to add
 */
public void addGroup(final JpaGroup group) throws UnauthorizedException {
    if (group != null && !UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, group.getRoles()))
        throw new UnauthorizedException("The user is not allowed to add or update a group with the admin role");
    Group existingGroup = loadGroup(group.getGroupId(), group.getOrganization().getId());
    if (existingGroup != null && !UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, existingGroup.getRoles()))
        throw new UnauthorizedException("The user is not allowed to update a group with the admin role");
    Set<JpaRole> roles = UserDirectoryPersistenceUtil.saveRoles(group.getRoles(), emf);
    JpaOrganization organization = UserDirectoryPersistenceUtil.saveOrganization(group.getOrganization(), emf);
    JpaGroup jpaGroup = new JpaGroup(group.getGroupId(), organization, group.getName(), group.getDescription(), roles, group.getMembers());
    // Then save the jpaGroup
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        JpaGroup foundGroup = UserDirectoryPersistenceUtil.findGroup(jpaGroup.getGroupId(), jpaGroup.getOrganization().getId(), emf);
        if (foundGroup == null) {
            em.persist(jpaGroup);
        } else {
            foundGroup.setName(jpaGroup.getName());
            foundGroup.setDescription(jpaGroup.getDescription());
            foundGroup.setMembers(jpaGroup.getMembers());
            foundGroup.setRoles(roles);
            em.merge(foundGroup);
        }
        tx.commit();
        messageSender.sendObjectMessage(GroupItem.GROUP_QUEUE, MessageSender.DestinationType.Queue, GroupItem.update(JaxbGroup.fromGroup(jpaGroup)));
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        if (em != null)
            em.close();
    }
}
Also used : JpaGroup(org.opencastproject.security.impl.jpa.JpaGroup) JpaGroup(org.opencastproject.security.impl.jpa.JpaGroup) JaxbGroup(org.opencastproject.security.api.JaxbGroup) Group(org.opencastproject.security.api.Group) EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) JpaOrganization(org.opencastproject.security.impl.jpa.JpaOrganization) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) JpaRole(org.opencastproject.security.impl.jpa.JpaRole)

Example 24 with JpaRole

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

the class UserDirectoryPersistenceUtil method saveRoles.

/**
 * Persist a set of roles
 *
 * @param roles
 *          the roles to persist
 * @param emf
 *          the entity manager factory
 * @return the persisted roles
 */
public static Set<JpaRole> saveRoles(Set<? extends Role> roles, EntityManagerFactory emf) {
    Set<JpaRole> updatedRoles = new HashSet<JpaRole>();
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        // Save or update roles
        for (Role role : roles) {
            JpaRole jpaRole = (JpaRole) role;
            saveOrganization((JpaOrganization) jpaRole.getOrganization(), emf);
            JpaRole findRole = findRole(jpaRole.getName(), jpaRole.getOrganization().getId(), emf);
            if (findRole == null) {
                em.persist(jpaRole);
                updatedRoles.add(jpaRole);
            } else {
                findRole.setDescription(jpaRole.getDescription());
                updatedRoles.add(em.merge(findRole));
            }
        }
        tx.commit();
        return updatedRoles;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        if (em != null)
            em.close();
    }
}
Also used : JpaRole(org.opencastproject.security.impl.jpa.JpaRole) Role(org.opencastproject.security.api.Role) EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) JpaRole(org.opencastproject.security.impl.jpa.JpaRole) HashSet(java.util.HashSet)

Example 25 with JpaRole

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

the class UserDirectoryPersistenceUtil method findRole.

/**
 * Returns the persisted role by the name and organization id
 *
 * @param name
 *          the role name
 * @param organization
 *          the organization id
 * @param emf
 *          the entity manager factory
 * @return the user or <code>null</code> if not found
 */
public static JpaRole findRole(String name, String organization, EntityManagerFactory emf) {
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query query = em.createNamedQuery("Role.findByName");
        query.setParameter("name", name);
        query.setParameter("org", organization);
        return (JpaRole) query.getSingleResult();
    } catch (NoResultException e) {
        return null;
    } finally {
        if (em != null)
            em.close();
    }
}
Also used : EntityManager(javax.persistence.EntityManager) Query(javax.persistence.Query) JpaRole(org.opencastproject.security.impl.jpa.JpaRole) NoResultException(javax.persistence.NoResultException)

Aggregations

JpaRole (org.opencastproject.security.impl.jpa.JpaRole)37 HashSet (java.util.HashSet)18 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)18 JpaUser (org.opencastproject.security.impl.jpa.JpaUser)18 Test (org.junit.Test)16 JpaOrganization (org.opencastproject.security.impl.jpa.JpaOrganization)14 JpaGroup (org.opencastproject.security.impl.jpa.JpaGroup)12 NotFoundException (org.opencastproject.util.NotFoundException)11 Role (org.opencastproject.security.api.Role)9 Path (javax.ws.rs.Path)6 RestQuery (org.opencastproject.util.doc.rest.RestQuery)6 EntityManager (javax.persistence.EntityManager)5 EntityTransaction (javax.persistence.EntityTransaction)4 Group (org.opencastproject.security.api.Group)4 SecurityService (org.opencastproject.security.api.SecurityService)4 User (org.opencastproject.security.api.User)4 Date (java.util.Date)3 POST (javax.ws.rs.POST)3 PUT (javax.ws.rs.PUT)3 JSONArray (org.json.simple.JSONArray)3