Search in sources :

Example 1 with Collaborator

use of org.eclipse.vorto.repository.web.api.v1.dto.Collaborator 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 2 with Collaborator

use of org.eclipse.vorto.repository.web.api.v1.dto.Collaborator in project vorto by eclipse.

the class EntityDTOConverter method createCollaborators.

public static Collection<Collaborator> createCollaborators(Map<User, Collection<IRole>> usersAndRoles) {
    Collection<Collaborator> result = new TreeSet<>(Comparator.comparing(Collaborator::getUserId));
    usersAndRoles.forEach((u, c) -> {
        Collaborator collaborator = new Collaborator();
        collaborator.setAuthenticationProviderId(u.getAuthenticationProviderId());
        collaborator.setRoles(c.stream().map(IRole::getName).collect(Collectors.toSet()));
        collaborator.setSubject(u.getSubject());
        collaborator.setTechnicalUser(u.isTechnicalUser());
        collaborator.setUserId(u.getUsername());
        result.add(collaborator);
    });
    return result;
}
Also used : Collaborator(org.eclipse.vorto.repository.web.api.v1.dto.Collaborator) IRole(org.eclipse.vorto.repository.domain.IRole) TreeSet(java.util.TreeSet)

Example 3 with Collaborator

use of org.eclipse.vorto.repository.web.api.v1.dto.Collaborator in project vorto by eclipse.

the class ModelRepositoryControllerTest method verifyFullModelPayloadForUI.

/**
 * This test performs the following:
 * <ol>
 *   <li>
 *     Creates the {@literal com.test} namespace with a sysadmin user, to hold the models.
 *   </li>
 *   <li>
 *     Adds a non-sysadmin user with {@literal model_creator} role to the {@literal com.test}
 *     namespace.
 *   </li>
 *   <li>
 *     Creates a "Zone" datatype model from the corresponding file resource.
 *   </li>
 *   <li>
 *     Creates a "Lamp" functionblock model from the corresponding file resource.
 *   </li>
 *   <li>
 *     Creates an "Address" functionblock model from the corresponding file resource.
 *   </li>
 *   <li>
 *     Creates a "StreetLamp" model from the corresponding file resource, using the above
 *     functionblocks as dependencies.
 *   </li>
 *   <li>
 *     Adds an attachment to the "StreetLamp" model.
 *   </li>
 *   <li>
 *     Adds a link to the "StreetLamp" model.
 *   </li>
 *   <li>
 *     Adds a mapping to the "StreetLamp" model.
 *   </li>
 *   <li>
 *     Loads the "StreetLamp" model with the REST call used by the UI, and verifies / validates:
 *     <ul>
 *       <li>
 *         Basic {@link org.eclipse.vorto.repository.core.ModelInfo} properties.
 *       </li>
 *       <li>
 *         The Base64-encoded model syntax
 *         (see {@link ModelFullDetailsDTO#getEncodedModelSyntax()})
 *       </li>
 *       <li>
 *         Mapping (see {@link ModelFullDetailsDTO#getMappings()}).
 *       </li>
 *       <li>
 *         Attachment (see {@link ModelFullDetailsDTO#getAttachments()}
 *       </li>
 *       <li>
 *         Link (see {@link ModelFullDetailsDTO#getLinks()}
 *       </li>
 *       <li>
 *         References (see {@link ModelFullDetailsDTO#getReferences()}
 *       </li>
 *       <li>
 *         "Referenced by" (see {@link ModelFullDetailsDTO#getReferencedBy()})
 *       </li>
 *       <li>
 *         Policies (see {@link ModelFullDetailsDTO#getPolicies()} and
 *         {@link ModelFullDetailsDTO#getBestPolicy()} for the creating user, and conversely, for
 *         an extraneous user with no access.
 *       </li>
 *       <li>
 *         Workflow actions (see {@link ModelFullDetailsDTO#getActions()} for the creating user,
 *         and conversely, for an extraneous user with no access.
 *       </li>
 *     </ul>
 *   </li>
 *   <li>
 *     Loads the "Lamp" functionblock model with the REST call used by the UI, and verifies the
 *     "referenced by" node (see {@link ModelFullDetailsDTO#getReferencedBy()}.
 *   </li>
 *   <li>
 *     Finally, cleans up and deletes all 4 models, then the namespace.
 *   </li>
 * </ol>
 *
 * @throws Exception
 */
