Skip to content

Commit

Permalink
Change document and link id in request (#815)
Browse files Browse the repository at this point in the history
* refactor: document id as object instead of String

* refactor: documentId for delete document

* refactor: improve display error message when document Id does not exist

* Update DocumentsResources.java

* refactor:delete document and delete link

object instead of String

* refactor: PUT /link/id

object instead of String

* refactor:add sanitize

* test: add new tests for documents services

* tests: clean codeLists tests

* fix:

* refactor: place of constant

* refactor
  • Loading branch information
GtanSndil authored Dec 4, 2024
1 parent cd01bd4 commit 2fa65b8
Show file tree
Hide file tree
Showing 7 changed files with 332 additions and 24 deletions.
3 changes: 3 additions & 0 deletions src/main/java/fr/insee/rmes/bauhaus_services/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

public class Constants {


/*A*/
public static final String ACCRUAL_PERIODICITY_LIST ="accrualPeriodicityList";
public static final String ALT_LABEL_LG1 = "altLabelLg1";
Expand Down Expand Up @@ -108,8 +109,10 @@ public class Constants {
public static final String TEXT_LG1 = "texte";
public static final String TEXT_LG2 = "text";
public static final String TYPE_OF_OBJECT = "typeOfObject";
public static final String TYPE_STRING = "String";
public static final String TYPELIST = "typeList";


/*U*/
public static final String UNDEFINED = "undefined";
public static final String UPDATED_DATE = "updatedDate";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ public JSONObject getDocument(String id, boolean isLink) throws RmesException {

if (jsonDocs.isNull(Constants.URI)) {
logger.error("Error with the document {}. It looks like it does not have an uri", id);
throw new RmesNotFoundException(ErrorCodes.DOCUMENT_UNKNOWN_ID, "Cannot find " + (isLink ? "Link" : "Document") + " with id: ", id);
throw new RmesNotFoundException(ErrorCodes.DOCUMENT_UNKNOWN_ID, "Cannot find " + (isLink ? "Link" : "Document") + " with id : " + id, id);
}
formatDateInJsonObject(jsonDocs);
jsonDocs.put("sims", this.getSimsByDocument(id, isLink));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package fr.insee.rmes.config.swagger.model.operations.documentation;

public class DocumentId {
private String id;

public DocumentId(String id) {
this.id = id;
}

public String getDocumentId() {
return id;
}

public String getString() {
if (id != null && !id.isEmpty()) {
return id;
}
else{
return null; //without this it might cause some trouble to test with new DocumentID(null)
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public String getDistributions() throws RmesException {
}

@GetMapping("/{id}")
@Operation(operationId = "getDistribution", summary = "Get a distributions",
@Operation(operationId = "getDistribution", summary = "Get a distribution",
responses = {@ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Distribution.class))))})
public Distribution getDistribution(@PathVariable(Constants.ID) String id) throws RmesException {
return this.distributionService.getDistributionByID(id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import fr.insee.rmes.bauhaus_services.Constants;
import fr.insee.rmes.bauhaus_services.DocumentsService;
import fr.insee.rmes.config.swagger.model.operations.documentation.DocumentId;
import fr.insee.rmes.exceptions.RmesException;
import fr.insee.rmes.model.operations.documentations.Document;
import io.swagger.v3.oas.annotations.Operation;
Expand Down Expand Up @@ -107,15 +108,28 @@ public ResponseEntity<String> setDocument(
@PutMapping("/document/{id}")
@Operation(operationId = "setDocumentById", summary = "Update document ")
public ResponseEntity<String> setDocument(
@Parameter(description = "Id", required = true) @PathVariable(Constants.ID) String id,
@Parameter(description = Constants.DOCUMENT, required = true, schema = @Schema(implementation = Document.class)) @RequestBody String body) throws RmesException {
documentsService.setDocument(id, body);
@Parameter(
description = "Id",
required = true,
schema = @Schema (type=Constants.TYPE_STRING)
)
@PathVariable(Constants.ID) DocumentId id,
@Parameter(
description = Constants.DOCUMENT,
required = true,
schema = @Schema(implementation = Document.class)
)
@RequestBody String body) throws RmesException {
String documentIdString = (id.getDocumentId() != null) ? sanitizeDocumentId(id.getDocumentId()) : null;
documentsService.setDocument(documentIdString, body);
logger.info("Update document : {}", id);
return ResponseEntity.ok(id);
return ResponseEntity.ok(documentIdString);
}


@PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN "


@PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN "
+ ", T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR "
+ ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)")
@Operation(operationId = "changeDocument", summary = "Change document file")
Expand All @@ -140,8 +154,15 @@ public ResponseEntity<String> changeDocument(
+ ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)")
@DeleteMapping("/document/{id}")
@Operation(operationId = "deleteDocument", summary = "Delete a document")
public ResponseEntity<Object> deleteDocument(@PathVariable(Constants.ID) String id) throws RmesException {
return ResponseEntity.status(documentsService.deleteDocument(id)).body(id);
public ResponseEntity<Object> deleteDocument(
@Parameter(
required = true,
schema = @Schema (type=Constants.TYPE_STRING)
)
@PathVariable(Constants.ID) DocumentId id)
throws RmesException {
String documentIdString = (id.getDocumentId() != null) ? sanitizeDocumentId(id.getDocumentId()) : null;
return ResponseEntity.status(documentsService.deleteDocument(documentIdString)).body(documentIdString);
}


Expand Down Expand Up @@ -176,17 +197,48 @@ public ResponseEntity<Object> setLink(
@PutMapping("/link/{id}")
@Operation(operationId = "setLinkById", summary = "Update link")
public ResponseEntity<Object> setLink(
@Parameter(description = "Id", required = true) @PathVariable(Constants.ID) String id,
@Parameter(description = "Link", required = true, schema = @Schema(implementation = Document.class)) @RequestBody String body) throws RmesException {
return ResponseEntity.ok(documentsService.setLink(id, body));
@Parameter(
description = "Id",
required = true,
schema = @Schema (type=Constants.TYPE_STRING)
)
@PathVariable(Constants.ID) DocumentId id,
@Parameter(
required = true,
schema = @Schema(implementation = Document.class)
)
@RequestBody String body
)
throws RmesException {
String documentIdString = (id.getDocumentId() != null) ? sanitizeDocumentId(id.getDocumentId()) : null;
return ResponseEntity.ok(documentsService.setLink(documentIdString, body));
}

@PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN "
+ ", T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR "
+ ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)")
@DeleteMapping("/link/{id}")
@Operation(operationId = "deleteLink", summary = "Delete a link")
public ResponseEntity<Object> deleteLink(@PathVariable(Constants.ID) String id) throws RmesException {
return ResponseEntity.status(documentsService.deleteLink(id)).body(id);
public ResponseEntity<Object> deleteLink(
@Parameter(
required = true,
schema = @Schema (type=Constants.TYPE_STRING)
)
@PathVariable(Constants.ID) DocumentId id
) throws RmesException {
String documentIdString = (id.getDocumentId() != null) ? sanitizeDocumentId(id.getDocumentId()) : null;
return ResponseEntity.status(documentsService.deleteLink(documentIdString)).body(documentIdString);
}


// Méthode pour encoder et valider le DocumentID
private String sanitizeDocumentId(String documentIdString) {
if (documentIdString == null || documentIdString.isEmpty()) {
return null;
}
//on peut ajouter d'autres contrôles
return documentIdString.replaceAll("[/<>:\"]", "");
}


}
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package fr.insee.rmes.integration.authorizations;

import fr.insee.rmes.bauhaus_services.CodeListService;
import fr.insee.rmes.bauhaus_services.OperationsDocumentationsService;
import fr.insee.rmes.bauhaus_services.StampAuthorizationChecker;
import fr.insee.rmes.config.Config;
import fr.insee.rmes.config.auth.UserProviderFromSecurityContext;
import fr.insee.rmes.config.auth.roles.Roles;
import fr.insee.rmes.config.auth.security.*;
import fr.insee.rmes.config.auth.security.BauhausMethodSecurityExpressionHandler;
import fr.insee.rmes.config.auth.security.CommonSecurityConfiguration;
import fr.insee.rmes.config.auth.security.DefaultSecurityContext;
import fr.insee.rmes.config.auth.security.OpenIDConnectSecurityContext;
import fr.insee.rmes.config.auth.user.Stamp;
import fr.insee.rmes.model.ValidationStatus;
import fr.insee.rmes.webservice.codesLists.CodeListsResources;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
Expand All @@ -23,7 +24,6 @@
import java.util.List;

import static fr.insee.rmes.integration.authorizations.TokenForTestsConfiguration.*;
import static fr.insee.rmes.model.ValidationStatus.UNPUBLISHED;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
Expand Down Expand Up @@ -56,15 +56,12 @@ class TestCodeListsResourcesEnvProd {
@MockBean
private CodeListService codeListService;
@MockBean
protected OperationsDocumentationsService documentationsService;
@MockBean
StampAuthorizationChecker stampAuthorizationChecker;

private final String idep = "xxxxxx";
private final String timbre = "XX59-YYY";

int codesListId=10;
ValidationStatus status= UNPUBLISHED;

@Test
void putCodesListAdmin_ok() throws Exception {
Expand Down Expand Up @@ -143,7 +140,7 @@ void postCodesListAsCodesListContributor_ok() throws Exception {

@Test
void postCodesList_noAuth() throws Exception {
mvc.perform(put("/codeList/")
mvc.perform(post("/codeList/")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.content("{\"id\": \"1\"}"))
Expand Down Expand Up @@ -233,7 +230,7 @@ void postCode_noAuth() throws Exception {

@Test
void postCodeAsNotCodesListContributor() throws Exception {
configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("mauvais rôle"));
configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("bad_role"));
mvc.perform(post("/codeList/detailed/1/codes").header("Authorization", "Bearer toto")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
Expand Down Expand Up @@ -274,7 +271,7 @@ void putCode_noAuth() throws Exception {

@Test
void putCodeAsNotCodesListContributor() throws Exception {
configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("mauvais rôle"));
configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("bad_role"));
mvc.perform(put("/codeList/detailed/1/codes/2").header("Authorization", "Bearer toto")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
Expand Down
Loading

0 comments on commit 2fa65b8

Please sign in to comment.