Search in sources :

Example 6 with OperationForbiddenException

use of org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException in project vorto by eclipse.

the class NamespaceController method createTechnicalUserForNamespace.

/**
 * Creates a technical user with the given {@link Collaborator} and associates them to the given
 * namespace, with the desired roles held by the collaborator.
 *
 * @param namespace
 * @param collaborator
 * @return
 */
@RequestMapping(method = RequestMethod.POST, value = "/{namespace:.+}/users")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<Boolean> createTechnicalUserForNamespace(@ApiParam(value = "namespace", required = true) @PathVariable String namespace, @RequestBody @ApiParam(value = "The user to be associated with the namespace", required = true) final Collaborator collaborator) {
    try {
        IUserContext userContext = UserContext.user(SecurityContextHolder.getContext().getAuthentication());
        User user = EntityDTOConverter.createUser(userUtil, collaborator);
        userNamespaceRoleService.createTechnicalUserAndAddAsCollaborator(userContext.getUsername(), user, namespace, collaborator.getRoles());
        return new ResponseEntity<>(true, HttpStatus.CREATED);
    } catch (InvalidUserException ie) {
        return new ResponseEntity<>(false, HttpStatus.BAD_REQUEST);
    } catch (OperationForbiddenException ofe) {
        return new ResponseEntity<>(false, HttpStatus.FORBIDDEN);
    } catch (DoesNotExistException d) {
        return new ResponseEntity<>(false, HttpStatus.NOT_FOUND);
    }
}
Also used : IUserContext(org.eclipse.vorto.repository.core.IUserContext) ResponseEntity(org.springframework.http.ResponseEntity) OperationForbiddenException(org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException) DoesNotExistException(org.eclipse.vorto.repository.services.exceptions.DoesNotExistException) User(org.eclipse.vorto.repository.domain.User) InvalidUserException(org.eclipse.vorto.repository.services.exceptions.InvalidUserException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 7 with OperationForbiddenException

use of org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException in project vorto by eclipse.

the class NamespaceController method createNamespace.

/**
 * Creates a new namespace with the given name for the authenticated user. <br/>
 * Automatically adds the user as owner and gives them all applicable roles on the namespace.<br/>
 * Subject to restrictions in terms of number of private namespaces owned, and whether the user
 * has the sufficient repository privileges to own a non-private namespace.
 *
 * @param namespace
 * @return
 */
@PutMapping(value = "/{namespace:.+}", produces = "application/json")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<OperationResult> createNamespace(@ApiParam(value = "The name of the namespace to be created", required = true) @PathVariable final String namespace) {
    try {
        IUserContext userContext = UserContext.user(SecurityContextHolder.getContext().getAuthentication());
        namespaceService.create(userContext.getUsername(), userContext.getUsername(), namespace);
        return new ResponseEntity<>(OperationResult.success(), HttpStatus.CREATED);
    } catch (DoesNotExistException | NameSyntaxException e) {
        return new ResponseEntity<>(OperationResult.failure(e.getMessage()), HttpStatus.BAD_REQUEST);
    } catch (PrivateNamespaceQuotaExceededException pnqee) {
        return new ResponseEntity<>(OperationResult.failure(pnqee.getMessage()), HttpStatus.FORBIDDEN);
    }// omitting explicit collision message and just going with status here
     catch (CollisionException ce) {
        return new ResponseEntity<>(OperationResult.failure(""), HttpStatus.CONFLICT);
    } catch (OperationForbiddenException ofe) {
        return new ResponseEntity<>(OperationResult.failure(ofe.getMessage()), HttpStatus.FORBIDDEN);
    }
}
Also used : IUserContext(org.eclipse.vorto.repository.core.IUserContext) ResponseEntity(org.springframework.http.ResponseEntity) DoesNotExistException(org.eclipse.vorto.repository.services.exceptions.DoesNotExistException) OperationForbiddenException(org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException) PrivateNamespaceQuotaExceededException(org.eclipse.vorto.repository.services.exceptions.PrivateNamespaceQuotaExceededException) CollisionException(org.eclipse.vorto.repository.services.exceptions.CollisionException) NameSyntaxException(org.eclipse.vorto.repository.services.exceptions.NameSyntaxException) PutMapping(org.springframework.web.bind.annotation.PutMapping) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 8 with OperationForbiddenException

use of org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException in project vorto by eclipse.

the class NamespaceController method addOrUpdateCollaboratorForNamespace.

/**
 * Sets the roles of the given user on the given namespace.
 *
 * @param namespace
 * @param collaborator
 * @return
 */
@PreAuthorize("isAuthenticated()")
@RequestMapping(method = RequestMethod.PUT, value = "/{namespace:.+}/users")
public ResponseEntity<Boolean> addOrUpdateCollaboratorForNamespace(@ApiParam(value = "namespace", required = true) @PathVariable String namespace, @RequestBody @ApiParam(value = "The user to be associated with the namespace", required = true) final Collaborator collaborator) {
    try {
        // no validation here save for essentials: we are pointing to an existing user
        User user = EntityDTOConverter.createUser(null, collaborator);
        IUserContext userContext = UserContext.user(SecurityContextHolder.getContext().getAuthentication());
        return new ResponseEntity<>(userNamespaceRoleService.setRoles(userContext.getUsername(), user.getUsername(), namespace, collaborator.getRoles(), false), HttpStatus.OK);
    } catch (InvalidUserException iue) {
        return new ResponseEntity<>(false, HttpStatus.BAD_REQUEST);
    } catch (OperationForbiddenException ofe) {
        return new ResponseEntity<>(false, HttpStatus.FORBIDDEN);
    } catch (DoesNotExistException d) {
        return new ResponseEntity<>(false, HttpStatus.NOT_FOUND);
    }
}
Also used : IUserContext(org.eclipse.vorto.repository.core.IUserContext) ResponseEntity(org.springframework.http.ResponseEntity) OperationForbiddenException(org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException) DoesNotExistException(org.eclipse.vorto.repository.services.exceptions.DoesNotExistException) User(org.eclipse.vorto.repository.domain.User) InvalidUserException(org.eclipse.vorto.repository.services.exceptions.InvalidUserException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 9 with OperationForbiddenException

use of org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException in project vorto by eclipse.

the class NamespaceService method findWorkspaceIdsOfPossibleReferences.

public Set<String> findWorkspaceIdsOfPossibleReferences() {
    Set<Namespace> visibleNamespaces = new HashSet<>(cache.namespaces(NamespaceRequestCache.PUBLIC));
    IUserContext userContext = UserContext.user(SecurityContextHolder.getContext().getAuthentication());
    if (!userContext.isAnonymous()) {
        User user = userRolesRequestCache.withUser(userContext.getUsername()).getUser();
        try {
            visibleNamespaces.addAll(userNamespaceRoleService.getNamespaces(user, user, (Long) null));
        } catch (OperationForbiddenException | DoesNotExistException e) {
            throw new IllegalStateException(e);
        }
    }
    return visibleNamespaces.stream().map(Namespace::getWorkspaceId).collect(Collectors.toSet());
}
Also used : IUserContext(org.eclipse.vorto.repository.core.IUserContext) OperationForbiddenException(org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException) DoesNotExistException(org.eclipse.vorto.repository.services.exceptions.DoesNotExistException) User(org.eclipse.vorto.repository.domain.User) Namespace(org.eclipse.vorto.repository.domain.Namespace) HashSet(java.util.HashSet)

Example 10 with OperationForbiddenException

use of org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException in project vorto by eclipse.

the class UserNamespaceRoleService method deleteAllRoles.

/**
 * Deletes the {@link User} + {@link Namespace} role association for the given {@link User} and
 * {@link Namespace} entirely. <br/>
 * The operation is permitted in the following cases:
 * <ol>
 *   <li>
 *     The acting user is sysadmin.
 *   </li>
 *   <li>
 *     The acting user is trying to remove themselves and is not the only administrator of the
 *     namespace.
 *   </li>
 *   <li>
 *     The acting user is trying to remove themselves and is the only administrator of the
 *     namespace, but they are deleting the namespace - this will fail early
 *     in {@link NamespaceService#deleteNamespace(User, String)} if the namespace has public
 *     models.
 *   </li>
 * </ol>
 * In any other case, the operation will fail and throw {@link OperationForbiddenException}.
 *
 * @param actor
 * @param target
 * @param namespace
 * @param deleteNamespace
 * @return
 * @throws DoesNotExistException
 */
@Transactional(rollbackOn = { DoesNotExistException.class, OperationForbiddenException.class })
public boolean deleteAllRoles(User actor, User target, Namespace namespace, boolean deleteNamespace) throws DoesNotExistException, OperationForbiddenException {
    // boilerplate null validation
    ServiceValidationUtil.validate(actor, target, namespace);
    ServiceValidationUtil.validateNulls(actor.getId(), target.getId(), namespace.getId());
    // namespace does not exist
    if (!namespaceRequestCache.namespace(namespace::equals).isPresent()) {
        throw new DoesNotExistException("Namespace [%s] does not exist - aborting deletion of user roles.");
    }
    // deleting the whole namespace: forbidden
    if (hasRole(actor, namespace, namespaceAdminRole()) && actor.equals(target) && !deleteNamespace) {
        throw new OperationForbiddenException(String.format("Acting user with namespace administrator role cannot remove themselves from namespace [%s].", namespace.getName()));
    } else // sysadmin
    if (!hasRole(actor, namespace, namespaceAdminRole()) && !actor.equals(target) && isNotSysadmin(actor)) {
        throw new OperationForbiddenException(String.format("Acting user cannot delete user roles for namespace [%s].", namespace.getName()));
    }
    Optional<UserNamespaceRoles> rolesToDelete = cache.withUser(target).getUserNamespaceRoles().stream().filter(unr -> unr.getNamespace().equals(namespace)).findAny();
    // user-namespace role association does not exist
    if (!rolesToDelete.isPresent()) {
        LOGGER.warn("Attempting to delete non existing user namespace roles. Aborting.");
        return false;
    }
    userNamespaceRoleRepository.delete(rolesToDelete.get().getID());
    LOGGER.info("Deleted user-namespace role association.");
    notificationService.sendNotificationAsync(new RemovedFromNamespaceMessage(target, namespace.getName()));
    return true;
}
Also used : ApplicationEventPublisherAware(org.springframework.context.ApplicationEventPublisherAware) org.eclipse.vorto.repository.domain(org.eclipse.vorto.repository.domain) java.util(java.util) Logger(org.slf4j.Logger) DoesNotExistException(org.eclipse.vorto.repository.services.exceptions.DoesNotExistException) Transactional(javax.transaction.Transactional) LoggerFactory(org.slf4j.LoggerFactory) OperationForbiddenException(org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException) Autowired(org.springframework.beans.factory.annotation.Autowired) NamespaceRoleRepository(org.eclipse.vorto.repository.repositories.NamespaceRoleRepository) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) RemovedFromNamespaceMessage(org.eclipse.vorto.repository.notification.message.RemovedFromNamespaceMessage) UserNamespaceRoleRepository(org.eclipse.vorto.repository.repositories.UserNamespaceRoleRepository) UserRolesRequestCache(org.eclipse.vorto.repository.core.impl.cache.UserRolesRequestCache) Service(org.springframework.stereotype.Service) RolesChangedInNamespaceMessage(org.eclipse.vorto.repository.notification.message.RolesChangedInNamespaceMessage) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) INotificationService(org.eclipse.vorto.repository.notification.INotificationService) AddedToNamespaceMessage(org.eclipse.vorto.repository.notification.message.AddedToNamespaceMessage) InvalidUserException(org.eclipse.vorto.repository.services.exceptions.InvalidUserException) NamespaceRequestCache(org.eclipse.vorto.repository.core.impl.cache.NamespaceRequestCache) DoesNotExistException(org.eclipse.vorto.repository.services.exceptions.DoesNotExistException) OperationForbiddenException(org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException) RemovedFromNamespaceMessage(org.eclipse.vorto.repository.notification.message.RemovedFromNamespaceMessage) Transactional(javax.transaction.Transactional)

Aggregations

OperationForbiddenException (org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException)10 DoesNotExistException (org.eclipse.vorto.repository.services.exceptions.DoesNotExistException)9 IUserContext (org.eclipse.vorto.repository.core.IUserContext)8 ResponseEntity (org.springframework.http.ResponseEntity)7 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)7 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 Namespace (org.eclipse.vorto.repository.domain.Namespace)4 User (org.eclipse.vorto.repository.domain.User)3 InvalidUserException (org.eclipse.vorto.repository.services.exceptions.InvalidUserException)3 HashSet (java.util.HashSet)2 Map (java.util.Map)2 Collectors (java.util.stream.Collectors)2 DeleteMapping (org.springframework.web.bind.annotation.DeleteMapping)2 Lists (com.google.common.collect.Lists)1 Sets (com.google.common.collect.Sets)1 ApiOperation (io.swagger.annotations.ApiOperation)1 ApiParam (io.swagger.annotations.ApiParam)1 ApiResponse (io.swagger.annotations.ApiResponse)1 ApiResponses (io.swagger.annotations.ApiResponses)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1