Search in sources :

Example 46 with IUserContext

use of org.eclipse.vorto.repository.core.IUserContext in project vorto by eclipse.

the class ModelRepositoryEventListener method makeModelsAnonymous.

private void makeModelsAnonymous(AppEvent event) {
    String username = (String) event.getSubject();
    IUserContext technicalUserContext = PrivilegedUserContextProvider.systemAdminContext(USER_ADMIN);
    List<ModelInfo> result = searchService.search("userReference:" + username, technicalUserContext);
    result.forEach(model -> {
        IModelRepository repository = repositoryFactory.getRepositoryByModel(model.getId(), technicalUserContext);
        if (model.getAuthor() != null && model.getAuthor().equals(username)) {
            model.setAuthor(User.USER_ANONYMOUS);
        }
        Map<String, String> properties = new HashMap<>();
        properties.put(VORTO_AUTHOR, User.USER_ANONYMOUS);
        repository.updatePropertyInElevatedSession(model.getId(), properties, technicalUserContext);
    });
}
Also used : IModelRepository(org.eclipse.vorto.repository.core.IModelRepository) IUserContext(org.eclipse.vorto.repository.core.IUserContext) ModelInfo(org.eclipse.vorto.repository.core.ModelInfo) HashMap(java.util.HashMap)

Example 47 with IUserContext

use of org.eclipse.vorto.repository.core.IUserContext in project vorto by eclipse.

the class ModelRepositoryController method saveModel.

@ApiOperation("Saves a model to the repository.")
@PreAuthorize("hasAuthority('sysadmin') or " + "hasPermission(T(org.eclipse.vorto.model.ModelId).fromPrettyFormat(#modelId)," + "T(org.eclipse.vorto.repository.core.PolicyEntry.Permission).MODIFY)")
@PutMapping(value = "/{modelId:.+}", produces = "application/json")
public ResponseEntity<ValidationReport> saveModel(@ApiParam(value = "modelId", required = true) @PathVariable String modelId, @RequestBody ModelContent content) {
    try {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        IModelRepository modelRepository = getModelRepository(ModelId.fromPrettyFormat(modelId));
        ModelId modelID = ModelId.fromPrettyFormat(modelId);
        if (modelRepository.getById(modelID) == null) {
            return new ResponseEntity<>(ValidationReport.invalid(null, "Model was not found"), HttpStatus.NOT_FOUND);
        }
        IUserContext userContext = UserContext.user(authentication, getWorkspaceId(modelId));
        ModelResource modelInfo = (ModelResource) modelParserFactory.getParser("model" + ModelType.valueOf(content.getType()).getExtension()).parse(new ByteArrayInputStream(content.getContentDsl().getBytes()));
        if (!modelID.equals(modelInfo.getId())) {
            return new ResponseEntity<>(ValidationReport.invalid(modelInfo, "You may not change the model ID (name, namespace, version). For this please create a new model."), HttpStatus.BAD_REQUEST);
        }
        ValidationReport validationReport = modelValidationHelper.validateModelUpdate(modelInfo, userContext);
        if (validationReport.isValid()) {
            modelRepository.save(modelInfo.getId(), content.getContentDsl().getBytes(), modelInfo.getId().getName() + modelInfo.getType().getExtension(), userContext);
        }
        return new ResponseEntity<>(validationReport, HttpStatus.OK);
    } catch (ValidationException validationException) {
        LOGGER.warn(validationException);
        return new ResponseEntity<>(ValidationReport.invalid(null, validationException), HttpStatus.BAD_REQUEST);
    }
}
Also used : IModelRepository(org.eclipse.vorto.repository.core.IModelRepository) IUserContext(org.eclipse.vorto.repository.core.IUserContext) ResponseEntity(org.springframework.http.ResponseEntity) ModelResource(org.eclipse.vorto.repository.core.ModelResource) ValidationException(org.eclipse.vorto.repository.core.impl.validation.ValidationException) ByteArrayInputStream(java.io.ByteArrayInputStream) ValidationReport(org.eclipse.vorto.repository.importer.ValidationReport) Authentication(org.springframework.security.core.Authentication) ModelId(org.eclipse.vorto.model.ModelId) ApiOperation(io.swagger.annotations.ApiOperation) PutMapping(org.springframework.web.bind.annotation.PutMapping) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 48 with IUserContext

use of org.eclipse.vorto.repository.core.IUserContext in project vorto by eclipse.

the class ModelRepositoryController method uploadModelImage.

