Search in sources :

Example 1 with OperationForbiddenException

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

the class ModelRepositoryController method getUserModels.

// ##################### Downloads ################################
@GetMapping(value = { "/mine/download" })
public void getUserModels(Principal principal, final HttpServletResponse response) {
    List<ModelId> userModels = Lists.newArrayList();
    User user = accountService.getUser(principal.getName());
    Collection<Namespace> namespaces = null;
    try {
        namespaces = userNamespaceRoleService.getNamespaces(user, user);
    } catch (OperationForbiddenException | DoesNotExistException e) {
        LOGGER.error(e.getMessage(), e);
    }
    for (Namespace namespace : namespaces) {
        IModelRepository modelRepo = getModelRepository(namespace.getWorkspaceId());
        List<ModelInfo> modelInfos = modelRepo.search(String.format("author:%s", user.getUsername()));
        List<ModelId> modelIds = modelInfos.stream().map(modelInfo -> modelInfo.getId()).collect(Collectors.toList());
        userModels.addAll(modelIds);
    }
    LOGGER.info("Exporting information models for user - results: " + userModels.size());
    sendAsZipFile(response, user.getUsername() + "-models.zip", getModelsAndDependencies(userModels));
}
Also used : IModelRepository(org.eclipse.vorto.repository.core.IModelRepository) InfomodelTemplate(org.eclipse.vorto.repository.web.core.templates.InfomodelTemplate) RequestParam(org.springframework.web.bind.annotation.RequestParam) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ApiParam(io.swagger.annotations.ApiParam) Autowired(org.springframework.beans.factory.annotation.Autowired) ModelAlreadyExistsException(org.eclipse.vorto.repository.core.ModelAlreadyExistsException) ModelInfo(org.eclipse.vorto.repository.core.ModelInfo) RequestContextHolder(org.springframework.web.context.request.RequestContextHolder) Future(java.util.concurrent.Future) Map(java.util.Map) Diagnostic(org.eclipse.vorto.repository.core.Diagnostic) AsyncModelMappingsFetcher(org.eclipse.vorto.repository.web.core.async.AsyncModelMappingsFetcher) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) ModelParserFactory(org.eclipse.vorto.repository.core.impl.parser.ModelParserFactory) PostMapping(org.springframework.web.bind.annotation.PostMapping) AsyncModelLinksFetcher(org.eclipse.vorto.repository.web.core.async.AsyncModelLinksFetcher) NotAuthorizedException(org.eclipse.vorto.repository.web.core.exceptions.NotAuthorizedException) User(org.eclipse.vorto.repository.domain.User) Namespace(org.eclipse.vorto.repository.domain.Namespace) RestController(org.springframework.web.bind.annotation.RestController) Executors(java.util.concurrent.Executors) IOUtils(org.apache.commons.io.IOUtils) Permission(org.eclipse.vorto.repository.core.PolicyEntry.Permission) DefaultUserAccountService(org.eclipse.vorto.repository.account.impl.DefaultUserAccountService) ZipOutputStream(java.util.zip.ZipOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ModelFullDetailsDTO(org.eclipse.vorto.repository.web.api.v1.dto.ModelFullDetailsDTO) ControllerUtils(org.eclipse.vorto.repository.web.ControllerUtils) ModelLink(org.eclipse.vorto.repository.web.api.v1.dto.ModelLink) IModelRepository(org.eclipse.vorto.repository.core.IModelRepository) Value(org.springframework.beans.factory.annotation.Value) RequestBody(org.springframework.web.bind.annotation.RequestBody) FatalModelRepositoryException(org.eclipse.vorto.repository.core.FatalModelRepositoryException) IWorkflowService(org.eclipse.vorto.repository.workflow.IWorkflowService) Lists(com.google.common.collect.Lists) Attachment(org.eclipse.vorto.repository.core.Attachment) AsyncModelSyntaxFetcher(org.eclipse.vorto.repository.web.core.async.AsyncModelSyntaxFetcher) UserRepositoryRoleService(org.eclipse.vorto.repository.services.UserRepositoryRoleService) ModelProperty(org.eclipse.vorto.model.ModelProperty) ModelNotReleasedException(org.eclipse.vorto.repository.model.ModelNotReleasedException) GenericApplicationException(org.eclipse.vorto.repository.web.GenericApplicationException) IOException(java.io.IOException) IModelPolicyManager(org.eclipse.vorto.repository.core.IModelPolicyManager) NamespaceService(org.eclipse.vorto.repository.services.NamespaceService) ExecutionException(java.util.concurrent.ExecutionException) HttpStatus(org.springframework.http.HttpStatus) ApiResponse(io.swagger.annotations.ApiResponse) AttachmentValidator(org.eclipse.vorto.repository.core.impl.validation.AttachmentValidator) AttachResult(org.eclipse.vorto.repository.web.api.v1.dto.AttachResult) ModelTemplate(org.eclipse.vorto.repository.web.core.templates.ModelTemplate) PathVariable(org.springframework.web.bind.annotation.PathVariable) ValidationReport(org.eclipse.vorto.repository.importer.ValidationReport) DoesNotExistException(org.eclipse.vorto.repository.services.exceptions.DoesNotExistException) ApiOperation(io.swagger.annotations.ApiOperation) Logger(org.apache.log4j.Logger) AbstractRepositoryController(org.eclipse.vorto.repository.web.AbstractRepositoryController) ByteArrayInputStream(java.io.ByteArrayInputStream) PutMapping(org.springframework.web.bind.annotation.PutMapping) ModelMinimalInfoDTO(org.eclipse.vorto.repository.web.api.v1.dto.ModelMinimalInfoDTO) ZipEntry(java.util.zip.ZipEntry) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping) AsyncWorkflowActionsFetcher(org.eclipse.vorto.repository.web.core.async.AsyncWorkflowActionsFetcher) FileContent(org.eclipse.vorto.repository.core.FileContent) IDiagnostics(org.eclipse.vorto.repository.core.IDiagnostics) Collection(java.util.Collection) ModelValidationHelper(org.eclipse.vorto.repository.core.impl.utils.ModelValidationHelper) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) OperationForbiddenException(org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException) Collectors(java.util.stream.Collectors) ModelId(org.eclipse.vorto.model.ModelId) Objects(java.util.Objects) List(java.util.List) Principal(java.security.Principal) Optional(java.util.Optional) WorkflowException(org.eclipse.vorto.repository.workflow.WorkflowException) Authentication(org.springframework.security.core.Authentication) IUserContext(org.eclipse.vorto.repository.core.IUserContext) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) HashMap(java.util.HashMap) ApiResponses(io.swagger.annotations.ApiResponses) AsyncModelAttachmentsFetcher(org.eclipse.vorto.repository.web.core.async.AsyncModelAttachmentsFetcher) Status(org.eclipse.vorto.repository.web.Status) GetMapping(org.springframework.web.bind.annotation.GetMapping) ExecutorService(java.util.concurrent.ExecutorService) ModelContent(org.eclipse.vorto.repository.web.core.dto.ModelContent) ModelNamespaceNotOfficialException(org.eclipse.vorto.repository.model.ModelNamespaceNotOfficialException) AsyncModelReferenceFetcher(org.eclipse.vorto.repository.web.core.async.AsyncModelReferenceFetcher) IBulkOperationsService(org.eclipse.vorto.repository.model.IBulkOperationsService) UserNamespaceRoleService(org.eclipse.vorto.repository.services.UserNamespaceRoleService) HttpServletResponse(javax.servlet.http.HttpServletResponse) PolicyEntry(org.eclipse.vorto.repository.core.PolicyEntry) ValidationException(org.eclipse.vorto.repository.core.impl.validation.ValidationException) ModelType(org.eclipse.vorto.model.ModelType) TimeUnit(java.util.concurrent.TimeUnit) ModelResource(org.eclipse.vorto.repository.core.ModelResource) PrincipalType(org.eclipse.vorto.repository.core.PolicyEntry.PrincipalType) MultipartFile(org.springframework.web.multipart.MultipartFile) ResponseEntity(org.springframework.http.ResponseEntity) UserContext(org.eclipse.vorto.repository.core.impl.UserContext) OperationForbiddenException(org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException) DoesNotExistException(org.eclipse.vorto.repository.services.exceptions.DoesNotExistException) ModelInfo(org.eclipse.vorto.repository.core.ModelInfo) User(org.eclipse.vorto.repository.domain.User) ModelId(org.eclipse.vorto.model.ModelId) Namespace(org.eclipse.vorto.repository.domain.Namespace) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 2 with OperationForbiddenException

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