@Test
public void verifyFullModelPayloadForUI() throws Exception {
    // required for some extra properties in DTOs not annotated with Jackson polymorphism
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    // model names, id strings and file names
    String namespace = "com.test";
    String version = "1.0.0";
    String idFormat = "%s.%s:%s";
    String zoneModelName = "Zone";
    String zoneModelID = String.format(idFormat, namespace, zoneModelName, version);
    String zoneFileName = zoneModelName.concat(".type");
    String lampModelName = "Lamp";
    String lampModelID = String.format(idFormat, namespace, lampModelName, version);
    String lampFileName = lampModelName.concat(".fbmodel");
    String addressModelName = "Address";
    String addressModelID = String.format(idFormat, namespace, addressModelName, version);
    String addressFileName = addressModelName.concat(".fbmodel");
    String streetLampModelName = "StreetLamp";
    String streetLampModelID = String.format(idFormat, namespace, streetLampModelName, version);
    String streetLampFileName = streetLampModelName.concat(".infomodel");
    String streetLampAttachmentFileName = "StreetLampAttachment.json";
    String streetLampLinkURL = "https://vorto.eclipse.org/";
    String streetLampLinkName = "Vorto";
    // creates the namespace as sysadmin
    createNamespaceSuccessfully(namespace, userSysadmin);
    // creates the collaborator payload to add userModelCreator to the namespace
    Collaborator userModelCreatorCollaborator = new Collaborator();
    userModelCreatorCollaborator.setAuthenticationProviderId(GITHUB);
    userModelCreatorCollaborator.setRoles(Arrays.asList("model_viewer", "model_creator"));
    userModelCreatorCollaborator.setTechnicalUser(false);
    userModelCreatorCollaborator.setUserId(USER_MODEL_CREATOR_NAME);
    // allows creator rights to userCreator on namespace
    repositoryServer.perform(put(String.format("/rest/namespaces/%s/users", namespace)).with(userSysadmin).contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(userModelCreatorCollaborator))).andExpect(status().isOk());
    // creates the Zone model
    createModel(userModelCreator, zoneFileName, zoneModelID);
    // creates the Lamp model
    createModel(userModelCreator, lampFileName, lampModelID);
    // creates the Address model
    createModel(userModelCreator, addressFileName, addressModelID);
    // creates the StreetLamp model
    createModel(userModelCreator, streetLampFileName, streetLampModelID);
    // adds an attachment to the StreetLamp model (still requires sysadmin for this)
    addAttachment(streetLampModelID, userSysadmin, streetLampAttachmentFileName, MediaType.APPLICATION_JSON).andExpect(status().isOk()).andExpect(content().json(objectMapper.writeValueAsString(AttachResult.success(ModelId.fromPrettyFormat(streetLampModelID), streetLampAttachmentFileName))));
    // adds a link to the StreetLamp model
    ModelLink link = new ModelLink(streetLampLinkURL, streetLampLinkName);
    addLink(streetLampModelID, userModelCreator, link);
    // saves a minimal mapping specification for the street lamp model
    Infomodel streetLampInfomodel = new Infomodel(ModelId.fromPrettyFormat(streetLampModelID));
    streetLampInfomodel.setTargetPlatformKey("myTargetPlatform");
    MappingSpecification mapping = new MappingSpecification(streetLampInfomodel);
    repositoryServer.perform(put(String.format("/rest/mappings/specifications/%s", streetLampModelID)).contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(mapping)).with(userModelCreator)).andExpect(status().isOk());
    // expected ID of the payload mapping model
    String mappingId = String.format("%s.%s:%sPayloadMapping:%s", // root namespace
    namespace, // virtual namespace for mapping
    streetLampModelName.toLowerCase(), // mapping name part 1 matching root model
    streetLampModelName, // root model version
    version);
    // fetches the full model for the UI
    repositoryServer.perform(get(String.format("/rest/models/ui/%s", streetLampModelID)).with(userModelCreator)).andExpect(status().isOk()).andDo(mvcResult -> {
        ModelFullDetailsDTO output = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ModelFullDetailsDTO.class);
        LOGGER.info(new StringBuilder("\nReceived response body:\n\n").append(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(output)).toString());
    }).andExpect(jsonPath("$.modelInfo").exists()).andExpect(jsonPath("$.modelInfo.id.name").value(streetLampModelName)).andExpect(jsonPath("$.modelInfo.id.namespace").value(namespace)).andExpect(jsonPath("$.modelInfo.type").value("InformationModel")).andExpect(jsonPath("$.modelInfo.author").value(USER_MODEL_CREATOR_NAME)).andExpect(jsonPath("$.mappings").isNotEmpty()).andExpect(jsonPath("$.mappings[0].id").value(mappingId)).andExpect(jsonPath("$.references", hasSize(2))).andExpect(jsonPath("$.referencedBy", hasSize(1))).andExpect(jsonPath("$.referencedBy[0].id").value(mappingId)).andExpect(jsonPath("$.attachments").exists()).andExpect(jsonPath("$.attachments[0].filename").value(streetLampAttachmentFileName)).andExpect(jsonPath("$.attachments[0].modelId.name").value(streetLampModelName)).andExpect(jsonPath("$.links").exists()).andExpect(jsonPath("$.links[0].url").value(equalTo(link.getUrl()))).andExpect(jsonPath("$.links[0].displayText").value(equalTo(link.getDisplayText()))).andExpect(jsonPath("$.actions").exists()).andExpect(jsonPath("$.actions").isEmpty()).andExpect(jsonPath("$.policies", hasSize(2))).andExpect(jsonPath("$.bestPolicy").exists()).andExpect(jsonPath("$.bestPolicy.principalId").value("model_creator")).andExpect(jsonPath("$.bestPolicy.permission").value(Permission.FULL_ACCESS.toString())).andExpect(jsonPath("$.encodedModelSyntax").value(Base64.getEncoder().encodeToString(createContentAsString(streetLampFileName).getBytes())));
    // cleanup: deletes models in reverse order of creation, then namespace
    repositoryServer.perform(delete(String.format("/rest/models/%s", mappingId)).with(userModelCreator)).andExpect(status().isOk());
    repositoryServer.perform(delete(String.format("/rest/models/%s", streetLampModelID)).with(userModelCreator)).andExpect(status().isOk());
    repositoryServer.perform(delete(String.format("/rest/models/%s", lampModelID)).with(userModelCreator)).andExpect(status().isOk());
    repositoryServer.perform(delete(String.format("/rest/models/%s", addressModelID)).with(userModelCreator)).andExpect(status().isOk());
    repositoryServer.perform(delete(String.format("/rest/models/%s", zoneModelID)).with(userModelCreator)).andExpect(status().isOk());
    repositoryServer.perform(delete(String.format("/rest/namespaces/%s", namespace)).with(userSysadmin)).andExpect(status().isNoContent());
    // removes test-specific configuration
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
}
Also used : Arrays(java.util.Arrays) MockMvcResultMatchers.jsonPath(org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath) MappingSpecification(org.eclipse.vorto.mapping.engine.model.spec.MappingSpecification) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) ModelFullDetailsDTO(org.eclipse.vorto.repository.web.api.v1.dto.ModelFullDetailsDTO) Autowired(org.springframework.beans.factory.annotation.Autowired) Infomodel(org.eclipse.vorto.model.Infomodel) MockMvcResultMatchers.content(org.springframework.test.web.servlet.result.MockMvcResultMatchers.content) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) ModelLink(org.eclipse.vorto.repository.web.api.v1.dto.ModelLink) MockMvcRequestBuilders.delete(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete) Logger(org.apache.log4j.Logger) MockMvcResultMatchers.status(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status) MockMvcRequestBuilders.post(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post) Matchers.hasSize(org.hamcrest.Matchers.hasSize) Collaborator(org.eclipse.vorto.repository.web.api.v1.dto.Collaborator) MockMvcRequestBuilders.put(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put) MediaType(org.springframework.http.MediaType) Test(org.junit.Test) ModelId(org.eclipse.vorto.model.ModelId) Sets(com.google.common.collect.Sets) ModelType(org.eclipse.vorto.model.ModelType) Base64(java.util.Base64) AttachmentValidator(org.eclipse.vorto.repository.core.impl.validation.AttachmentValidator) MockMvcRequestBuilders.get(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get) Permission(org.eclipse.vorto.repository.core.PolicyEntry.Permission) AttachResult(org.eclipse.vorto.repository.web.api.v1.dto.AttachResult) ModelFullDetailsDTO(org.eclipse.vorto.repository.web.api.v1.dto.ModelFullDetailsDTO) Collaborator(org.eclipse.vorto.repository.web.api.v1.dto.Collaborator) MappingSpecification(org.eclipse.vorto.mapping.engine.model.spec.MappingSpecification) ModelLink(org.eclipse.vorto.repository.web.api.v1.dto.ModelLink) Infomodel(org.eclipse.vorto.model.Infomodel) Test(org.junit.Test)