@PostMapping("/{modelId:.+}/images")
@PreAuthorize("hasAuthority('sysadmin') or " + "hasPermission(T(org.eclipse.vorto.model.ModelId).fromPrettyFormat(#modelId)," + "T(org.eclipse.vorto.repository.core.PolicyEntry.Permission).MODIFY)")
public ResponseEntity<AttachResult> uploadModelImage(@ApiParam(value = "The image to upload", required = true) @RequestParam("file") MultipartFile file, @ApiParam(value = "The model ID of vorto model, e.g. com.mycompany.Car:1.0.0", required = true) @PathVariable final String modelId) {
    LOGGER.info("uploadImage: [" + file.getOriginalFilename() + ", " + file.getSize() + "]");
    ModelId actualModelID = ModelId.fromPrettyFormat(modelId);
    if (!attachmentValidator.validateAttachmentSize(file.getSize())) {
        return new ResponseEntity<>(AttachResult.fail(actualModelID, file.getOriginalFilename(), String.format("The attachment is too large. Maximum size allowed is %dMB", attachmentValidator.getMaxFileSizeSetting())), HttpStatus.PAYLOAD_TOO_LARGE);
    }
    try {
        IUserContext user = UserContext.user(SecurityContextHolder.getContext().getAuthentication(), getWorkspaceId(modelId));
        getModelRepository(actualModelID).attachFile(actualModelID, new FileContent(file.getOriginalFilename(), file.getBytes()), user, Attachment.TAG_IMAGE, Attachment.TAG_DISPLAY_IMAGE);
    } catch (IOException e) {
        throw new GenericApplicationException("error in attaching file to model '" + modelId + "'", e);
    }
    return new ResponseEntity<>(AttachResult.success(actualModelID, file.getOriginalFilename()), HttpStatus.CREATED);
}
Also used : FileContent(org.eclipse.vorto.repository.core.FileContent) IUserContext(org.eclipse.vorto.repository.core.IUserContext) ResponseEntity(org.springframework.http.ResponseEntity) IOException(java.io.IOException) GenericApplicationException(org.eclipse.vorto.repository.web.GenericApplicationException) ModelId(org.eclipse.vorto.model.ModelId) PostMapping(org.springframework.web.bind.annotation.PostMapping) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 49 with IUserContext

use of org.eclipse.vorto.repository.core.IUserContext in project vorto by eclipse.

the class ModelRepositoryController method createVersionOfModel.

@ApiOperation(value = "Creates a new version for the given model in the specified version")
@PreAuthorize("hasAuthority('sysadmin') or (hasAuthority('model_creator') and " + "hasPermission(T(org.eclipse.vorto.model.ModelId).fromPrettyFormat(#modelId)," + "T(org.eclipse.vorto.repository.core.PolicyEntry.Permission).READ))")
@PostMapping(value = "/{modelId:.+}/versions/{modelVersion:.+}", produces = "application/json")
public ResponseEntity<ModelInfo> createVersionOfModel(@ApiParam(value = "modelId", required = true) @PathVariable String modelId, @ApiParam(value = "modelVersion", required = true) @PathVariable String modelVersion) throws WorkflowException {
    final ModelId modelID = ModelId.fromPrettyFormat(modelId);
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    try {
        IUserContext userContext = UserContext.user(authentication, getWorkspaceId(modelId));
        ModelResource resource = getModelRepository(modelID).createVersion(modelID, modelVersion, userContext);
        this.workflowService.start(resource.getId(), userContext);
        return new ResponseEntity<>(resource, HttpStatus.CREATED);
    } catch (FatalModelRepositoryException e) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}
Also used : IUserContext(org.eclipse.vorto.repository.core.IUserContext) ResponseEntity(org.springframework.http.ResponseEntity) ModelResource(org.eclipse.vorto.repository.core.ModelResource) Authentication(org.springframework.security.core.Authentication) FatalModelRepositoryException(org.eclipse.vorto.repository.core.FatalModelRepositoryException) ModelId(org.eclipse.vorto.model.ModelId) PostMapping(org.springframework.web.bind.annotation.PostMapping) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 50 with IUserContext

use of org.eclipse.vorto.repository.core.IUserContext 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)

Aggregations

IUserContext (org.eclipse.vorto.repository.core.IUserContext)54 Test (org.junit.Test)32 ModelInfo (org.eclipse.vorto.repository.core.ModelInfo)28 ClassPathResource (org.springframework.core.io.ClassPathResource)18 ResponseEntity (org.springframework.http.ResponseEntity)14 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)14 DoesNotExistException (org.eclipse.vorto.repository.services.exceptions.DoesNotExistException)10 OperationForbiddenException (org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException)8 ModelId (org.eclipse.vorto.model.ModelId)7 IModelRepository (org.eclipse.vorto.repository.core.IModelRepository)6 User (org.eclipse.vorto.repository.domain.User)6 PostMapping (org.springframework.web.bind.annotation.PostMapping)5 PutMapping (org.springframework.web.bind.annotation.PutMapping)5 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 Namespace (org.eclipse.vorto.repository.domain.Namespace)4 ApiOperation (io.swagger.annotations.ApiOperation)3 IOException (java.io.IOException)3 HashSet (java.util.HashSet)3 ModelResource (org.eclipse.vorto.repository.core.ModelResource)3 InvalidUserException (org.eclipse.vorto.repository.services.exceptions.InvalidUserException)3