the class AccountController method deleteUserAccount.

@DeleteMapping("/rest/accounts/{username:.+}")
@PreAuthorize("hasAuthority('sysadmin') or hasPermission(#username,'user:delete')")
public ResponseEntity<Void> deleteUserAccount(@PathVariable("username") final String username) {
    try {
        IUserContext userContext = UserContext.user(SecurityContextHolder.getContext().getAuthentication());
        userService.delete(userContext.getUsername(), username);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    } catch (OperationForbiddenException ofe) {
        return new ResponseEntity<>(HttpStatus.FORBIDDEN);
    } catch (DoesNotExistException dnee) {
        return new ResponseEntity<>(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) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 3 with OperationForbiddenException

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

the class NamespaceController method getCollaboratorsByNamespace.

/**
 * @param namespace
 * @return all users of a given namespace, if the user acting the call has either administrative rights on the namespace, or on the repository.
 */
@RequestMapping(method = RequestMethod.GET, value = "/{namespace:.+}/users")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<Collection<Collaborator>> getCollaboratorsByNamespace(@ApiParam(value = "namespace", required = true) @PathVariable String namespace) {
    Collection<Collaborator> collaborators = new HashSet<>();
    try {
        IUserContext userContext = UserContext.user(SecurityContextHolder.getContext().getAuthentication());
        collaborators = EntityDTOConverter.createCollaborators(userNamespaceRoleService.getRolesByUser(userContext.getUsername(), namespace));
        return new ResponseEntity<>(collaborators, HttpStatus.OK);
    } catch (OperationForbiddenException ofe) {
        return new ResponseEntity<>(collaborators, HttpStatus.FORBIDDEN);
    } catch (DoesNotExistException d) {
        return new ResponseEntity<>(collaborators, 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) Collaborator(org.eclipse.vorto.repository.web.api.v1.dto.Collaborator) HashSet(java.util.HashSet) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 4 with OperationForbiddenException

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

the class NamespaceController method getAllNamespacesForLoggedUser.

/**
 * @return all namespaces the logged on user has access to.
 */
@RequestMapping(method = RequestMethod.GET, value = "/all")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<Collection<NamespaceDto>> getAllNamespacesForLoggedUser() {
    IUserContext userContext = UserContext.user(SecurityContextHolder.getContext().getAuthentication());
    Collection<NamespaceDto> namespaces = new TreeSet<>(Comparator.comparing(NamespaceDto::getName));
    try {
        for (Map.Entry<Namespace, Map<User, Collection<IRole>>> entry : userNamespaceRoleService.getNamespacesCollaboratorsAndRoles(userContext.getUsername(), userContext.getUsername(), "namespace_admin").entrySet()) {
            namespaces.add(EntityDTOConverter.createNamespaceDTO(entry.getKey(), entry.getValue()));
        }
    } catch (OperationForbiddenException ofe) {
        return new ResponseEntity<>(namespaces, HttpStatus.FORBIDDEN);
    } catch (DoesNotExistException d) {
        return new ResponseEntity<>(namespaces, HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<>(namespaces, HttpStatus.OK);
}
Also used : IUserContext(org.eclipse.vorto.repository.core.IUserContext) NamespaceDto(org.eclipse.vorto.repository.web.api.v1.dto.NamespaceDto) OperationForbiddenException(org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException) DoesNotExistException(org.eclipse.vorto.repository.services.exceptions.DoesNotExistException) ResponseEntity(org.springframework.http.ResponseEntity) IRole(org.eclipse.vorto.repository.domain.IRole) TreeSet(java.util.TreeSet) Map(java.util.Map) Namespace(org.eclipse.vorto.repository.domain.Namespace) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with OperationForbiddenException

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

the class UserService method delete.

/**
 * Deletes the given {@link User} and their namespace-role associations, as acted by the given
 * acting {@link User}.<br/>
 * This can fail for a number of reasons:
 * <ul>
 *   <li>
 *     The acting {@link User} does not have the {@literal sysadmin} repository role, or is not
 *     the same {@link User} as the target.
 *   </li>
 *   <li>
 *     The target {@link User} owns a {@link org.eclipse.vorto.repository.domain.Namespace} - in
 *     which case, ownership should be given to another {@link User} before deleting.
 *   </li>
 *   <li>
 *     The target {@link User} is the only one listed with namespace role {@literal namespace_admin}
 *     on one or more {@link org.eclipse.vorto.repository.domain.Namespace}s - in which case, the
 *     role should be given to at least one other {@link User} before deleting.
 *   </li>
 * </ul>
 * Failures above will throw checked exceptions. <br/>
 * It is also possible that this method will fail by returning {@code false}, should the target
 * {@link User} simply not exist.
 *
 * @param actor
 * @param target
 * @return
 */
@Transactional(rollbackFor = { OperationForbiddenException.class, DoesNotExistException.class })
public boolean delete(User actor, User target) throws OperationForbiddenException, DoesNotExistException {
    // boilerplate null validation
    ServiceValidationUtil.validateNulls(actor, target);
    if (cache.withUser(target).getUser() == null) {
        LOGGER.info("Attempting to delete a user that does not exist. ");
        return false;
    }
    // authorizing actor
    userUtil.authorizeActorAsTargetOrSysadmin(actor, target);
    // checking if only admin in any namespace
    if (userNamespaceRoleService.isOnlyAdminInAnyNamespace(actor, target)) {
        throw new OperationForbiddenException("User is the only administrator of at least one namespace - aborting delete operation.");
    }
    // retrieving namespaces target manages
    Collection<Namespace> namespacesManagedByTarget = userNamespaceRoleService.getNamespacesAndRolesByUser(actor, target).entrySet().stream().filter(e -> e.getValue().contains(userNamespaceRoleService.namespaceAdminRole())).map(Entry::getKey).collect(Collectors.toSet());
    // target owns at least one namespace - failing
    if (!namespacesManagedByTarget.isEmpty()) {
        throw new OperationForbiddenException("User is administrator in at least one namespace. Ownership must change before user can be deleted. Aborting operation.");
    }
    // collecting target user's e-mail address if any
    DeleteAccountMessage message = null;
    if (target.hasEmailAddress()) {
        message = new DeleteAccountMessage(target);
    }
    // firstly, publish the user deleted event - this way, the models are all anonymized while the
    // user and their namespace associations are still there
    eventPublisher.publishEvent(new AppEvent(this, target.getUsername(), EventType.USER_DELETED));
    // then, retrie namespaces where target has any role
    Collection<Namespace> namespacesWhereTargetHasAnyRole = userNamespaceRoleService.getNamespaces(actor, target);
    // and remove association for all namespaces
    for (Namespace namespace : namespacesWhereTargetHasAnyRole) {
        userNamespaceRoleService.deleteAllRoles(actor, target, namespace, false);
    }
    // finally, delete target user
    userRepository.delete(target);
    // and send them a message if possible
    if (message != null) {
        notificationService.sendNotification(message);
    }
    return true;
}
Also used : AppEvent(org.eclipse.vorto.repository.core.events.AppEvent) OperationForbiddenException(org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException) Namespace(org.eclipse.vorto.repository.domain.Namespace) DeleteAccountMessage(org.eclipse.vorto.repository.notification.message.DeleteAccountMessage) Transactional(org.springframework.transaction.annotation.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