Example 4 with Collaborator

use of org.eclipse.vorto.repository.web.api.v1.dto.Collaborator in project vorto by eclipse.

the class NamespaceControllerIntegrationTest method createTechnicalCollaboratorUnknownProvider.

@Test
public void createTechnicalCollaboratorUnknownProvider() throws Exception {
    // creates the collaborator payload and the existing user
    String otherUser = "userstandard2";
    Collaborator collaborator = new Collaborator(otherUser, "unknownProvider", null, Lists.newArrayList("model_viewer", "model_creator"));
    collaborator.setTechnicalUser(true);
    repositoryServer.perform(post("/rest/namespaces/com.mycompany/users").content(objectMapper.writeValueAsString(collaborator)).contentType(MediaType.APPLICATION_JSON).with(userSysadmin)).andExpect(status().isBadRequest());
}
Also used : Collaborator(org.eclipse.vorto.repository.web.api.v1.dto.Collaborator) Test(org.junit.Test)

Example 5 with Collaborator

use of org.eclipse.vorto.repository.web.api.v1.dto.Collaborator in project vorto by eclipse.

the class NamespaceControllerIntegrationTest method updateCollaboratorUserDoesNotExist.

@Test
public void updateCollaboratorUserDoesNotExist() throws Exception {
    String namespaceName = "com.mycompany";
    Collaborator collaborator = new Collaborator("unknownUser", GITHUB, null, Lists.newArrayList("model_viewer", "model_creator"));
    repositoryServer.perform(put(String.format("/rest/namespaces/%s/users", namespaceName)).content(objectMapper.writeValueAsString(collaborator)).contentType(MediaType.APPLICATION_JSON).with(userSysadmin)).andExpect(status().isNotFound()).andExpect(content().string("false"));
}
Also used : Collaborator(org.eclipse.vorto.repository.web.api.v1.dto.Collaborator) Test(org.junit.Test)

Aggregations

Collaborator (org.eclipse.vorto.repository.web.api.v1.dto.Collaborator)28 Test (org.junit.Test)24 HashSet (java.util.HashSet)10 UserBuilder (org.eclipse.vorto.repository.services.UserBuilder)5 Sets (com.google.common.collect.Sets)2 ModelId (org.eclipse.vorto.model.ModelId)2 ModelType (org.eclipse.vorto.model.ModelType)2 ModelLink (org.eclipse.vorto.repository.web.api.v1.dto.ModelLink)2 Autowired (org.springframework.beans.factory.annotation.Autowired)2 MediaType (org.springframework.http.MediaType)2 SecurityMockMvcRequestPostProcessors (org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors)2 MockMvcResultMatchers.content (org.springframework.test.web.servlet.result.MockMvcResultMatchers.content)2 MockMvcResultMatchers.status (org.springframework.test.web.servlet.result.MockMvcResultMatchers.status)2 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 DeserializationFeature (com.fasterxml.jackson.databind.DeserializationFeature)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Gson (com.google.gson.Gson)1 GsonBuilder (com.google.gson.GsonBuilder)1 java.util (java.util)1 ArrayList (java.util.ArrayList)1