diff --git a/pom.xml b/pom.xml index 959dce25..58cdc366 100644 --- a/pom.xml +++ b/pom.xml @@ -186,6 +186,11 @@ spring-cloud-stream-test-binder test + + org.springframework.security + spring-security-test + test + org.springframework spring-web diff --git a/src/main/java/org/gridsuite/explore/server/UserAuthentication.java b/src/main/java/org/gridsuite/explore/server/UserAuthentication.java new file mode 100644 index 00000000..26317a7d --- /dev/null +++ b/src/main/java/org/gridsuite/explore/server/UserAuthentication.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2026, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +package org.gridsuite.explore.server; + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.authority.SimpleGrantedAuthority; + +import java.util.*; +import java.util.stream.Collectors; + +public class UserAuthentication implements Authentication { + + private final String principal; + + private final Collection authorities; + + private boolean authenticated = false; + + public UserAuthentication(String principal, Collection authorities) { + this.principal = principal; + this.authorities = authorities == null + ? AuthorityUtils.NO_AUTHORITIES + : Collections.unmodifiableList(new ArrayList<>(authorities)); + setAuthenticated(true); + } + + public UserAuthentication(String principal, String roles) { + List authorities = Collections.emptyList(); + if (roles != null && !roles.isEmpty()) { + authorities = Arrays.stream(roles.split("\\|")) + .map(String::trim) + .filter(role -> !role.isEmpty()) + .map(SimpleGrantedAuthority::new) + .map(GrantedAuthority.class::cast) + .toList(); + } + this(principal, authorities); + } + + // TODO: pour les roles, on recoit un String ou une liste d'authorities ? on renvoie un String on une liste d'authorities ? + + public String getUserId() { + return principal; + } + + public String getRoles() { + return authorities.stream() + .map(GrantedAuthority::getAuthority) + .collect(Collectors.joining("|")); + } + + // methods needed by interface + + @Override + public String getName() { + return principal; + } + + @Override + public String getPrincipal() { + return this.principal; + } + + @Override + public Collection getAuthorities() { + return this.authorities; + } + + @Override + public boolean isAuthenticated() { + return this.authenticated; + } + + @Override + public void setAuthenticated(boolean authenticated) { + this.authenticated = authenticated; + } + + @Override + public Object getCredentials() { + return null; + } + + @Override + public Object getDetails() { + return null; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(getClass().getSimpleName()).append(" ["); + sb.append("Principal=").append(getPrincipal()).append(", "); + sb.append("Authenticated=").append(isAuthenticated()).append(", "); + sb.append("Granted Authorities=").append(this.authorities); + sb.append("]"); + return sb.toString(); + } +} diff --git a/src/main/java/org/gridsuite/explore/server/RestTemplateConfig.java b/src/main/java/org/gridsuite/explore/server/config/RestTemplateConfig.java similarity index 76% rename from src/main/java/org/gridsuite/explore/server/RestTemplateConfig.java rename to src/main/java/org/gridsuite/explore/server/config/RestTemplateConfig.java index aad5e2ec..931097c0 100644 --- a/src/main/java/org/gridsuite/explore/server/RestTemplateConfig.java +++ b/src/main/java/org/gridsuite/explore/server/config/RestTemplateConfig.java @@ -4,11 +4,11 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -package org.gridsuite.explore.server; +package org.gridsuite.explore.server.config; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; -import jakarta.servlet.http.HttpServletRequest; +import org.gridsuite.explore.server.UserAuthentication; import org.springframework.boot.jackson.JsonComponentModule; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; @@ -20,9 +20,8 @@ import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.client.RestTemplate; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; import java.io.IOException; import java.util.Collections; @@ -43,39 +42,38 @@ public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { if (httpMessageConverter instanceof MappingJackson2HttpMessageConverter) { restTemplate.getMessageConverters().set(i, mappingJackson2HttpMessageConverter()); } - - restTemplate.setInterceptors( - Collections.singletonList(new RoleHeaderForwardingInterceptor()) - ); } + restTemplate.setInterceptors( + Collections.singletonList(new HeaderForwardingInterceptor()) + ); + return restTemplate; } /** - * In our microservice architecture, user permissions (roles) must be preserved when - * one service calls another. This interceptor automatically forwards the "roles" header + * In our microservice architecture, user permissions (userId and roles) must be preserved when + * one service calls another. This interceptor automatically forwards the "userId" and "roles" headers * from incoming requests to any outgoing REST calls made with this RestTemplate. * * Without this interceptor, authorization information would be lost in service-to-service * communication. */ - public static class RoleHeaderForwardingInterceptor implements ClientHttpRequestInterceptor { + public static class HeaderForwardingInterceptor implements ClientHttpRequestInterceptor { private static final String ROLES_HEADER = "roles"; + private static final String USER_ID_HEADER = "userId"; @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { - ServletRequestAttributes attributes = - (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + UserAuthentication authentication = (UserAuthentication) SecurityContextHolder.getContext().getAuthentication(); - // If we have a current request, copy its roles header to the outgoing request - if (attributes != null) { - HttpServletRequest currentRequest = attributes.getRequest(); - String roles = currentRequest.getHeader(ROLES_HEADER); + if (authentication != null) { + request.getHeaders().set(USER_ID_HEADER, authentication.getUserId()); - if (roles != null && !roles.isEmpty()) { + String roles = authentication.getRoles(); + if (!roles.isEmpty()) { request.getHeaders().set(ROLES_HEADER, roles); } } diff --git a/src/main/java/org/gridsuite/explore/server/config/SecurityFilter.java b/src/main/java/org/gridsuite/explore/server/config/SecurityFilter.java new file mode 100644 index 00000000..f9fddd57 --- /dev/null +++ b/src/main/java/org/gridsuite/explore/server/config/SecurityFilter.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2026, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +package org.gridsuite.explore.server.config; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.gridsuite.explore.server.UserAuthentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +/** + * @author Caroline Jeandat + */ +public class SecurityFilter extends OncePerRequestFilter { + + private static final String HEADER_ROLES = "roles"; + private static final String HEADER_USER_ID = "userId"; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + + String userId = request.getHeader(HEADER_USER_ID); + String rolesHeader = request.getHeader(HEADER_ROLES); + + if (userId != null && !userId.isEmpty()) { + SecurityContextHolder.getContext().setAuthentication(new UserAuthentication(userId, rolesHeader)); + /* + Set roles = Collections.emptySet(); + if (rolesHeader != null && !rolesHeader.isEmpty()) { + roles = Arrays.stream(rolesHeader.split("\\|")) + .map(String::trim) + .filter(role -> !role.isEmpty()) + .collect(Collectors.toSet()); + } + userContext.setUserId(userId); + userContext.setRoles(roles); + */ + } + + filterChain.doFilter(request, response); + } +} diff --git a/src/main/java/org/gridsuite/explore/server/config/SpringSecurityConfig.java b/src/main/java/org/gridsuite/explore/server/config/SpringSecurityConfig.java new file mode 100644 index 00000000..dae85e37 --- /dev/null +++ b/src/main/java/org/gridsuite/explore/server/config/SpringSecurityConfig.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2026, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +package org.gridsuite.explore.server.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.context.SecurityContextHolderFilter; + +/** + * @author Caroline Jeandat + */ +@Configuration +@EnableWebSecurity +public class SpringSecurityConfig { + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http + .csrf(AbstractHttpConfigurer::disable) + .authorizeHttpRequests(authorize -> authorize + .anyRequest().permitAll() + ) + .addFilterAfter(new SecurityFilter(), SecurityContextHolderFilter.class); + + return http.build(); + } +} diff --git a/src/main/java/org/gridsuite/explore/server/controller/ActionsController.java b/src/main/java/org/gridsuite/explore/server/controller/ActionsController.java index e2b56907..21608f0d 100644 --- a/src/main/java/org/gridsuite/explore/server/controller/ActionsController.java +++ b/src/main/java/org/gridsuite/explore/server/controller/ActionsController.java @@ -14,6 +14,7 @@ import org.gridsuite.explore.server.services.ContingencyListService; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @@ -32,18 +33,22 @@ public ActionsController(ContingencyListService contingencyListService) { this.contingencyListService = contingencyListService; } + // TODO: on récupère l'élément depuis actions-server, donc vérifier qu'il existe bien dans directory-server @GetMapping(value = "/identifier-contingency-lists/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Get identifier contingency list by id from actions-server") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "The identifier contingency list"), @ApiResponse(responseCode = "404", description = "The identifier contingency list does not exists")}) + @PreAuthorize("@authorizationService.canRead(#id)") public ResponseEntity getIdentifierContingencyList(@PathVariable("id") UUID id) { return ResponseEntity.ok(contingencyListService.getIdentifierContingencyList(id)); } + // TODO: on récupère l'élément depuis actions-server, donc vérifier qu'il existe bien dans directory-server @GetMapping(value = "/filters-contingency-lists/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Get filter based contingency list by id from actions-server") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "The filter based contingency list"), @ApiResponse(responseCode = "404", description = "The filter based contingency list does not exists")}) + @PreAuthorize("@authorizationService.canRead(#id)") public ResponseEntity getFilterBasedContingencyList(@PathVariable("id") UUID id) { return ResponseEntity.ok(contingencyListService.getFilterBasedContingencyList(id)); } diff --git a/src/main/java/org/gridsuite/explore/server/controller/CaseController.java b/src/main/java/org/gridsuite/explore/server/controller/CaseController.java index 57325eeb..0bfaee0f 100644 --- a/src/main/java/org/gridsuite/explore/server/controller/CaseController.java +++ b/src/main/java/org/gridsuite/explore/server/controller/CaseController.java @@ -35,23 +35,27 @@ public CaseController(CaseService caseService) { this.caseService = caseService; } + // TODO: rien à checker @PostMapping(value = "/cases", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity importCase(@RequestPart("file") MultipartFile file, @RequestParam(value = "withExpiration", required = false, defaultValue = "false") boolean withExpiration) { return ResponseEntity.ok(caseService.importCaseWithoutDirectoryElementCreation(file, withExpiration)); } + // TODO: appel à case-server et pas à directory-server -> rien à checker ?? vérifier l'utilité de cet endpoint @DeleteMapping(value = "/cases/{caseUuid}") public ResponseEntity deleteCase(@PathVariable("caseUuid") UUID caseUuid) { caseService.deleteCase(caseUuid); return ResponseEntity.ok().build(); } + // TODO: appel à case-server et pas à directory-server -> rien à checker ?? vérifier l'utilité de cet endpoint @GetMapping(value = "/cases/{caseUuid}") public ResponseEntity downloadCase(@PathVariable("caseUuid") UUID caseUuid) { return caseService.downloadCase(caseUuid); } + // TODO: rien à checker @GetMapping(value = "/cases/caseBaseName") public ResponseEntity getBaseName(@RequestParam("caseName") String caseName) { return ResponseEntity.ok(caseService.getBaseName(caseName)); diff --git a/src/main/java/org/gridsuite/explore/server/controller/ExploreController.java b/src/main/java/org/gridsuite/explore/server/controller/ExploreController.java index 3c4d47e6..2987ce6b 100644 --- a/src/main/java/org/gridsuite/explore/server/controller/ExploreController.java +++ b/src/main/java/org/gridsuite/explore/server/controller/ExploreController.java @@ -46,7 +46,6 @@ public class ExploreController { private static final String QUERY_PARAM_PARENT_DIRECTORY_ID = "parentDirectoryUuid"; private static final String QUERY_PARAM_TYPE = "type"; - private static final String QUERY_PARAM_USER_ID = "userId"; private final ExploreService exploreService; private final DirectoryService directoryService; @@ -56,141 +55,134 @@ public ExploreController(ExploreService exploreService, DirectoryService directo this.directoryService = directoryService; } + // TODO @PostMapping(value = "/explore/studies/{studyName}/cases/{caseUuid}") @Operation(summary = "create a study from an existing case") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Study creation request delegated to study server")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #parentDirectoryUuid, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#parentDirectoryUuid)") public ResponseEntity createStudy(@PathVariable("studyName") String studyName, @PathVariable("caseUuid") UUID caseUuid, @RequestParam(name = "caseFormat") String caseFormat, @RequestParam(name = "duplicateCase", required = false, defaultValue = "false") Boolean duplicateCase, @RequestParam("description") String description, @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId, @RequestBody(required = false) Map importParams) { - exploreService.assertCanCreateCase(userId); + exploreService.assertCanCreateCase(); CaseInfo caseInfo = new CaseInfo(caseUuid, caseFormat); - exploreService.createStudy(studyName, caseInfo, description, userId, parentDirectoryUuid, importParams, duplicateCase); + exploreService.createStudy(studyName, caseInfo, description, parentDirectoryUuid, importParams, duplicateCase); return ResponseEntity.ok().build(); } @PostMapping(value = "/explore/studies/{id}/duplicate") @Operation(summary = "Duplicate a study") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Study creation request delegated to study server")}) - @PreAuthorize("@authorizationService.isAuthorizedForDuplication(#userId, #studyId, #targetDirectoryId)") + @PreAuthorize("@authorizationService.canDuplicateTo(#studyId, #targetDirectoryId)") public ResponseEntity duplicateStudy(@PathVariable("id") UUID studyId, - @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.assertCanCreateCase(userId); - exploreService.duplicateStudy(studyId, targetDirectoryId, userId); + @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId) { + exploreService.assertCanCreateCase(); + exploreService.duplicateStudy(studyId, targetDirectoryId); return ResponseEntity.ok().build(); } @PostMapping(value = "/explore/cases/{caseName}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @Operation(summary = "create a case") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Case creation request delegated to case server")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #parentDirectoryUuid, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#parentDirectoryUuid)") public ResponseEntity createCase(@PathVariable("caseName") String caseName, @RequestPart("caseFile") MultipartFile caseFile, @RequestParam("description") String description, - @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.assertCanCreateCase(userId); - exploreService.createCase(caseName, caseFile, description, userId, parentDirectoryUuid); + @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid) { + exploreService.assertCanCreateCase(); + exploreService.createCase(caseName, caseFile, description, parentDirectoryUuid); return ResponseEntity.ok().build(); } @PostMapping(value = "/explore/cases/{caseName}/persist", params = {"caseUuid", "description", QUERY_PARAM_PARENT_DIRECTORY_ID}) @Operation(summary = "persist an existing case") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Case persist request delegated to case server")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #parentDirectoryUuid, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#parentDirectoryUuid)") public ResponseEntity persistCase(@PathVariable("caseName") String caseName, @RequestParam("caseUuid") UUID caseUuid, @RequestParam("description") String description, - @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.assertCanCreateCase(userId); - exploreService.persistCase(caseName, caseUuid, description, userId, parentDirectoryUuid); + @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid) { + exploreService.assertCanCreateCase(); + exploreService.persistCase(caseName, caseUuid, description, parentDirectoryUuid); return ResponseEntity.ok().build(); } @PostMapping(value = "/explore/cases/{id}/duplicate") @Operation(summary = "Duplicate a case") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Case duplication request delegated to case server")}) - @PreAuthorize("@authorizationService.isAuthorizedForDuplication(#userId, #caseId, #targetDirectoryId)") + @PreAuthorize("@authorizationService.canDuplicateTo(#caseId, #targetDirectoryId)") public ResponseEntity duplicateCase( @PathVariable("id") UUID caseId, - @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.assertCanCreateCase(userId); - exploreService.duplicateCase(caseId, targetDirectoryId, userId); + @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId) { + exploreService.assertCanCreateCase(); + exploreService.duplicateCase(caseId, targetDirectoryId); return ResponseEntity.ok().build(); } @PostMapping(value = "/explore/contingency-lists/{id}/duplicate") @Operation(summary = "Duplicate a contingency list") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Contingency list has been created")}) - @PreAuthorize("@authorizationService.isAuthorizedForDuplication(#userId, #contingencyListUuid, #targetDirectoryId)") + @PreAuthorize("@authorizationService.canDuplicateTo(#contingencyListUuid, #targetDirectoryId)") public ResponseEntity duplicateContingencyList( @PathVariable("id") UUID contingencyListUuid, @RequestParam(name = QUERY_PARAM_TYPE) ContingencyListType contingencyListType, - @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.duplicateContingencyList(contingencyListUuid, targetDirectoryId, userId, contingencyListType); + @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId) { + exploreService.duplicateContingencyList(contingencyListUuid, targetDirectoryId, contingencyListType); return ResponseEntity.ok().build(); } @PostMapping(value = "/explore/identifier-contingency-lists/{listName}") @Operation(summary = "create an identifier contingency list") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Identifier contingency list has been created")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #parentDirectoryUuid, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#parentDirectoryUuid)") public ResponseEntity createIdentifierContingencyList(@PathVariable("listName") String listName, @RequestBody(required = false) String content, @RequestParam("description") String description, - @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.createIdentifierContingencyList(listName, content, description, userId, parentDirectoryUuid); + @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid) { + exploreService.createIdentifierContingencyList(listName, content, description, parentDirectoryUuid); return ResponseEntity.ok().build(); } @PostMapping(value = "/explore/filters-contingency-lists/{listName}") @Operation(summary = "create a filter based contingency list") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Filter based contingency list has been created")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #parentDirectoryUuid, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#parentDirectoryUuid)") public ResponseEntity createFilterBasedContingencyList(@PathVariable("listName") String listName, @RequestBody(required = false) String content, @RequestParam("description") String description, - @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.createFilterBasedContingencyList(listName, content, description, userId, parentDirectoryUuid); + @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid) { + exploreService.createFilterBasedContingencyList(listName, content, description, parentDirectoryUuid); return ResponseEntity.ok().build(); } @PostMapping(value = "/explore/filters", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "create a filter") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Filter creation request delegated to filter server")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #parentDirectoryUuid, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#parentDirectoryUuid)") public ResponseEntity createFilter(@RequestBody String filter, @RequestParam("name") String filterName, @RequestParam("description") String description, - @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.createFilter(filter, filterName, description, parentDirectoryUuid, userId); + @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid) { + exploreService.createFilter(filter, filterName, description, parentDirectoryUuid); return ResponseEntity.ok().build(); } @PostMapping(value = "/explore/filters/{id}/duplicate") @Operation(summary = "Duplicate a filter") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "The script has been created successfully")}) - @PreAuthorize("@authorizationService.isAuthorizedForDuplication(#userId, #filterId, #targetDirectoryId)") + @PreAuthorize("@authorizationService.canDuplicateTo(#filterId, #targetDirectoryId)") public ResponseEntity duplicateFilter( @PathVariable("id") UUID filterId, - @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.duplicateFilter(filterId, targetDirectoryId, userId); + @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId) { + exploreService.duplicateFilter(filterId, targetDirectoryId); return ResponseEntity.ok().build(); } + // TODO: les deux endpoints suivants sont redondants ??? p-e moyen de refacto ? + @DeleteMapping(value = "/explore/elements/{elementUuid}") @Operation(summary = "Remove directory/element") @ApiResponses(value = { @@ -198,38 +190,41 @@ public ResponseEntity duplicateFilter( @ApiResponse(responseCode = "404", description = "Directory/element was not found"), @ApiResponse(responseCode = "403", description = "Access forbidden for the directory/element") }) - @PreAuthorize("@authorizationService.isRecursivelyAuthorized(#userId, #elementUuid, null)") - public ResponseEntity deleteElement(@PathVariable("elementUuid") UUID elementUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.deleteElement(elementUuid, userId); + @PreAuthorize("@authorizationService.canDelete(#elementUuid)") + public ResponseEntity deleteElement(@PathVariable("elementUuid") UUID elementUuid) { + exploreService.deleteElement(elementUuid); return ResponseEntity.ok().build(); } @DeleteMapping(value = "/explore/elements/{directoryUuid}", params = "ids") + // dans les ids, ça ne peut pas contenir de subDirectories, car ils n'apparaissent que dans l'arbre @Operation(summary = "Remove directories/elements") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "directories/elements was successfully removed"), @ApiResponse(responseCode = "404", description = "At least one directory/element was not found"), @ApiResponse(responseCode = "403", description = "Access forbidden for at least one directory/element") }) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #directoryUuid, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") - public ResponseEntity deleteElements(@RequestParam("ids") List elementsUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId, + @PreAuthorize("@authorizationService.canDelete(#elementsUuids)") // ça ne peut pas contenir de subDirectories, car ils n'apparaissent que dans l'arbre + public ResponseEntity deleteElements(@RequestParam("ids") List elementsUuids, @PathVariable UUID directoryUuid) { - exploreService.deleteElementsFromDirectory(elementsUuid, directoryUuid, userId); + exploreService.deleteElementsFromDirectory(elementsUuids, directoryUuid); return ResponseEntity.ok().build(); } + // TODO : l'endpoint getElements dans directory-server filtre les éléments sur lesquels on n'a pas les droits si strictMode = false, et renvoie une erreur si strictMode = true + // ici on a strictMode = true (peut être que c'est à revoir ?) -> @PreFilter à tester ? @GetMapping(value = "/explore/elements/metadata", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "get element infos from ids given as parameters") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "The elements information")}) + @PreAuthorize("@authorizationService.canRead(#ids)") // TODO: strictMode => @PreAuthorize, non strictMode => @PreFilter public ResponseEntity> getElementsMetadata(@RequestParam("ids") List ids, @RequestParam(value = "equipmentTypes", required = false) List equipmentTypes, - @RequestParam(value = "elementTypes", required = false) List elementTypes, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(directoryService.getElementsMetadata(ids, elementTypes, equipmentTypes, userId)); + @RequestParam(value = "elementTypes", required = false) List elementTypes) { + return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(directoryService.getElementsMetadata(ids, elementTypes, equipmentTypes)); } + // TODO: ici je pense qu'on n'a pas besoin de permission ? ou alors READ ? + // actuellement on ne regarde pas si on a les droits (même dans l'endpoint de directory-server), on renvoie tout. On peut faire un @PreFilter ? @GetMapping(value = "/explore/elements/name", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "get element names from ids given as parameters") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "The elements names")}) @@ -237,6 +232,7 @@ public ResponseEntity> getElementsName(@RequestParam("ids") Li return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(directoryService.getElementsName(ids)); } + // TODO: est ce que cet élément existe dans directory-server ??? car on l'appelle depuis network-modification-server @GetMapping(value = "/explore/composite-modification/{id}/network-modifications", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "get the basic information of the network modifications contained in a composite modification") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Basic infos from all the contained network modifications")}) @@ -249,290 +245,273 @@ public ResponseEntity> getCompositeModificationContent(@PathVariabl @PutMapping(value = "/explore/filters/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Modify a filter") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "The filter has been successfully modified")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #id, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") - public ResponseEntity changeFilter(@PathVariable UUID id, @RequestBody String filter, @RequestHeader(QUERY_PARAM_USER_ID) String userId, - @RequestParam("name") String name, @RequestParam("description") String description) { - exploreService.updateFilter(id, filter, userId, name, description); + @PreAuthorize("@authorizationService.canWrite(#id)") + public ResponseEntity changeFilter(@PathVariable UUID id, + @RequestBody String filter, + @RequestParam("name") String name, + @RequestParam("description") String description) { + exploreService.updateFilter(id, filter, name, description); return ResponseEntity.ok().build(); } @PutMapping(value = "/explore/contingency-lists/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Modify a contingency list") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "The contingency list have been modified successfully")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #id, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#id)") public ResponseEntity updateContingencyList( @PathVariable UUID id, @RequestParam(name = "name") String name, @RequestParam(name = QUERY_PARAM_DESCRIPTION) String description, @RequestParam(name = "contingencyListType") ContingencyListType contingencyListType, - @RequestBody String content, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - - exploreService.updateContingencyList(id, content, userId, name, description, contingencyListType); + @RequestBody String content) { + exploreService.updateContingencyList(id, content, name, description, contingencyListType); return ResponseEntity.ok().build(); } @PostMapping(value = "/explore/parameters", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "create parameters") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "parameters creation request delegated to corresponding server")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #parentDirectoryUuid, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#parentDirectoryUuid)") public ResponseEntity createParameters(@RequestBody String parameters, @RequestParam("name") String parametersName, @RequestParam(name = QUERY_PARAM_TYPE, defaultValue = "") ParametersType parametersType, @RequestParam(QUERY_PARAM_DESCRIPTION) String description, - @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.createParameters(parameters, parametersType, parametersName, description, parentDirectoryUuid, userId); + @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid) { + exploreService.createParameters(parameters, parametersType, parametersName, description, parentDirectoryUuid); return ResponseEntity.ok().build(); } @PostMapping(value = "/explore/diagram-config", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "create diagram config") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "diagram config creation request delegated to corresponding server")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #parentDirectoryUuid, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#parentDirectoryUuid)") public ResponseEntity createDiagramConfig(@RequestBody String diagramConfig, @RequestParam("name") String diagramConfigName, @RequestParam(QUERY_PARAM_DESCRIPTION) String description, - @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.createDiagramConfig(diagramConfig, diagramConfigName, description, parentDirectoryUuid, userId); + @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid) { + exploreService.createDiagramConfig(diagramConfig, diagramConfigName, description, parentDirectoryUuid); return ResponseEntity.ok().build(); } @PostMapping(value = "/explore/diagram-config/{id}/duplicate") @Operation(summary = "Duplicate a diagram config") @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "diagram config has been successfully duplicated")}) - @PreAuthorize("@authorizationService.isAuthorizedForDuplication(#userId, #sourceId, #targetDirectoryId)") + @PreAuthorize("@authorizationService.canDuplicateTo(#sourceId, #targetDirectoryId)") public ResponseEntity duplicateDiagramConfig(@PathVariable("id") UUID sourceId, - @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.duplicateDiagramConfig(sourceId, targetDirectoryId, userId); + @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId) { + exploreService.duplicateDiagramConfig(sourceId, targetDirectoryId); return ResponseEntity.ok().build(); } @PutMapping(value = "/explore/diagram-config/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Modify a diagram config") @ApiResponses(value = {@ApiResponse(responseCode = "204", description = "Diagram config has been successfully modified")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #id, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#id)") public ResponseEntity updateDiagramConfig(@PathVariable UUID id, @RequestBody String diagramConfig, - @RequestHeader(QUERY_PARAM_USER_ID) String userId, @RequestParam(QUERY_PARAM_NAME) String name, @RequestParam(QUERY_PARAM_DESCRIPTION) String description) { - exploreService.updateDiagramConfig(id, diagramConfig, userId, name, description); + exploreService.updateDiagramConfig(id, diagramConfig, name, description); return ResponseEntity.noContent().build(); } @PutMapping(value = "/explore/parameters/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Modify parameters") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "parameters have been successfully modified")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #id, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#id)") public ResponseEntity updateParameters(@PathVariable UUID id, @RequestBody String parameters, @RequestParam(name = QUERY_PARAM_TYPE, defaultValue = "") ParametersType parametersType, - @RequestHeader(QUERY_PARAM_USER_ID) String userId, @RequestParam(QUERY_PARAM_NAME) String name, @RequestParam(QUERY_PARAM_DESCRIPTION) String description) { - exploreService.updateParameters(id, parameters, parametersType, userId, name, description); + exploreService.updateParameters(id, parameters, parametersType, name, description); return ResponseEntity.ok().build(); } @PostMapping(value = "/explore/parameters/{id}/duplicate") @Operation(summary = "Duplicate parameters") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "parameters have been successfully duplicated")}) - @PreAuthorize("@authorizationService.isAuthorizedForDuplication(#userId, #parametersId, #targetDirectoryId)") + @PreAuthorize("@authorizationService.canDuplicateTo(#parametersId, #targetDirectoryId)") public ResponseEntity duplicateParameters(@PathVariable("id") UUID parametersId, @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId, - @RequestParam(name = QUERY_PARAM_TYPE) ParametersType parametersType, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.duplicateParameters(parametersId, targetDirectoryId, parametersType, userId); + @RequestParam(name = QUERY_PARAM_TYPE) ParametersType parametersType) { + exploreService.duplicateParameters(parametersId, targetDirectoryId, parametersType); return ResponseEntity.ok().build(); } @PostMapping(value = "/explore/spreadsheet-configs", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Create a spreadsheet configuration") @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Spreadsheet config created")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #parentDirectoryUuid, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#parentDirectoryUuid)") public ResponseEntity createSpreadsheetConfig(@RequestBody String spreadsheetConfigDto, @RequestParam("name") String configName, @RequestParam(QUERY_PARAM_DESCRIPTION) String description, - @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.createSpreadsheetConfig(spreadsheetConfigDto, configName, description, parentDirectoryUuid, userId); + @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid) { + exploreService.createSpreadsheetConfig(spreadsheetConfigDto, configName, description, parentDirectoryUuid); return ResponseEntity.status(HttpStatus.CREATED).build(); } @PostMapping(value = "/explore/spreadsheet-config-collections", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Create a spreadsheet configuration collection") @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Spreadsheet config collection created")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #parentDirectoryUuid, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#parentDirectoryUuid)") public ResponseEntity createSpreadsheetConfigCollection(@RequestBody String spreadsheetConfigCollectionDto, @RequestParam("name") String collectionName, @RequestParam(QUERY_PARAM_DESCRIPTION) String description, - @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.createSpreadsheetConfigCollection(spreadsheetConfigCollectionDto, collectionName, description, parentDirectoryUuid, userId); + @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid) { + exploreService.createSpreadsheetConfigCollection(spreadsheetConfigCollectionDto, collectionName, description, parentDirectoryUuid); return ResponseEntity.status(HttpStatus.CREATED).build(); } + // TODO: je passe de canCreate à canDuplicateTo. Pertinent ? @PostMapping(value = "/explore/spreadsheet-config-collections/merge", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Create a new spreadsheet configuration collection duplicating and merging a list of existing configurations") @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Spreadsheet config collection created")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #parentDirectoryUuid, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canDuplicateTo(#configUuids, #parentDirectoryUuid)") public ResponseEntity createSpreadsheetConfigCollectionFromConfigIds(@RequestBody List configUuids, @RequestParam("name") String collectionName, @RequestParam(QUERY_PARAM_DESCRIPTION) String description, - @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.createSpreadsheetConfigCollectionFromConfigIds(configUuids, collectionName, description, parentDirectoryUuid, userId); + @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid) { + exploreService.createSpreadsheetConfigCollectionFromConfigIds(configUuids, collectionName, description, parentDirectoryUuid); return ResponseEntity.status(HttpStatus.CREATED).build(); } @PutMapping(value = "/explore/spreadsheet-configs/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Modify a spreadsheet configuration") @ApiResponses(value = {@ApiResponse(responseCode = "204", description = "Spreadsheet config has been successfully modified")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #id, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#id)") public ResponseEntity updateSpreadsheetConfig(@PathVariable UUID id, @RequestBody String spreadsheetConfigDto, - @RequestHeader(QUERY_PARAM_USER_ID) String userId, @RequestParam(QUERY_PARAM_NAME) String name, @RequestParam(QUERY_PARAM_DESCRIPTION) String description) { - exploreService.updateSpreadsheetConfig(id, spreadsheetConfigDto, userId, name, description); + exploreService.updateSpreadsheetConfig(id, spreadsheetConfigDto, name, description); return ResponseEntity.noContent().build(); } @PutMapping(value = "/explore/spreadsheet-config-collections/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Modify a spreadsheet configuration collection") @ApiResponses(value = {@ApiResponse(responseCode = "204", description = "Spreadsheet config collection has been successfully modified")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #id, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#id)") public ResponseEntity updateSpreadsheetConfigCollection(@PathVariable UUID id, @RequestBody String spreadsheetConfigCollectionDto, - @RequestHeader(QUERY_PARAM_USER_ID) String userId, @RequestParam(QUERY_PARAM_NAME) String name, @RequestParam(QUERY_PARAM_DESCRIPTION) String description) { - exploreService.updateSpreadsheetConfigCollection(id, spreadsheetConfigCollectionDto, userId, name, description); + exploreService.updateSpreadsheetConfigCollection(id, spreadsheetConfigCollectionDto, name, description); return ResponseEntity.noContent().build(); } + // TODO: on rajoute un canRead ? @PutMapping(value = "/explore/spreadsheet-config-collections/{id}/spreadsheet-configs/replace-all", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Replace all spreadsheet configurations in a collection") @ApiResponses(value = {@ApiResponse(responseCode = "204", description = "Spreadsheet config collection has been successfully modified")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #id, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#id) && @authorizationService.canRead(#configUuids)") public ResponseEntity replaceAllSpreadsheetConfigsInCollection(@PathVariable UUID id, @RequestBody List configUuids, - @RequestHeader(QUERY_PARAM_USER_ID) String userId, @RequestParam(QUERY_PARAM_NAME) String name, @RequestParam(QUERY_PARAM_DESCRIPTION) String description) { - exploreService.replaceAllSpreadsheetConfigsInCollection(id, configUuids, userId, name, description); + exploreService.replaceAllSpreadsheetConfigsInCollection(id, configUuids, name, description); return ResponseEntity.noContent().build(); } @PostMapping(value = "/explore/spreadsheet-configs/{id}/duplicate") @Operation(summary = "Duplicate a spreadsheet configuration") @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Spreadsheet config has been successfully duplicated")}) - @PreAuthorize("@authorizationService.isAuthorizedForDuplication(#userId, #sourceId, #targetDirectoryId)") + @PreAuthorize("@authorizationService.canDuplicateTo(#sourceId, #targetDirectoryId)") public ResponseEntity duplicateSpreadsheetConfig(@PathVariable("id") UUID sourceId, - @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.duplicateSpreadsheetConfig(sourceId, targetDirectoryId, userId); + @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId) { + exploreService.duplicateSpreadsheetConfig(sourceId, targetDirectoryId); return ResponseEntity.status(HttpStatus.CREATED).build(); } + // TODO: je passe de canCreate à canDuplicateTo. Pertinent ? @PostMapping(value = "/explore/workspaces", params = "workspaceId") @Operation(summary = "Create a workspace by duplicating an existing workspace") @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Workspace created")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #parentDirectoryUuid, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canDuplicateTo(#workspaceId, #parentDirectoryUuid)") public ResponseEntity createWorkspace(@RequestParam("workspaceId") UUID workspaceId, @RequestParam("name") String workspaceName, @RequestParam(QUERY_PARAM_DESCRIPTION) String description, - @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.createWorkspace(workspaceId, workspaceName, description, parentDirectoryUuid, userId); + @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid) { + exploreService.createWorkspace(workspaceId, workspaceName, description, parentDirectoryUuid); return ResponseEntity.status(HttpStatus.CREATED).build(); } + // TODO: je rajoute un canRead ? @PutMapping(value = "/explore/workspaces/{id}", params = "workspaceId") @Operation(summary = "Replace a workspace with another workspace") @ApiResponses(value = {@ApiResponse(responseCode = "204", description = "Workspace has been successfully replaced")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #id, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#id) && @authorizationService.canRead(#workspaceId)") public ResponseEntity replaceWorkspace(@PathVariable UUID id, @RequestParam("workspaceId") UUID workspaceId, - @RequestHeader(QUERY_PARAM_USER_ID) String userId, @RequestParam(QUERY_PARAM_NAME) String name, @RequestParam(QUERY_PARAM_DESCRIPTION) String description) { - exploreService.replaceWorkspace(id, workspaceId, userId, name, description); + exploreService.replaceWorkspace(id, workspaceId, name, description); return ResponseEntity.noContent().build(); } @PostMapping(value = "/explore/workspaces/{id}/duplicate") @Operation(summary = "Duplicate a workspace") @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Workspace has been successfully duplicated")}) - @PreAuthorize("@authorizationService.isAuthorizedForDuplication(#userId, #sourceId, #targetDirectoryId)") + @PreAuthorize("@authorizationService.canDuplicateTo(#sourceId, #targetDirectoryId)") public ResponseEntity duplicateWorkspace(@PathVariable("id") UUID sourceId, - @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.duplicateWorkspace(sourceId, targetDirectoryId, userId); + @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId) { + exploreService.duplicateWorkspace(sourceId, targetDirectoryId); return ResponseEntity.status(HttpStatus.CREATED).build(); } @PostMapping(value = "/explore/spreadsheet-config-collections/{id}/duplicate") @Operation(summary = "Duplicate a spreadsheet configuration collection") @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Spreadsheet config collection has been successfully duplicated")}) - @PreAuthorize("@authorizationService.isAuthorizedForDuplication(#userId, #sourceId, #targetDirectoryId)") + @PreAuthorize("@authorizationService.canDuplicateTo(#sourceId, #targetDirectoryId)") public ResponseEntity duplicateSpreadsheetConfigCollection(@PathVariable("id") UUID sourceId, - @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.duplicateSpreadsheetConfigCollection(sourceId, targetDirectoryId, userId); + @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId) { + exploreService.duplicateSpreadsheetConfigCollection(sourceId, targetDirectoryId); return ResponseEntity.status(HttpStatus.CREATED).build(); } @PostMapping(value = "/explore/composite-modifications") @Operation(summary = "Create composite modification element from existing network modifications") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Modifications have been created and composite modification element created in the directory")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #parentDirectoryUuid, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#parentDirectoryUuid)") public ResponseEntity createCompositeModification(@RequestBody List modificationAttributes, @RequestParam(QUERY_PARAM_NAME) String name, @RequestParam(QUERY_PARAM_DESCRIPTION) String description, - @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.createCompositeModification(modificationAttributes, userId, name, description, parentDirectoryUuid); + @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryUuid) { + exploreService.createCompositeModification(modificationAttributes, name, description, parentDirectoryUuid); return ResponseEntity.ok().build(); } @PutMapping(value = "/explore/composite-modifications/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Modify a composite modification") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "The composite modification has been modified successfully")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #id, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#id)") public ResponseEntity updateCompositeNetworkModification(@PathVariable UUID id, @RequestBody List modificationUuids, - @RequestHeader(QUERY_PARAM_USER_ID) String userId, @RequestParam(QUERY_PARAM_NAME) String name, @RequestParam(QUERY_PARAM_DESCRIPTION) String description) { - exploreService.updateCompositeModification(id, modificationUuids, userId, name, description); + exploreService.updateCompositeModification(id, modificationUuids, name, description); return ResponseEntity.ok().build(); } @PostMapping(value = "/explore/composite-modifications/{id}/duplicate") @Operation(summary = "duplicate modification element") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Composite modification has been duplicated and corresponding element created in the directory")}) - @PreAuthorize("@authorizationService.isAuthorizedForDuplication(#userId, #networkModificationId, #targetDirectoryId)") + @PreAuthorize("@authorizationService.canDuplicateTo(#networkModificationId, #targetDirectoryId)") public ResponseEntity duplicateCompositeNetworkModification(@PathVariable("id") UUID networkModificationId, - @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - exploreService.duplicateCompositeModification(networkModificationId, targetDirectoryId, userId); + @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId) { + exploreService.duplicateCompositeModification(networkModificationId, targetDirectoryId); return ResponseEntity.ok().build(); } + // TODO @PutMapping(value = "/explore/elements/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Modify an element") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "The element has been modified successfully")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #id, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#id)") public ResponseEntity updateElement( @PathVariable UUID id, - @RequestBody ElementAttributes elementAttributes, - @RequestHeader("userId") String userId) { - - exploreService.updateElement(id, elementAttributes, userId); + @RequestBody ElementAttributes elementAttributes) { + exploreService.updateElement(id, elementAttributes); return ResponseEntity.ok().build(); } @@ -543,139 +522,151 @@ public ResponseEntity updateElement( @ApiResponse(responseCode = "404", description = "The elements or the targeted directory was not found"), @ApiResponse(responseCode = "403", description = "Not authorized execute this update") }) - @PreAuthorize("@authorizationService.isRecursivelyAuthorized(#userId, #elementsUuids, #targetDirectoryUuid)") + @PreAuthorize("@authorizationService.canMoveTo(#elementsUuids, #targetDirectoryUuid)") public ResponseEntity moveElementsDirectory( @RequestParam UUID targetDirectoryUuid, - @RequestBody List elementsUuids, - @RequestHeader("userId") String userId) { - exploreService.moveElementsDirectory(elementsUuids, targetDirectoryUuid, userId); + @RequestBody List elementsUuids) { + exploreService.moveElementsDirectory(elementsUuids, targetDirectoryUuid); return ResponseEntity.ok().build(); } + // TODO: ici dans getUsersIdentities, ça appelle directory-server getElements qui vérifie si on a le droit, avec strictMode = true. + // Je met un PreAuthorize, voir si on met un PreFilter à la place @GetMapping(value = "/explore/elements/users-identities", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "get users identities from the elements ids given as parameters") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "The users identities"), }) - public ResponseEntity getUsersIdentities(@RequestParam("ids") List ids, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - String usersIdentities = exploreService.getUsersIdentities(ids, userId); + @PreAuthorize("@authorizationService.canRead(#ids)") + public ResponseEntity getUsersIdentities(@RequestParam("ids") List ids) { + String usersIdentities = exploreService.getUsersIdentities(ids); return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(usersIdentities); } + // TODO: PostFilter ? et virer la vérification dans l'endpoint directory-server + // Mais pas très efficace, on ferait 2 requêtes eu lieu d'une + // Par contre c'est plus dans la logique de mon refacto @GetMapping(value = "/explore/directories/root-directories", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Get root directories") @ApiResponses(@ApiResponse(responseCode = "200", description = "The root directories")) - public ResponseEntity getRootDirectories(@RequestParam(value = "elementTypes", required = false, defaultValue = "") List types, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - return ResponseEntity.ok().body(directoryService.getRootDirectories(types, userId)); + public ResponseEntity getRootDirectories(@RequestParam(value = "elementTypes", required = false, defaultValue = "") List types) { + return ResponseEntity.ok().body(directoryService.getRootDirectories(types)); } + // TODO: idem que au dessus: PostFilter ? @RequestMapping(value = "explore/directories/root-directories", method = RequestMethod.HEAD) @Operation(summary = "Get if a root directory of this name exists") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "The root directory exists"), @ApiResponse(responseCode = "204", description = "The root directory doesn't exist"), }) - public ResponseEntity rootDirectoryExists(@RequestParam("directoryName") String directoryName, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - return ResponseEntity.status(directoryService.rootDirectoryExists(directoryName, userId)).contentType(MediaType.APPLICATION_JSON).build(); + public ResponseEntity rootDirectoryExists(@RequestParam("directoryName") String directoryName) { + return ResponseEntity.status(directoryService.rootDirectoryExists(directoryName)).contentType(MediaType.APPLICATION_JSON).build(); } + // TODO: ici tout le monde a les droits -> pas de @PreAuthorize @PostMapping(value = "/explore/directories/root-directories", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Create root directory") @ApiResponses(@ApiResponse(responseCode = "200", description = "The created root directory")) - public ResponseEntity createRootDirectory(@RequestBody String rootDirectoryAttributes, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(directoryService.createRootDirectory(rootDirectoryAttributes, userId)); + public ResponseEntity createRootDirectory(@RequestBody String rootDirectoryAttributes) { + return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(directoryService.createRootDirectory(rootDirectoryAttributes)); } + // TODO: je rajoute un canRead ? il est déjà côté directory-server : hasReadPermission(directoryUuid) et renvoie List.of() @GetMapping(value = "/explore/directories/{directoryUuid}/elements", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Get directory elements") @ApiResponses(@ApiResponse(responseCode = "200", description = "List directory's elements")) + @PreAuthorize("@authorizationService.canRead(#directoryUuid)") // renvoie une erreur, alors qu'actuellement on renvoie juste une liste vide public ResponseEntity getDirectoryElements(@PathVariable("directoryUuid") UUID directoryUuid, @RequestParam(value = "elementTypes", required = false, defaultValue = "") List types, - @RequestParam(value = "recursive", required = false, defaultValue = "false") Boolean recursive, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(directoryService.getDirectoryElements(directoryUuid, types, recursive, userId)); + @RequestParam(value = "recursive", required = false, defaultValue = "false") Boolean recursive) { + return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(directoryService.getDirectoryElements(directoryUuid, types, recursive)); } @PostMapping(value = "/explore/directories/{directoryUuid}/directories", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Create a subdirectory") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "The created directory"), @ApiResponse(responseCode = "409", description = "A directory with the same name already exists in the directory")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #directoryUuid, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#directoryUuid)") public ResponseEntity createDirectory(@PathVariable("directoryUuid") UUID directoryUuid, - @RequestBody ElementAttributes elementAttributes, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(directoryService.createElement(elementAttributes, directoryUuid, userId)); + @RequestBody ElementAttributes elementAttributes) { + return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(directoryService.createElement(elementAttributes, directoryUuid)); } + // TODO: est ce que je rajoute un canRead ici ? ça ne sert pas à grand chose, de toute manière on ne peut pas ouvrir l'élément par la suite si on n'a pas les droits + // par contre vérifier s'il n'y a pas des infos dans le path. Il n'y a que les parentDirectories et le depth de l'élément + // donc j'aurais tendance à dire qu'on veut justement que ce soit accessible à tous @GetMapping(value = "/explore/directories/elements/{elementUuid}/path", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Get path of element") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "List info of an element and its parents in order to get its path"), @ApiResponse(responseCode = "403", description = "Access forbidden for the element"), @ApiResponse(responseCode = "404", description = "The searched element was not found")}) - public ResponseEntity getPath(@PathVariable("elementUuid") UUID elementUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(directoryService.getPath(elementUuid, userId)); + public ResponseEntity getPath(@PathVariable("elementUuid") UUID elementUuid) { + return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(directoryService.getPath(elementUuid)); } + // TODO: accessible à tout le monde ; pas de @PreAuthorize @RequestMapping(method = RequestMethod.HEAD, value = "/explore/directories/{directoryUuid}/elements/{elementName}/types/{type}") @Operation(summary = "Check if an element with this name and this type already exists in the given directory") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "The element exists"), @ApiResponse(responseCode = "204", description = "The element doesn't exist")}) + //@PreAuthorize("true") public ResponseEntity elementExists(@PathVariable("directoryUuid") UUID directoryUuid, @PathVariable("elementName") String elementName, - @PathVariable("type") String type, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - return ResponseEntity.status(directoryService.elementExists(directoryUuid, elementName, type, userId)).contentType(MediaType.APPLICATION_JSON).build(); + @PathVariable("type") String type) { + return ResponseEntity.status(directoryService.elementExists(directoryUuid, elementName, type)).contentType(MediaType.APPLICATION_JSON).build(); } + // TODO: vérif dans endpoint de directory-server canRead(directoryUuid) -> je le rajoute ici en @PreAuthorize, à suppr dans directory-server ?? @GetMapping(value = "/explore/directories/{directoryUuid}/{elementName}/newNameCandidate") @Operation(summary = "Get a free name in directory based on the one given and it's type") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "If the element exists or not")}) + @PreAuthorize("@authorizationService.canRead(#directoryUuid)") public ResponseEntity elementNameCandidate(@PathVariable("directoryUuid") UUID directoryUuid, @PathVariable("elementName") String elementName, - @RequestParam("type") String type, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(directoryService.getNameCandidate(directoryUuid, elementName, type, userId)); + @RequestParam("type") String type) { + return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(directoryService.getNameCandidate(directoryUuid, elementName, type)); } + // TODO: accessible à tout le monde @GetMapping(value = "/explore/directories/elements/indexation-infos", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Search elements in elasticsearch") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "List of elements found")}) + //@PreAuthorize("true") public ResponseEntity searchElements( @Parameter(description = "User input") @RequestParam(value = "userInput") String userInput, - @Parameter(description = "Current directory UUID") @RequestParam(value = "directoryUuid", required = false, defaultValue = "") String directoryUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { + @Parameter(description = "Current directory UUID") @RequestParam(value = "directoryUuid", required = false, defaultValue = "") String directoryUuid) { return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON) - .body(directoryService.searchElements(userInput, directoryUuid, userId)); + .body(directoryService.searchElements(userInput, directoryUuid)); } + // TODO: accessible à tous ??? ou remplacer entièrement par @PreAuthorize... (bof) @GetMapping(value = "/explore/elements/{elementUuid}") @Operation(summary = "Check if user has a given right on a directory, or a single element by checking its parent") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "The user has the right on the element"), @ApiResponse(responseCode = "204", description = "The user has not the right on the element"), }) + //@PreAuthorize("true") public ResponseEntity hasRight(@PathVariable("elementUuid") UUID elementUuid, - @RequestParam(name = "permission") PermissionType permission, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - directoryService.checkPermission(List.of(elementUuid), null, userId, permission); + @RequestParam(name = "permission") PermissionType permission) { + directoryService.checkPermission(List.of(elementUuid), null, permission); return ResponseEntity.ok().build(); } + // TODO: verif READ dans endpoint directory-server sur les studyUuids retournées car on leur fait getElementsInfos en strictMode = false ; + // voir ce qu'on en fait, je ne sais pas + // je rajoute le canRead sur l'elementUuid' @GetMapping(value = "/explore/elements/{elementUuid}/referencing-element-infos", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Get the elements using the given shared element") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "The infos of the elements using the shared element"), @ApiResponse(responseCode = "404", description = "The shared element was not found"), }) - public ResponseEntity> getReferencingElementInfos(@PathVariable("elementUuid") UUID elementUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { + @PreAuthorize("@authorizationService.canRead(#elementUuid)") + public ResponseEntity> getReferencingElementInfos(@PathVariable("elementUuid") UUID elementUuid) { return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON) - .body(exploreService.getReferencingElementInfos(elementUuid, userId)); + .body(exploreService.getReferencingElementInfos(elementUuid)); } @GetMapping(value = "/explore/directories/{directoryUuid}/permissions", produces = MediaType.APPLICATION_JSON_VALUE) @@ -685,13 +676,13 @@ public ResponseEntity> getReferencingElementInfos( @ApiResponse(responseCode = "403", description = "Not authorized to view permissions for this directory"), @ApiResponse(responseCode = "404", description = "The directory was not found") }) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #directoryUuid, null, T(org.gridsuite.explore.server.dto.PermissionType).READ)") - public ResponseEntity> getDirectoryPermissions(@PathVariable("directoryUuid") UUID directoryUuid, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { + @PreAuthorize("@authorizationService.canRead(#directoryUuid)") + public ResponseEntity> getDirectoryPermissions(@PathVariable("directoryUuid") UUID directoryUuid) { return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON) - .body(directoryService.getDirectoryPermissions(directoryUuid, userId)); + .body(directoryService.getDirectoryPermissions(directoryUuid)); } + // TODO @PutMapping(value = "/explore/directories/{directoryUuid}/permissions", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Set permissions for a directory") @ApiResponses(value = { @@ -699,83 +690,79 @@ public ResponseEntity> getDirectoryPermissions(@PathVariable @ApiResponse(responseCode = "403", description = "Not authorized to update permissions for this directory"), @ApiResponse(responseCode = "404", description = "The directory was not found") }) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #directoryUuid, null, T(org.gridsuite.explore.server.dto.PermissionType).MANAGE)") + @PreAuthorize("@authorizationService.canManage(#directoryUuid)") public ResponseEntity setDirectoryPermissions(@PathVariable("directoryUuid") UUID directoryUuid, - @RequestBody List permissions, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - directoryService.setDirectoryPermissions(directoryUuid, permissions, userId); + @RequestBody List permissions) { + directoryService.setDirectoryPermissions(directoryUuid, permissions); return ResponseEntity.ok().build(); } + // TODO @PostMapping(value = "/explore/process-configs", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Create a process config") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Process config has been successfully created")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #parentDirectoryId, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#parentDirectoryId)") public ResponseEntity createProcessConfig(@RequestParam(QUERY_PARAM_NAME) String name, @RequestParam(QUERY_PARAM_DESCRIPTION) String description, @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryId, - @RequestHeader(QUERY_PARAM_USER_ID) String userId, @RequestBody(required = false) String processConfig) { - return ResponseEntity.ok().body(exploreService.createProcessConfig(name, processConfig, description, userId, parentDirectoryId)); + return ResponseEntity.ok().body(exploreService.createProcessConfig(name, processConfig, description, parentDirectoryId)); } + // TODO @PutMapping(value = "/explore/process-configs/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Modify a process config") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Process config has been successfully modified")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #id, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#id)") public ResponseEntity updateProcessConfig(@PathVariable UUID id, @RequestParam(QUERY_PARAM_NAME) String name, @RequestParam(QUERY_PARAM_DESCRIPTION) String description, - @RequestHeader(QUERY_PARAM_USER_ID) String userId, @RequestBody(required = false) String processConfig) { - exploreService.updateProcessConfig(id, name, processConfig, description, userId); + exploreService.updateProcessConfig(id, name, processConfig, description); return ResponseEntity.ok().build(); } + // TODO @PostMapping(value = "/explore/process-configs/{id}/duplicate") @Operation(summary = "Duplicate a process config") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Process config has been successfully created")}) - @PreAuthorize("@authorizationService.isAuthorizedForDuplication(#userId, #id, #targetDirectoryId)") + @PreAuthorize("@authorizationService.canDuplicateTo(#id, #targetDirectoryId)") public ResponseEntity duplicateProcessConfig(@PathVariable("id") UUID id, - @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - return ResponseEntity.ok().body(exploreService.duplicateProcessConfig(id, targetDirectoryId, userId)); + @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId) { + return ResponseEntity.ok().body(exploreService.duplicateProcessConfig(id, targetDirectoryId)); } @PostMapping(value = "/explore/dynamic-mappings", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Create a dynamic mapping") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Dynamic mapping has been successfully created")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #parentDirectoryId, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#parentDirectoryId)") public ResponseEntity createDynamicMapping(@RequestParam(QUERY_PARAM_NAME) String name, @RequestParam(QUERY_PARAM_DESCRIPTION) String description, @RequestParam(QUERY_PARAM_PARENT_DIRECTORY_ID) UUID parentDirectoryId, - @RequestHeader(QUERY_PARAM_USER_ID) String userId, @RequestBody(required = false) String dynamicMapping) { - UUID newDynamicMappingUuid = exploreService.createDynamicMapping(name, dynamicMapping, description, userId, parentDirectoryId); + UUID newDynamicMappingUuid = exploreService.createDynamicMapping(name, dynamicMapping, description, parentDirectoryId); return ResponseEntity.ofNullable(newDynamicMappingUuid); } @PutMapping(value = "/explore/dynamic-mappings/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Modify a dynamic mapping") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Dynamic mapping has been successfully modified")}) - @PreAuthorize("@authorizationService.isAuthorized(#userId, #id, null, T(org.gridsuite.explore.server.dto.PermissionType).WRITE)") + @PreAuthorize("@authorizationService.canWrite(#id)") public ResponseEntity updateDynamicMapping(@PathVariable UUID id, @RequestParam(QUERY_PARAM_NAME) String name, @RequestParam(QUERY_PARAM_DESCRIPTION) String description, - @RequestHeader(QUERY_PARAM_USER_ID) String userId, @RequestBody(required = false) String dynamicMapping) { - exploreService.updateDynamicMapping(id, name, dynamicMapping, description, userId); + exploreService.updateDynamicMapping(id, name, dynamicMapping, description); return ResponseEntity.ok().build(); } @PostMapping(value = "/explore/dynamic-mappings/{id}/duplicate") @Operation(summary = "Duplicate a dynamic mapping") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Dynamic mapping has been successfully duplicated")}) - @PreAuthorize("@authorizationService.isAuthorizedForDuplication(#userId, #id, #targetDirectoryId)") + @PreAuthorize("@authorizationService.canDuplicateTo(#id, #targetDirectoryId)") public ResponseEntity duplicateDynamicMapping(@PathVariable("id") UUID id, - @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId, - @RequestHeader(QUERY_PARAM_USER_ID) String userId) { - UUID newDynamicMappingUuid = exploreService.duplicateDynamicMapping(id, targetDirectoryId, userId); + @RequestParam(name = QUERY_PARAM_PARENT_DIRECTORY_ID, required = false) UUID targetDirectoryId) { + UUID newDynamicMappingUuid = exploreService.duplicateDynamicMapping(id, targetDirectoryId); return ResponseEntity.ofNullable(newDynamicMappingUuid); } } diff --git a/src/main/java/org/gridsuite/explore/server/controller/FilterController.java b/src/main/java/org/gridsuite/explore/server/controller/FilterController.java index fcdd5258..c2f3f710 100644 --- a/src/main/java/org/gridsuite/explore/server/controller/FilterController.java +++ b/src/main/java/org/gridsuite/explore/server/controller/FilterController.java @@ -11,6 +11,7 @@ import org.gridsuite.explore.server.services.FilterService; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @@ -29,7 +30,10 @@ public FilterController(FilterService filterService) { this.filterService = filterService; } + // TODO: appel direct à filter-server -> n'existe pas dans directory-server donc rien à checker ? + // vérifier où est utilisé cet endpoint. Pour l'instant je mets canRead @GetMapping(value = "/filters/{id}", produces = MediaType.APPLICATION_JSON_VALUE) + @PreAuthorize("@authorizationService.canRead(#id)") public ResponseEntity getFilter(@PathVariable("id") UUID id) { return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(filterService.getFilter(id)); } diff --git a/src/main/java/org/gridsuite/explore/server/controller/NetworkConversionController.java b/src/main/java/org/gridsuite/explore/server/controller/NetworkConversionController.java index 71be6de3..518f07bd 100644 --- a/src/main/java/org/gridsuite/explore/server/controller/NetworkConversionController.java +++ b/src/main/java/org/gridsuite/explore/server/controller/NetworkConversionController.java @@ -12,11 +12,11 @@ import org.springframework.core.io.Resource; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @@ -28,33 +28,37 @@ @Tag(name = "Explore server - Network conversion") public class NetworkConversionController { - private static final String HEADER_USER_ID = "userId"; - private final NetworkConversionService networkConversionService; public NetworkConversionController(NetworkConversionService networkConversionService) { this.networkConversionService = networkConversionService; } + // TODO: à checker ??? @GetMapping(value = "/cases/{caseUuid}/import-parameters", produces = MediaType.APPLICATION_JSON_VALUE) + @PreAuthorize("@authorizationService.canRead(#caseUuid)") public ResponseEntity getCaseImportParameters(@PathVariable("caseUuid") UUID caseUuid) { return ResponseEntity.ok(networkConversionService.getCaseImportParameters(caseUuid)); } + // TODO: à checker ??? @PostMapping(value = "/cases/{caseUuid}/convert/{format}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + @PreAuthorize("@authorizationService.canWrite(#caseUuid)") public ResponseEntity convertCase(@PathVariable("caseUuid") UUID caseUuid, @PathVariable("format") String format, @RequestParam(value = "fileName", required = false) String fileName, - @RequestBody(required = false) String formatParameters, - @RequestHeader(HEADER_USER_ID) String userId) { - return ResponseEntity.ok(networkConversionService.convertCase(caseUuid, format, fileName, formatParameters, userId)); + @RequestBody(required = false) String formatParameters) { + return ResponseEntity.ok(networkConversionService.convertCase(caseUuid, format, fileName, formatParameters)); } + // TODO: à checker ??? @GetMapping(value = "/download-file/{exportUuid}") + @PreAuthorize("@authorizationService.canRead(#exportUuid)") public ResponseEntity downloadFile(@PathVariable("exportUuid") UUID exportUuid) { return networkConversionService.downloadFile(exportUuid); } + // TODO: accessible à tous @GetMapping(value = "/export/formats", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity getExportFormats() { return ResponseEntity.ok(networkConversionService.getExportFormats()); diff --git a/src/main/java/org/gridsuite/explore/server/controller/SupervisionController.java b/src/main/java/org/gridsuite/explore/server/controller/SupervisionController.java index b9a4dd37..e6ffa0e4 100644 --- a/src/main/java/org/gridsuite/explore/server/controller/SupervisionController.java +++ b/src/main/java/org/gridsuite/explore/server/controller/SupervisionController.java @@ -7,6 +7,7 @@ import org.gridsuite.explore.server.ExploreApi; import org.gridsuite.explore.server.services.SupervisionService; import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import java.util.List; @@ -15,6 +16,7 @@ @RestController @RequestMapping(value = "/" + ExploreApi.API_VERSION + "/supervision") @Tag(name = "Explore server - Supervision") +@PreAuthorize("hasRole('ADMIN')") public class SupervisionController { private final SupervisionService supervisionService; @@ -25,9 +27,8 @@ public SupervisionController(SupervisionService supervisionService) { @DeleteMapping(value = "/explore/elements", params = "ids") @Operation(summary = "Remove directories/elements") @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "directories/elements was successfully removed")}) - public ResponseEntity deleteElements(@RequestParam("ids") List elementsUuid, - @RequestHeader("userId") String userId) { - supervisionService.deleteElements(elementsUuid, userId); + public ResponseEntity deleteElements(@RequestParam("ids") List elementsUuid) { + supervisionService.deleteElements(elementsUuid); return ResponseEntity.ok().build(); } } diff --git a/src/main/java/org/gridsuite/explore/server/dto/ElementAttributes.java b/src/main/java/org/gridsuite/explore/server/dto/ElementAttributes.java index 25396999..3b4e95e1 100644 --- a/src/main/java/org/gridsuite/explore/server/dto/ElementAttributes.java +++ b/src/main/java/org/gridsuite/explore/server/dto/ElementAttributes.java @@ -8,6 +8,8 @@ import com.fasterxml.jackson.annotation.JsonInclude; import lombok.*; +import org.gridsuite.explore.server.UserAuthentication; +import org.springframework.security.core.context.SecurityContextHolder; import java.time.Instant; import java.util.ArrayList; @@ -55,11 +57,17 @@ public ElementAttributes(UUID elementUuid, String elementName, String type, Stri this(elementUuid, elementName, type, owner, subdirectoriesCount, description, null, null, null, null, null); } + public ElementAttributes(UUID elementUuid, String elementName, String type, long subdirectoriesCount, String description) { + String owner = ((UserAuthentication) SecurityContextHolder.getContext().getAuthentication()).getUserId(); + this(elementUuid, elementName, type, owner, subdirectoriesCount, description, null, null, null, null, null); + } + public ElementAttributes(UUID elementUuid, String elementName, String type, String owner, long subdirectoriesCount, String description, Map specificMetadata) { this(elementUuid, elementName, type, owner, subdirectoriesCount, description, null, null, null, null, specificMetadata); } - public ElementAttributes(UUID elementUuid, String elementName, String type, String owner, long subdirectoriesCount, String description, DirectoryElementStatus status) { + public ElementAttributes(UUID elementUuid, String elementName, String type, long subdirectoriesCount, String description, DirectoryElementStatus status) { + String owner = ((UserAuthentication) SecurityContextHolder.getContext().getAuthentication()).getUserId(); this(elementUuid, elementName, type, owner, subdirectoriesCount, description, null, null, status, null, null); } diff --git a/src/main/java/org/gridsuite/explore/server/services/AuthorizationService.java b/src/main/java/org/gridsuite/explore/server/services/AuthorizationService.java index f82ec0c6..136389cc 100644 --- a/src/main/java/org/gridsuite/explore/server/services/AuthorizationService.java +++ b/src/main/java/org/gridsuite/explore/server/services/AuthorizationService.java @@ -6,6 +6,7 @@ */ package org.gridsuite.explore.server.services; +import jakarta.validation.constraints.NotNull; import org.gridsuite.explore.server.dto.PermissionType; import org.springframework.stereotype.Service; @@ -24,18 +25,47 @@ public AuthorizationService(DirectoryService directoryService) { this.directoryService = directoryService; } - //This method should only be called inside of @PreAuthorize to centralize permission checks - public void isAuthorized(String userId, List elementUuids, UUID targetDirectoryUuid, PermissionType permissionType) { - directoryService.checkPermission(elementUuids, targetDirectoryUuid, userId, permissionType); + public boolean canRead(UUID elementUuid) { + return canRead(List.of(elementUuid)); } - //This method should only be called inside of @PreAuthorize to centralize permission checks - public void isAuthorizedForDuplication(String userId, UUID elementToDuplicate, UUID targetDirectoryUuid) { - directoryService.checkPermission(List.of(elementToDuplicate), null, userId, PermissionType.READ); - directoryService.checkPermission(List.of(targetDirectoryUuid != null ? targetDirectoryUuid : elementToDuplicate), null, userId, PermissionType.WRITE); + public boolean canRead(List elementUuids) { + directoryService.checkPermission(elementUuids, null, PermissionType.READ); + return true; } - public void isRecursivelyAuthorized(String userId, List elementUuids, UUID targetDirectoryUuid) { - directoryService.checkPermission(elementUuids, targetDirectoryUuid, userId, PermissionType.WRITE, true); + public boolean canWrite(UUID elementUuid) { + directoryService.checkPermission(List.of(elementUuid), null, PermissionType.WRITE); + return true; + } + + public boolean canDuplicateTo(UUID elementUuid, UUID targetDirectoryUuid) { + return canDuplicateTo(List.of(elementUuid), targetDirectoryUuid != null ? targetDirectoryUuid : elementUuid); + } + + public boolean canDuplicateTo(List elementUuids, @NotNull UUID targetDirectoryUuid) { + return canRead(elementUuids) && canWrite(targetDirectoryUuid); + } + + public boolean canDelete(UUID elementUuid) { + return canDelete(List.of(elementUuid)); + } + + public boolean canDelete(List elementUuids) { + return canRecursivelyWrite(elementUuids, null); + } + + public boolean canMoveTo(List elementUuids, UUID targetDirectoryUuid) { + return canRecursivelyWrite(elementUuids, targetDirectoryUuid); + } // pas sûre de ça, p-e on veut plus la main au niveau des endpoints pour savoir exactement ce qu'on checke ? + + public boolean canRecursivelyWrite(List elementUuids, UUID targetDirectoryUuid) { + directoryService.checkPermission(elementUuids, targetDirectoryUuid, PermissionType.WRITE, true); + return true; + } + + public boolean canManage(UUID elementUuid) { + directoryService.checkPermission(List.of(elementUuid), null, PermissionType.MANAGE); + return true; } } diff --git a/src/main/java/org/gridsuite/explore/server/services/CaseService.java b/src/main/java/org/gridsuite/explore/server/services/CaseService.java index 0f9f76ce..9509cb94 100644 --- a/src/main/java/org/gridsuite/explore/server/services/CaseService.java +++ b/src/main/java/org/gridsuite/explore/server/services/CaseService.java @@ -119,13 +119,11 @@ UUID duplicateCase(UUID caseId) { } @Override - public void delete(UUID id, String userId) { + public void delete(UUID id) { String path = UriComponentsBuilder.fromPath(DELIMITER + CASE_SERVER_API_VERSION + "/cases/{id}") .buildAndExpand(id) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - restTemplate.exchange(caseServerBaseUri + path, HttpMethod.DELETE, new HttpEntity<>(headers), Void.class); + restTemplate.exchange(caseServerBaseUri + path, HttpMethod.DELETE, HttpEntity.EMPTY, Void.class); } @Override diff --git a/src/main/java/org/gridsuite/explore/server/services/ContingencyListService.java b/src/main/java/org/gridsuite/explore/server/services/ContingencyListService.java index 9acd6448..115d0f66 100644 --- a/src/main/java/org/gridsuite/explore/server/services/ContingencyListService.java +++ b/src/main/java/org/gridsuite/explore/server/services/ContingencyListService.java @@ -27,7 +27,6 @@ public class ContingencyListService implements IDirectoryElementsService { private static final String ACTIONS_API_VERSION = "v1"; private static final String DELIMITER = "/"; - private static final String HEADER_USER_ID = "userId"; private String actionsServerBaseUri; private final RestTemplate restTemplate; @@ -41,13 +40,11 @@ public void setActionsServerBaseUri(String actionsServerBaseUri) { } @Override - public void delete(UUID id, String userId) { + public void delete(UUID id) { String path = UriComponentsBuilder.fromPath(DELIMITER + ACTIONS_API_VERSION + "/contingency-lists/{id}") .buildAndExpand(id) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - restTemplate.exchange(actionsServerBaseUri + path, HttpMethod.DELETE, new HttpEntity<>(headers), Void.class); + restTemplate.exchange(actionsServerBaseUri + path, HttpMethod.DELETE, HttpEntity.EMPTY, Void.class); } public void insertIdentifierContingencyList(UUID id, String content) { @@ -111,21 +108,11 @@ public List> getMetadata(List contingencyListsUuids) { }).getBody(); } - public void updateContingencyList(UUID id, String content, String userId, String element) { - + public void updateContingencyList(UUID id, String content, String element) { String path = UriComponentsBuilder.fromPath(DELIMITER + ACTIONS_API_VERSION + element) .buildAndExpand(id) .toUriString(); - restTemplate.exchange(actionsServerBaseUri + path, HttpMethod.PUT, getHttpEntityWithUserHeader(userId, content), Void.class); - - } - - private HttpEntity getHttpEntityWithUserHeader(String userId, String content) { - - HttpHeaders headers = new HttpHeaders(); - headers.set(HEADER_USER_ID, userId); - headers.setContentType(MediaType.APPLICATION_JSON); + restTemplate.exchange(actionsServerBaseUri + path, HttpMethod.PUT, new HttpEntity<>(content), Void.class); - return new HttpEntity<>(content, headers); } } diff --git a/src/main/java/org/gridsuite/explore/server/services/DirectoryService.java b/src/main/java/org/gridsuite/explore/server/services/DirectoryService.java index 364af5f6..9cf6d0d7 100644 --- a/src/main/java/org/gridsuite/explore/server/services/DirectoryService.java +++ b/src/main/java/org/gridsuite/explore/server/services/DirectoryService.java @@ -95,33 +95,28 @@ public void setDirectoryServerBaseUri(String directoryServerBaseUri) { this.directoryServerBaseUri = directoryServerBaseUri; } - public String getRootDirectories(List types, String userId) { + public String getRootDirectories(List types) { String path = UriComponentsBuilder .fromPath(DIRECTORIES_SERVER_ROOT_PATH + "/root-directories") .queryParam(PARAM_ELEMENT_TYPES, types) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - headers.setContentType(MediaType.APPLICATION_JSON); + return restTemplate - .exchange(directoryServerBaseUri + path, HttpMethod.GET, new HttpEntity<>(headers), String.class) + .exchange(directoryServerBaseUri + path, HttpMethod.GET, HttpEntity.EMPTY, String.class) .getBody(); } - public String createRootDirectory(String rootDirectoryAttributes, String userId) { + public String createRootDirectory(String rootDirectoryAttributes) { String path = UriComponentsBuilder .fromPath(DIRECTORIES_SERVER_ROOT_PATH + "/root-directories") .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - headers.setContentType(MediaType.APPLICATION_JSON); return restTemplate - .exchange(directoryServerBaseUri + path, HttpMethod.POST, new HttpEntity<>(rootDirectoryAttributes, headers), String.class) + .exchange(directoryServerBaseUri + path, HttpMethod.POST, new HttpEntity<>(rootDirectoryAttributes), String.class) .getBody(); } - public String getDirectoryElements(UUID directoryUuid, List types, boolean recursive, String userId) { + public String getDirectoryElements(UUID directoryUuid, List types, boolean recursive) { String path = UriComponentsBuilder .fromPath(DIRECTORIES_SERVER_DIRECTORIES_ROOT_PATH + "/{directoryUuid}/elements") .queryParam(PARAM_ELEMENT_TYPES, types) @@ -129,25 +124,19 @@ public String getDirectoryElements(UUID directoryUuid, List types, boole .buildAndExpand(directoryUuid) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - headers.setContentType(MediaType.APPLICATION_JSON); return restTemplate - .exchange(directoryServerBaseUri + path, HttpMethod.GET, new HttpEntity<>(headers), String.class) + .exchange(directoryServerBaseUri + path, HttpMethod.GET, HttpEntity.EMPTY, String.class) .getBody(); } - public String getPath(UUID elementUuid, String userId) { + public String getPath(UUID elementUuid) { String path = UriComponentsBuilder .fromPath(DIRECTORIES_SERVER_ROOT_PATH + "/elements/{elementUuid}/path") .buildAndExpand(elementUuid) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - headers.setContentType(MediaType.APPLICATION_JSON); return restTemplate - .exchange(directoryServerBaseUri + path, HttpMethod.GET, new HttpEntity<>(headers), String.class) + .exchange(directoryServerBaseUri + path, HttpMethod.GET, HttpEntity.EMPTY, String.class) .getBody(); } @@ -155,100 +144,81 @@ public String getPath(UUID elementUuid, String userId) { * @return the path of each element, indexed by element uuid. Each path is ordered from the root directory to the * element itself, and unknown elements are absent from the result. */ - public Map> getElementsPaths(List elementUuids, String userId) { + public Map> getElementsPaths(List elementUuids) { String path = UriComponentsBuilder.fromPath(ELEMENTS_SERVER_ROOT_PATH + "/paths") .queryParam(PARAM_IDS, elementUuids) .buildAndExpand() .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - headers.setContentType(MediaType.APPLICATION_JSON); Map> elementsPaths = restTemplate - .exchange(directoryServerBaseUri + path, HttpMethod.GET, new HttpEntity<>(headers), - new ParameterizedTypeReference>>() { - }) + .exchange(directoryServerBaseUri + path, HttpMethod.GET, HttpEntity.EMPTY, + new ParameterizedTypeReference>>() { }) .getBody(); return Objects.requireNonNullElse(elementsPaths, Collections.emptyMap()); } - public HttpStatusCode elementExists(UUID directoryUuid, String elementName, String type, String userId) { + public HttpStatusCode elementExists(UUID directoryUuid, String elementName, String type) { String path = UriComponentsBuilder .fromPath(DIRECTORIES_SERVER_DIRECTORIES_ROOT_PATH + "/{directoryUuid}/elements/{elementName}/types/{type}") .buildAndExpand(directoryUuid, elementName, type) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - headers.setContentType(MediaType.APPLICATION_JSON); return restTemplate - .exchange(directoryServerBaseUri + path, HttpMethod.HEAD, new HttpEntity<>(headers), Void.class) + .exchange(directoryServerBaseUri + path, HttpMethod.HEAD, HttpEntity.EMPTY, Void.class) .getStatusCode(); } - public HttpStatusCode rootDirectoryExists(String directoryName, String userId) { + public HttpStatusCode rootDirectoryExists(String directoryName) { String path = UriComponentsBuilder .fromPath(DIRECTORIES_SERVER_ROOT_PATH + "/root-directories") .queryParam(PARAM_DIRECTORY_NAME, directoryName) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - headers.setContentType(MediaType.APPLICATION_JSON); return restTemplate - .exchange(directoryServerBaseUri + path, HttpMethod.HEAD, new HttpEntity<>(headers), Void.class) + .exchange(directoryServerBaseUri + path, HttpMethod.HEAD, HttpEntity.EMPTY, Void.class) .getStatusCode(); } - public String getNameCandidate(UUID directoryUuid, String elementName, String type, String userId) { + public String getNameCandidate(UUID directoryUuid, String elementName, String type) { String path = UriComponentsBuilder .fromPath(DIRECTORIES_SERVER_DIRECTORIES_ROOT_PATH + "/{directoryUuid}/{elementName}/newNameCandidate") .queryParam(PARAM_TYPE, type) .buildAndExpand(directoryUuid, elementName) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - headers.setContentType(MediaType.APPLICATION_JSON); return restTemplate - .exchange(directoryServerBaseUri + path, HttpMethod.GET, new HttpEntity<>(headers), String.class) + .exchange(directoryServerBaseUri + path, HttpMethod.GET, HttpEntity.EMPTY, String.class) .getBody(); } - public String searchElements(String userInput, String directoryUuid, String userId) { + public String searchElements(String userInput, String directoryUuid) { URI uri = UriComponentsBuilder .fromUriString(directoryServerBaseUri + DIRECTORIES_SERVER_ROOT_PATH + "/elements/indexation-infos") .queryParam(PARAM_DIRECTORY_UUID, "{directoryUuid}") .queryParam(PARAM_USER_INPUT, "{userInput}") .build(directoryUuid, userInput); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - headers.setContentType(MediaType.APPLICATION_JSON); return restTemplate - .exchange(uri, HttpMethod.GET, new HttpEntity<>(headers), String.class) + .exchange(uri, HttpMethod.GET, HttpEntity.EMPTY, String.class) .getBody(); } - public ElementAttributes createElement(ElementAttributes elementAttributes, UUID directoryUuid, String userId) { - return createElementWithNewName(elementAttributes, directoryUuid, userId, false); + public ElementAttributes createElement(ElementAttributes elementAttributes, UUID directoryUuid) { + return createElementWithNewName(elementAttributes, directoryUuid, false); } - public ElementAttributes createElementWithNewName(ElementAttributes elementAttributes, UUID directoryUuid, String userId, boolean allowNewName) { + public ElementAttributes createElementWithNewName(ElementAttributes elementAttributes, UUID directoryUuid, boolean allowNewName) { String path = UriComponentsBuilder .fromPath(DIRECTORIES_SERVER_DIRECTORIES_ROOT_PATH + "/{directoryUuid}/elements?allowNewName={allowNewName}") .buildAndExpand(directoryUuid, allowNewName) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - headers.setContentType(MediaType.APPLICATION_JSON); - HttpEntity httpEntity = new HttpEntity<>(elementAttributes, headers); + return restTemplate - .exchange(directoryServerBaseUri + path, HttpMethod.POST, httpEntity, ElementAttributes.class) + .exchange(directoryServerBaseUri + path, HttpMethod.POST, new HttpEntity<>(elementAttributes), ElementAttributes.class) .getBody(); } - public ElementAttributes duplicateElement(UUID elementUuid, UUID newElementUuid, UUID targetDirectoryId, DirectoryElementStatus newElementStatus, String userId) { + public ElementAttributes duplicateElement(UUID elementUuid, UUID newElementUuid, UUID targetDirectoryId, DirectoryElementStatus newElementStatus) { UriComponentsBuilder uri = UriComponentsBuilder .fromPath(ELEMENTS_SERVER_ROOT_PATH + DELIMITER + "{uuid}" + DELIMITER + "duplicate") .queryParam("newElementUuid", newElementUuid) @@ -258,25 +228,22 @@ public ElementAttributes duplicateElement(UUID elementUuid, UUID newElementUuid, } String path = uri.buildAndExpand(elementUuid) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - headers.setContentType(MediaType.APPLICATION_JSON); + return restTemplate - .exchange(directoryServerBaseUri + path, HttpMethod.POST, new HttpEntity<>(headers), ElementAttributes.class) + .exchange(directoryServerBaseUri + path, HttpMethod.POST, HttpEntity.EMPTY, ElementAttributes.class) .getBody(); } - public void deleteDirectoryElement(UUID elementUuid, String userId) { + public void deleteDirectoryElement(UUID elementUuid) { String path = UriComponentsBuilder .fromPath(ELEMENTS_SERVER_ELEMENT_PATH) .buildAndExpand(elementUuid) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.DELETE, new HttpEntity<>(headers), Void.class); + + restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.DELETE, HttpEntity.EMPTY, Void.class); } - public void deleteElementsFromDirectory(List elementUuids, UUID parentDirectoryUuid, String userId) { + public void deleteElementsFromDirectory(List elementUuids, UUID parentDirectoryUuid) { var ids = elementUuids.stream().map(UUID::toString).collect(Collectors.joining(",")); String path = UriComponentsBuilder .fromPath(ELEMENTS_SERVER_ROOT_PATH) @@ -284,9 +251,8 @@ public void deleteElementsFromDirectory(List elementUuids, UUID parentDire .queryParam("parentDirectoryUuid", parentDirectoryUuid) .buildAndExpand() .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.DELETE, new HttpEntity<>(headers), Void.class); + + restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.DELETE, HttpEntity.EMPTY, Void.class); } public ElementAttributes getElementInfos(UUID elementUuid) { @@ -294,18 +260,18 @@ public ElementAttributes getElementInfos(UUID elementUuid) { .fromPath(ELEMENTS_SERVER_ELEMENT_PATH) .buildAndExpand(elementUuid) .toUriString(); - return Objects.requireNonNull(restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.GET, null, ElementAttributes.class).getBody()); + return Objects.requireNonNull(restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.GET, HttpEntity.EMPTY, ElementAttributes.class).getBody()); } - public List getElementsInfos(List elementsUuids, List elementTypes, String userId) { - return getElementsInfos(elementsUuids, elementTypes, userId, true); + public List getElementsInfos(List elementsUuids, List elementTypes) { + return getElementsInfos(elementsUuids, elementTypes, true); } /** * @param strictMode when false, elements the user cannot read or that no longer exist are absent from the result * instead of failing the whole call */ - public List getElementsInfos(List elementsUuids, List elementTypes, String userId, boolean strictMode) { + public List getElementsInfos(List elementsUuids, List elementTypes, boolean strictMode) { var ids = elementsUuids.stream().map(UUID::toString).collect(Collectors.joining(",")); String path = UriComponentsBuilder.fromPath(ELEMENTS_SERVER_ROOT_PATH).toUriString() + "?ids=" + ids; @@ -318,52 +284,46 @@ public List getElementsInfos(List elementsUuids, List elementAttributesList; - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - elementAttributesList = restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.GET, new HttpEntity<>(headers), - new ParameterizedTypeReference>() { - }).getBody(); + elementAttributesList = restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.GET, HttpEntity.EMPTY, + new ParameterizedTypeReference>() { }).getBody(); return Objects.requireNonNullElse(elementAttributesList, Collections.emptyList()); } + // TODO: est ce que je laisse userId en argument ici ? public int getUserCasesCount(String userId) { String path = UriComponentsBuilder .fromPath(DELIMITER + DIRECTORY_SERVER_API_VERSION + DELIMITER + "users/{userId}/cases/count") .buildAndExpand(userId) .toUriString(); - return Objects.requireNonNull(restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.GET, null, Integer.class).getBody()); + return Objects.requireNonNull(restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.GET, HttpEntity.EMPTY, Integer.class).getBody()); } - public void notifyDirectoryChanged(UUID elementUuid, String userId) { + // TODO: method not used -> to delete ? + public void notifyDirectoryChanged(UUID elementUuid) { String path = UriComponentsBuilder .fromPath(ELEMENTS_SERVER_ELEMENT_PATH + "/notification?type={update_directory}") .buildAndExpand(elementUuid, NotificationType.UPDATE_DIRECTORY.name()) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.POST, new HttpEntity<>(headers), Void.class); + restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.POST, HttpEntity.EMPTY, Void.class); } - private List getDirectoryElements(UUID directoryUuid, String userId) { + private List getDirectoryElements(UUID directoryUuid) { String path = UriComponentsBuilder.fromPath(DIRECTORIES_SERVER_DIRECTORIES_ROOT_PATH + "/{directoryUuid}/elements") .buildAndExpand(directoryUuid) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); List elementAttributesList; elementAttributesList = restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.GET, - new HttpEntity<>(headers), new ParameterizedTypeReference>() { - }).getBody(); + HttpEntity.EMPTY, new ParameterizedTypeReference>() { }).getBody(); return Objects.requireNonNullElse(elementAttributesList, Collections.emptyList()); } - public void deleteElement(UUID id, String userId) { + public void deleteElement(UUID id) { ElementAttributes elementAttribute = getElementInfos(id); IDirectoryElementsService service = getGenericService(elementAttribute.getType()); - service.delete(elementAttribute.getElementUuid(), userId); + service.delete(elementAttribute.getElementUuid()); } private IDirectoryElementsService getGenericService(String type) { @@ -375,8 +335,8 @@ private IDirectoryElementsService getGenericService(String type) { } public List getElementsMetadata(List ids, List elementTypes, - List equipmentTypes, String userId) { - Map> elementAttributesListByType = getElementsInfos(ids, elementTypes, userId) + List equipmentTypes) { + Map> elementAttributesListByType = getElementsInfos(ids, elementTypes) .stream() .collect(Collectors.groupingBy(ElementAttributes::getType)); List listOfElements = new ArrayList<>(); @@ -415,98 +375,78 @@ public Map getElementsName(List ids) { }).getBody(); } - public void updateElement(UUID elementUuid, ElementAttributes elementAttributes, String userId) { + public void updateElement(UUID elementUuid, ElementAttributes elementAttributes) { String path = UriComponentsBuilder .fromPath(ELEMENTS_SERVER_ELEMENT_PATH) .buildAndExpand(elementUuid) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.set(HEADER_USER_ID, userId); - headers.setContentType(MediaType.APPLICATION_JSON); - HttpEntity httpEntity = new HttpEntity<>(elementAttributes, headers); - restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.PUT, httpEntity, Void.class); + restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.PUT, new HttpEntity<>(elementAttributes), Void.class); } // TODO get id/type recursively then do batch delete @Override - public void delete(UUID id, String userId) { - List elementAttributesList = getDirectoryElements(id, userId); - elementAttributesList.forEach(elementAttributes -> deleteElement(elementAttributes.getElementUuid(), userId)); + public void delete(UUID id) { + List elementAttributesList = getDirectoryElements(id); + elementAttributesList.forEach(elementAttributes -> deleteElement(elementAttributes.getElementUuid())); } - public void moveElementsDirectory(List elementsUuids, UUID targetDirectoryUuid, String userId) { + public void moveElementsDirectory(List elementsUuids, UUID targetDirectoryUuid) { String path = UriComponentsBuilder .fromPath(ELEMENTS_SERVER_ROOT_PATH) .queryParam(PARAM_TARGET_DIRECTORY_UUID, targetDirectoryUuid) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.set(HEADER_USER_ID, userId); - headers.setContentType(MediaType.APPLICATION_JSON); - HttpEntity> httpEntity = new HttpEntity<>(elementsUuids, headers); - restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.PUT, httpEntity, Void.class); + restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.PUT, new HttpEntity<>(elementsUuids), Void.class); } - public void checkPermission(List elementUuids, UUID targetDirectoryUuid, String userId, PermissionType permissionType) { - checkPermission(elementUuids, targetDirectoryUuid, userId, permissionType, false); + public void checkPermission(List elementUuids, UUID targetDirectoryUuid, PermissionType permissionType) { + checkPermission(elementUuids, targetDirectoryUuid, permissionType, false); } - //This method should only be called inside of AuthorizationService to centralize permission checks - public void checkPermission(List elementUuids, UUID targetDirectoryUuid, String userId, PermissionType permissionType, boolean recursiveCheck) { - String ids = elementUuids.stream().map(UUID::toString).collect(Collectors.joining(",")); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - + public void checkPermission(List elementUuids, UUID targetDirectoryUuid, PermissionType permissionType, boolean recursiveCheck) { String path = UriComponentsBuilder.fromPath(ELEMENTS_SERVER_ROOT_PATH + "/authorized") - .queryParam(PARAM_ACCESS_TYPE, permissionType) - .queryParam(PARAM_IDS, ids) - .queryParam(PARAM_TARGET_DIRECTORY_UUID, targetDirectoryUuid) - .queryParam(PARAM_RECURSIVE_CHECK, recursiveCheck) - .buildAndExpand() - .toUriString(); + .queryParam(PARAM_ACCESS_TYPE, permissionType) + .queryParam(PARAM_IDS, elementUuids) + .queryParam(PARAM_TARGET_DIRECTORY_UUID, targetDirectoryUuid) + .queryParam(PARAM_RECURSIVE_CHECK, recursiveCheck) + .buildAndExpand() + .toUriString(); - restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.GET, new HttpEntity<>(headers), Void.class); + restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.GET, HttpEntity.EMPTY, Void.class); } - public List getDirectoryPermissions(UUID directoryUuid, String userId) { + public List getDirectoryPermissions(UUID directoryUuid) { String path = UriComponentsBuilder .fromPath(DIRECTORIES_SERVER_DIRECTORIES_ROOT_PATH + "/{directoryUuid}/permissions") .buildAndExpand(directoryUuid) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - headers.setContentType(MediaType.APPLICATION_JSON); ResponseEntity> response = restTemplate.exchange( directoryServerBaseUri + path, HttpMethod.GET, - new HttpEntity<>(headers), - new ParameterizedTypeReference>() { - } + HttpEntity.EMPTY, + new ParameterizedTypeReference<>() { } ); return response.getBody(); } - public void setDirectoryPermissions(UUID directoryUuid, List permissions, String userId) { + public void setDirectoryPermissions(UUID directoryUuid, List permissions) { String path = UriComponentsBuilder .fromPath(DIRECTORIES_SERVER_DIRECTORIES_ROOT_PATH + "/{directoryUuid}/permissions") .buildAndExpand(directoryUuid) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - headers.setContentType(MediaType.APPLICATION_JSON); restTemplate.exchange( directoryServerBaseUri + path, HttpMethod.PUT, - new HttpEntity<>(permissions, headers), + new HttpEntity<>(permissions), Void.class ); } - public void updateElementsStatus(List elementUuids, DirectoryElementStatus status, String userId) { + public void updateElementsStatus(List elementUuids, DirectoryElementStatus status) { if (elementUuids == null || elementUuids.isEmpty()) { return; } @@ -517,8 +457,7 @@ public void updateElementsStatus(List elementUuids, DirectoryElementStatus .queryParam(PARAM_STATUS, status) .buildAndExpand() .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.PUT, new HttpEntity<>(headers), Void.class); + + restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.PUT, HttpEntity.EMPTY, Void.class); } } diff --git a/src/main/java/org/gridsuite/explore/server/services/DynamicMappingService.java b/src/main/java/org/gridsuite/explore/server/services/DynamicMappingService.java index c1997213..dad29566 100644 --- a/src/main/java/org/gridsuite/explore/server/services/DynamicMappingService.java +++ b/src/main/java/org/gridsuite/explore/server/services/DynamicMappingService.java @@ -68,7 +68,7 @@ public UUID duplicateMapping(UUID sourceMappingUuid) { } @Override - public void delete(UUID id, String userId) { + public void delete(UUID id) { restClient.delete() .uri(MAPPING_PATH + DELIMITER + "{id}", id) .retrieve() diff --git a/src/main/java/org/gridsuite/explore/server/services/ExploreService.java b/src/main/java/org/gridsuite/explore/server/services/ExploreService.java index 44740d09..3f4ad7e4 100644 --- a/src/main/java/org/gridsuite/explore/server/services/ExploreService.java +++ b/src/main/java/org/gridsuite/explore/server/services/ExploreService.java @@ -8,6 +8,7 @@ import jakarta.annotation.Nullable; import org.apache.commons.lang3.StringUtils; +import org.gridsuite.explore.server.UserAuthentication; import org.gridsuite.explore.server.dto.CaseAlertThresholdMessage; import org.gridsuite.explore.server.dto.CaseInfo; import org.gridsuite.explore.server.dto.DirectoryElementStatus; @@ -22,6 +23,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; +import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.multipart.MultipartFile; @@ -29,6 +31,7 @@ import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; +import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -114,13 +117,13 @@ public ExploreService( this.exploreServerExecutionService = exploreServerExecutionService; } - public void createStudy(String studyName, CaseInfo caseInfo, String description, String userId, UUID parentDirectoryUuid, Map importParams, Boolean duplicateCase) { - ElementAttributes elementAttributes = new ElementAttributes(UUID.randomUUID(), studyName, STUDY, userId, 0L, description, CREATING); + public void createStudy(String studyName, CaseInfo caseInfo, String description, UUID parentDirectoryUuid, Map importParams, Boolean duplicateCase) { + ElementAttributes elementAttributes = new ElementAttributes(UUID.randomUUID(), studyName, STUDY, 0L, description, CREATING); String elementName = getElementName(caseInfo.caseUuid()); - studyService.insertStudyWithExistingCaseFile(elementAttributes.getElementUuid(), userId, caseInfo.caseUuid(), caseInfo.caseFormat(), importParams, duplicateCase, elementName); - createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, userId, studyService::delete); + studyService.insertStudyWithExistingCaseFile(elementAttributes.getElementUuid(), caseInfo.caseUuid(), caseInfo.caseFormat(), importParams, duplicateCase, elementName); + createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, studyService::delete); } private @Nullable String getElementName(UUID elementUuid) { @@ -140,86 +143,86 @@ public void createStudy(String studyName, CaseInfo caseInfo, String description, return elementName; } - public void duplicateStudy(UUID sourceStudyUuid, UUID targetDirectoryId, String userId) { - UUID newStudyId = studyService.duplicateStudy(sourceStudyUuid, userId); - duplicateDirectoryElementOrDeleteElement(sourceStudyUuid, newStudyId, targetDirectoryId, CREATING, userId, studyService::delete); + public void duplicateStudy(UUID sourceStudyUuid, UUID targetDirectoryId) { + UUID newStudyId = studyService.duplicateStudy(sourceStudyUuid); + duplicateDirectoryElementOrDeleteElement(sourceStudyUuid, newStudyId, targetDirectoryId, CREATING, studyService::delete); } - public void createCase(String caseName, MultipartFile caseFile, String description, String userId, UUID parentDirectoryUuid) { + public void createCase(String caseName, MultipartFile caseFile, String description, UUID parentDirectoryUuid) { UUID uuid = caseService.importCase(caseFile); - ElementAttributes elementAttributes = new ElementAttributes(uuid, caseName, CASE, userId, 0L, description); - createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, userId, caseService::delete); + ElementAttributes elementAttributes = new ElementAttributes(uuid, caseName, CASE, 0L, description); + createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, caseService::delete); } - public void persistCase(String caseName, UUID caseUuid, String description, String userId, UUID parentDirectoryUuid) { + public void persistCase(String caseName, UUID caseUuid, String description, UUID parentDirectoryUuid) { caseService.persistCase(caseUuid); - ElementAttributes elementAttributes = new ElementAttributes(caseUuid, caseName, CASE, userId, 0L, description); - createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, userId, caseService::delete); + ElementAttributes elementAttributes = new ElementAttributes(caseUuid, caseName, CASE, 0L, description); + createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, caseService::delete); } - public void duplicateCase(UUID sourceCaseUuid, UUID targetDirectoryId, String userId) { + public void duplicateCase(UUID sourceCaseUuid, UUID targetDirectoryId) { UUID newCaseId = caseService.duplicateCase(sourceCaseUuid); - duplicateDirectoryElementOrDeleteElement(sourceCaseUuid, newCaseId, targetDirectoryId, userId, caseService::delete); + duplicateDirectoryElementOrDeleteElement(sourceCaseUuid, newCaseId, targetDirectoryId, caseService::delete); } - public void duplicateContingencyList(UUID contingencyListsId, UUID targetDirectoryId, String userId, ContingencyListType contingencyListType) { + public void duplicateContingencyList(UUID contingencyListsId, UUID targetDirectoryId, ContingencyListType contingencyListType) { UUID newId = switch (contingencyListType) { case IDENTIFIERS -> contingencyListService.duplicateIdentifierContingencyList(contingencyListsId); case FILTERS -> contingencyListService.duplicateFilterBasedContingencyList(contingencyListsId); }; - duplicateDirectoryElementOrDeleteElement(contingencyListsId, newId, targetDirectoryId, userId, contingencyListService::delete); + duplicateDirectoryElementOrDeleteElement(contingencyListsId, newId, targetDirectoryId, contingencyListService::delete); } - public void createIdentifierContingencyList(String listName, String content, String description, String userId, UUID parentDirectoryUuid) { - ElementAttributes elementAttributes = new ElementAttributes(UUID.randomUUID(), listName, CONTINGENCY_LIST, userId, 0L, description); + public void createIdentifierContingencyList(String listName, String content, String description, UUID parentDirectoryUuid) { + ElementAttributes elementAttributes = new ElementAttributes(UUID.randomUUID(), listName, CONTINGENCY_LIST, 0L, description); contingencyListService.insertIdentifierContingencyList(elementAttributes.getElementUuid(), content); - createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, userId, contingencyListService::delete); + createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, contingencyListService::delete); } - public void createFilterBasedContingencyList(String listName, String content, String description, String userId, UUID parentDirectoryUuid) { - ElementAttributes elementAttributes = new ElementAttributes(UUID.randomUUID(), listName, CONTINGENCY_LIST, userId, 0L, description); + public void createFilterBasedContingencyList(String listName, String content, String description, UUID parentDirectoryUuid) { + ElementAttributes elementAttributes = new ElementAttributes(UUID.randomUUID(), listName, CONTINGENCY_LIST, 0L, description); contingencyListService.insertFilterBasedContingencyList(elementAttributes.getElementUuid(), content); - createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, userId, contingencyListService::delete); + createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, contingencyListService::delete); } - public void createFilter(String filter, String filterName, String description, UUID parentDirectoryUuid, String userId) { - ElementAttributes elementAttributes = new ElementAttributes(UUID.randomUUID(), filterName, FILTER, userId, 0, description); - filterService.insertFilter(filter, elementAttributes.getElementUuid(), userId); - createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, userId, filterService::delete); + public void createFilter(String filter, String filterName, String description, UUID parentDirectoryUuid) { + ElementAttributes elementAttributes = new ElementAttributes(UUID.randomUUID(), filterName, FILTER, 0, description); + filterService.insertFilter(filter, elementAttributes.getElementUuid()); + createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, filterService::delete); } - public void duplicateFilter(UUID sourceFilterId, UUID targetDirectoryId, String userId) { + public void duplicateFilter(UUID sourceFilterId, UUID targetDirectoryId) { UUID newFilterId = filterService.duplicateFilter(sourceFilterId); - duplicateDirectoryElementOrDeleteElement(sourceFilterId, newFilterId, targetDirectoryId, userId, filterService::delete); + duplicateDirectoryElementOrDeleteElement(sourceFilterId, newFilterId, targetDirectoryId, filterService::delete); } - public CompletableFuture deleteElement(UUID id, String userId) { - return exploreServerExecutionService.runAsync(() -> doDeleteElement(id, userId)); + public CompletableFuture deleteElement(UUID id) { + return exploreServerExecutionService.runAsync(() -> doDeleteElement(id)); } - private void doDeleteElement(UUID id, String userId) { + private void doDeleteElement(UUID id) { try { - directoryService.updateElementsStatus(List.of(id), DirectoryElementStatus.DELETING, userId); + directoryService.updateElementsStatus(List.of(id), DirectoryElementStatus.DELETING); // FIXME dirty fix to ignore errors and still delete the elements in the directory-server. To delete when handled properly. - directoryService.deleteElement(id, userId); + directoryService.deleteElement(id); } catch (Exception e) { LOGGER.error(e.toString(), e); } finally { - directoryService.deleteDirectoryElement(id, userId); + directoryService.deleteDirectoryElement(id); } } - public CompletableFuture deleteElementsFromDirectory(List uuids, UUID parentDirectoryUuid, String userId) { - return exploreServerExecutionService.runAsync(() -> doDeleteElementsFromDirectory(uuids, parentDirectoryUuid, userId)); + public CompletableFuture deleteElementsFromDirectory(List uuids, UUID parentDirectoryUuid) { + return exploreServerExecutionService.runAsync(() -> doDeleteElementsFromDirectory(uuids, parentDirectoryUuid)); } - private void doDeleteElementsFromDirectory(List uuids, UUID parentDirectoryUuid, String userId) { - directoryService.updateElementsStatus(uuids, DirectoryElementStatus.DELETING, userId); + private void doDeleteElementsFromDirectory(List uuids, UUID parentDirectoryUuid) { + directoryService.updateElementsStatus(uuids, DirectoryElementStatus.DELETING); List deletedIds = new ArrayList<>(); List failedIds = new ArrayList<>(); for (UUID id : uuids) { try { - directoryService.deleteElement(id, userId); + directoryService.deleteElement(id); deletedIds.add(id); } catch (Exception e) { LOGGER.error("Failed to delete element {}", id, e); @@ -228,43 +231,43 @@ private void doDeleteElementsFromDirectory(List uuids, UUID parentDirector } if (!deletedIds.isEmpty()) { try { - directoryService.deleteElementsFromDirectory(deletedIds, parentDirectoryUuid, userId); + directoryService.deleteElementsFromDirectory(deletedIds, parentDirectoryUuid); } catch (Exception e) { LOGGER.error("Failed to remove deleted elements {} from directory", deletedIds, e); failedIds.addAll(deletedIds); } } if (!failedIds.isEmpty()) { - directoryService.updateElementsStatus(failedIds, DirectoryElementStatus.CREATED, userId); + directoryService.updateElementsStatus(failedIds, DirectoryElementStatus.CREATED); } } - public void updateFilter(UUID id, String filter, String userId, String name, String description) { + public void updateFilter(UUID id, String filter, String name, String description) { // check if the user have the right to update the filter - filterService.updateFilter(id, filter, userId); + filterService.updateFilter(id, filter); ElementAttributes elementAttributes = new ElementAttributes(); elementAttributes.setDescription(description); if (StringUtils.isNotBlank(name)) { elementAttributes.setElementName(name); } - directoryService.updateElement(id, elementAttributes, userId); + directoryService.updateElement(id, elementAttributes); } - public void updateContingencyList(UUID id, String content, String userId, String name, String description, ContingencyListType contingencyListType) { + public void updateContingencyList(UUID id, String content, String name, String description, ContingencyListType contingencyListType) { // check if the user have the right to update the contingency - contingencyListService.updateContingencyList(id, content, userId, getProperPath(contingencyListType)); + contingencyListService.updateContingencyList(id, content, getProperPath(contingencyListType)); ElementAttributes elementAttributes = new ElementAttributes(); elementAttributes.setDescription(description); if (StringUtils.isNotBlank(name)) { elementAttributes.setElementName(name); } - directoryService.updateElement(id, elementAttributes, userId); + directoryService.updateElement(id, elementAttributes); } - public void updateCompositeModification(UUID id, List modificationUuids, String userId, String name, String description) { + public void updateCompositeModification(UUID id, List modificationUuids, String name, String description) { networkModificationService.replaceCompositeModification(id, name, modificationUuids); - updateElementNameAndDescription(id, name, description, userId); + updateElementNameAndDescription(id, name, description); } public List getCompositeModificationContent(UUID compositeModificationId) { @@ -273,14 +276,14 @@ public List getCompositeModificationContent(UUID compositeModificationId return requestedContent != null ? requestedContent : List.of(); } - private void updateElementNameAndDescription(UUID id, String name, String description, String userId) { + private void updateElementNameAndDescription(UUID id, String name, String description) { if (StringUtils.isBlank(name)) { return; } ElementAttributes elementAttributes = new ElementAttributes(); elementAttributes.setElementName(name); elementAttributes.setDescription(description); - directoryService.updateElement(id, elementAttributes, userId); + directoryService.updateElement(id, elementAttributes); } private String getProperPath(ContingencyListType contingencyListType) { @@ -290,153 +293,153 @@ private String getProperPath(ContingencyListType contingencyListType) { }; } - public void createParameters(String parameters, ParametersType parametersType, String parametersName, String description, UUID parentDirectoryUuid, String userId) { + public void createParameters(String parameters, ParametersType parametersType, String parametersName, String description, UUID parentDirectoryUuid) { UUID parametersUuid = parametersService.createParameters(parameters, parametersType); - ElementAttributes elementAttributes = new ElementAttributes(parametersUuid, parametersName, parametersType.name(), userId, 0, description); - createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, userId, parametersService::delete); + ElementAttributes elementAttributes = new ElementAttributes(parametersUuid, parametersName, parametersType.name(), 0, description); + createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, parametersService::delete); } - public void updateParameters(UUID id, String parameters, ParametersType parametersType, String userId, String name, String description) { + public void updateParameters(UUID id, String parameters, ParametersType parametersType, String name, String description) { parametersService.updateParameters(id, parameters, parametersType); - updateElementNameAndDescription(id, name, description, userId); + updateElementNameAndDescription(id, name, description); } - public void duplicateParameters(UUID sourceId, UUID targetDirectoryId, ParametersType parametersType, String userId) { - UUID newParametersUuid = parametersService.duplicateParameters(sourceId, parametersType, userId); - duplicateDirectoryElementOrDeleteElement(sourceId, newParametersUuid, targetDirectoryId, userId, parametersService::delete); + public void duplicateParameters(UUID sourceId, UUID targetDirectoryId, ParametersType parametersType) { + UUID newParametersUuid = parametersService.duplicateParameters(sourceId, parametersType); + duplicateDirectoryElementOrDeleteElement(sourceId, newParametersUuid, targetDirectoryId, parametersService::delete); } - public void createDiagramConfig(String diagramConfig, String diagramConfigName, String description, UUID parentDirectoryUuid, String userId) { + public void createDiagramConfig(String diagramConfig, String diagramConfigName, String description, UUID parentDirectoryUuid) { UUID diagramConfigUuid = singleLineDiagramService.createDiagramConfig(diagramConfig); - ElementAttributes elementAttributes = new ElementAttributes(diagramConfigUuid, diagramConfigName, DIAGRAM_CONFIG, userId, 0, description); - createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, userId, singleLineDiagramService::delete); + ElementAttributes elementAttributes = new ElementAttributes(diagramConfigUuid, diagramConfigName, DIAGRAM_CONFIG, 0, description); + createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, singleLineDiagramService::delete); } - public void duplicateDiagramConfig(UUID sourceId, UUID targetDirectoryId, String userId) { + public void duplicateDiagramConfig(UUID sourceId, UUID targetDirectoryId) { UUID newConfigUuid = singleLineDiagramService.duplicateDiagramConfig(sourceId); - duplicateDirectoryElementOrDeleteElement(sourceId, newConfigUuid, targetDirectoryId, userId, singleLineDiagramService::delete); + duplicateDirectoryElementOrDeleteElement(sourceId, newConfigUuid, targetDirectoryId, singleLineDiagramService::delete); } - public void updateDiagramConfig(UUID id, String diagramConfig, String userId, String name, String description) { + public void updateDiagramConfig(UUID id, String diagramConfig, String name, String description) { singleLineDiagramService.updateDiagramConfig(id, diagramConfig); - updateElementNameAndDescription(id, name, description, userId); + updateElementNameAndDescription(id, name, description); } - public void createSpreadsheetConfig(String spreadsheetConfigDto, String configName, String description, UUID parentDirectoryUuid, String userId) { + public void createSpreadsheetConfig(String spreadsheetConfigDto, String configName, String description, UUID parentDirectoryUuid) { UUID spreadsheetConfigUuid = spreadsheetConfigService.createSpreadsheetConfig(spreadsheetConfigDto); - ElementAttributes elementAttributes = new ElementAttributes(spreadsheetConfigUuid, configName, SPREADSHEET_CONFIG, userId, 0, description); - createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, userId, spreadsheetConfigService::delete); + ElementAttributes elementAttributes = new ElementAttributes(spreadsheetConfigUuid, configName, SPREADSHEET_CONFIG, 0, description); + createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, spreadsheetConfigService::delete); } - public void createSpreadsheetConfigCollection(String spreadsheetConfigCollectionDto, String collectionName, String description, UUID parentDirectoryUuid, String userId) { + public void createSpreadsheetConfigCollection(String spreadsheetConfigCollectionDto, String collectionName, String description, UUID parentDirectoryUuid) { UUID spreadsheetConfigUuid = spreadsheetConfigCollectionService.createSpreadsheetConfigCollection(spreadsheetConfigCollectionDto); - createSpreadsheetConfigCollectionElement(spreadsheetConfigUuid, collectionName, description, parentDirectoryUuid, userId); + createSpreadsheetConfigCollectionElement(spreadsheetConfigUuid, collectionName, description, parentDirectoryUuid); } - public void createSpreadsheetConfigCollectionFromConfigIds(List configIds, String collectionName, String description, UUID parentDirectoryUuid, String userId) { + public void createSpreadsheetConfigCollectionFromConfigIds(List configIds, String collectionName, String description, UUID parentDirectoryUuid) { UUID spreadsheetConfigUuid = spreadsheetConfigCollectionService.createSpreadsheetConfigCollectionFromConfigIds(configIds); - createSpreadsheetConfigCollectionElement(spreadsheetConfigUuid, collectionName, description, parentDirectoryUuid, userId); + createSpreadsheetConfigCollectionElement(spreadsheetConfigUuid, collectionName, description, parentDirectoryUuid); } - private void createSpreadsheetConfigCollectionElement(UUID spreadsheetConfigUuid, String collectionName, String description, UUID parentDirectoryUuid, String userId) { - ElementAttributes elementAttributes = new ElementAttributes(spreadsheetConfigUuid, collectionName, SPREADSHEET_CONFIG_COLLECTION, userId, 0, description); - createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, userId, spreadsheetConfigCollectionService::delete); + private void createSpreadsheetConfigCollectionElement(UUID spreadsheetConfigUuid, String collectionName, String description, UUID parentDirectoryUuid) { + ElementAttributes elementAttributes = new ElementAttributes(spreadsheetConfigUuid, collectionName, SPREADSHEET_CONFIG_COLLECTION, 0, description); + createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, spreadsheetConfigCollectionService::delete); } - public void updateSpreadsheetConfig(UUID id, String spreadsheetConfigDto, String userId, String name, String description) { + public void updateSpreadsheetConfig(UUID id, String spreadsheetConfigDto, String name, String description) { spreadsheetConfigService.updateSpreadsheetConfig(id, spreadsheetConfigDto); - updateElementNameAndDescription(id, name, description, userId); + updateElementNameAndDescription(id, name, description); } - public void updateSpreadsheetConfigCollection(UUID id, String spreadsheetConfigCollectionDto, String userId, String name, String description) { + public void updateSpreadsheetConfigCollection(UUID id, String spreadsheetConfigCollectionDto, String name, String description) { spreadsheetConfigCollectionService.updateSpreadsheetConfigCollection(id, spreadsheetConfigCollectionDto); - updateElementNameAndDescription(id, name, description, userId); - notificationService.emitElementUpdated(id, userId); + updateElementNameAndDescription(id, name, description); + notificationService.emitElementUpdated(id); } - public void replaceAllSpreadsheetConfigsInCollection(UUID id, List configIds, String userId, String name, String description) { + public void replaceAllSpreadsheetConfigsInCollection(UUID id, List configIds, String name, String description) { spreadsheetConfigCollectionService.replaceAllSpreadsheetConfigsInCollection(id, configIds); - updateElementNameAndDescription(id, name, description, userId); - notificationService.emitElementUpdated(id, userId); + updateElementNameAndDescription(id, name, description); + notificationService.emitElementUpdated(id); } - public void duplicateSpreadsheetConfig(UUID sourceId, UUID targetDirectoryId, String userId) { + public void duplicateSpreadsheetConfig(UUID sourceId, UUID targetDirectoryId) { UUID newSpreadsheetConfigUuid = spreadsheetConfigService.duplicateSpreadsheetConfig(sourceId); - duplicateDirectoryElementOrDeleteElement(sourceId, newSpreadsheetConfigUuid, targetDirectoryId, userId, spreadsheetConfigService::delete); + duplicateDirectoryElementOrDeleteElement(sourceId, newSpreadsheetConfigUuid, targetDirectoryId, spreadsheetConfigService::delete); } - public void duplicateSpreadsheetConfigCollection(UUID sourceId, UUID targetDirectoryId, String userId) { + public void duplicateSpreadsheetConfigCollection(UUID sourceId, UUID targetDirectoryId) { UUID newSpreadsheetConfigUuid = spreadsheetConfigCollectionService.duplicateSpreadsheetConfigCollection(sourceId); - duplicateDirectoryElementOrDeleteElement(sourceId, newSpreadsheetConfigUuid, targetDirectoryId, userId, spreadsheetConfigCollectionService::delete); + duplicateDirectoryElementOrDeleteElement(sourceId, newSpreadsheetConfigUuid, targetDirectoryId, spreadsheetConfigCollectionService::delete); } - public void createWorkspace(UUID workspaceId, String workspaceName, String description, UUID parentDirectoryUuid, String userId) { + public void createWorkspace(UUID workspaceId, String workspaceName, String description, UUID parentDirectoryUuid) { UUID newWorkspaceId = workspaceService.duplicateWorkspace(workspaceId); - ElementAttributes elementAttributes = new ElementAttributes(newWorkspaceId, workspaceName, WORKSPACE, userId, 0, description); - createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, userId, workspaceService::delete); + ElementAttributes elementAttributes = new ElementAttributes(newWorkspaceId, workspaceName, WORKSPACE, 0, description); + createDirectoryElementOrDeleteElement(elementAttributes, parentDirectoryUuid, workspaceService::delete); } - public void replaceWorkspace(UUID id, UUID workspaceId, String userId, String name, String description) { + public void replaceWorkspace(UUID id, UUID workspaceId, String name, String description) { workspaceService.replaceWorkspace(id, workspaceId); - updateElementNameAndDescription(id, name, description, userId); + updateElementNameAndDescription(id, name, description); } - public void duplicateWorkspace(UUID sourceId, UUID targetDirectoryId, String userId) { + public void duplicateWorkspace(UUID sourceId, UUID targetDirectoryId) { UUID newWorkspaceId = workspaceService.duplicateWorkspace(sourceId); - duplicateDirectoryElementOrDeleteElement(sourceId, newWorkspaceId, targetDirectoryId, userId, workspaceService::delete); + duplicateDirectoryElementOrDeleteElement(sourceId, newWorkspaceId, targetDirectoryId, workspaceService::delete); } - public void createCompositeModification(List modificationUuids, String userId, String name, + public void createCompositeModification(List modificationUuids, String name, String description, UUID parentDirectoryUuid) { // create composite modifications UUID modificationsUuid = networkModificationService.createCompositeModification(modificationUuids, name); - ElementAttributes elementAttributes = new ElementAttributes(modificationsUuid, name, MODIFICATION, - userId, 0L, description); - createDirectoryElementWithNewNameOrDeleteElement(elementAttributes, parentDirectoryUuid, userId, networkModificationService::delete); + ElementAttributes elementAttributes = new ElementAttributes(modificationsUuid, name, MODIFICATION, 0L, description); + createDirectoryElementWithNewNameOrDeleteElement(elementAttributes, parentDirectoryUuid, networkModificationService::delete); } - public void duplicateCompositeModification(UUID sourceId, UUID parentDirectoryUuid, String userId) { + public void duplicateCompositeModification(UUID sourceId, UUID parentDirectoryUuid) { // create duplicated modification Map newModificationsUuids = networkModificationService.duplicateCompositeModifications(List.of(sourceId)); UUID newNetworkModification = newModificationsUuids.get(sourceId); // create corresponding directory element - duplicateDirectoryElementOrDeleteElement(sourceId, newNetworkModification, parentDirectoryUuid, userId, networkModificationService::delete); + duplicateDirectoryElementOrDeleteElement(sourceId, newNetworkModification, parentDirectoryUuid, networkModificationService::delete); } - public void assertCanCreateCase(String userId) { + public void assertCanCreateCase() { + String userId = ((UserAuthentication) SecurityContextHolder.getContext().getAuthentication()).getUserId(); Integer userMaxAllowedStudiesAndCases = userAdminService.getUserMaxAllowedCases(userId); if (userMaxAllowedStudiesAndCases != null) { int userCasesCount = directoryService.getUserCasesCount(userId); if (userCasesCount >= userMaxAllowedStudiesAndCases) { throw new ExploreException(EXPLORE_MAX_ELEMENTS_EXCEEDED, "max allowed cases reached", Map.of("limit", userMaxAllowedStudiesAndCases)); } - notifyCasesThresholdReached(userCasesCount, userMaxAllowedStudiesAndCases, userId); + notifyCasesThresholdReached(userCasesCount, userMaxAllowedStudiesAndCases); } } - public void notifyCasesThresholdReached(int userCasesCount, int userMaxAllowedStudiesAndCases, String userId) { + public void notifyCasesThresholdReached(int userCasesCount, int userMaxAllowedStudiesAndCases) { Integer casesAlertThreshold = userAdminService.getCasesAlertThreshold(); if (casesAlertThreshold != null) { int userCasesUsagePercentage = (100 * userCasesCount) / userMaxAllowedStudiesAndCases; if (userCasesUsagePercentage >= casesAlertThreshold) { CaseAlertThresholdMessage caseAlertThresholdMessage = new CaseAlertThresholdMessage(userCasesUsagePercentage, userCasesCount); - notificationService.emitUserMessage(userId, "casesAlertThreshold", caseAlertThresholdMessage); + notificationService.emitUserMessage("casesAlertThreshold", caseAlertThresholdMessage); } } } - public void updateElement(UUID id, ElementAttributes elementAttributes, String userId) { + public void updateElement(UUID id, ElementAttributes elementAttributes) { // The check to know if the user have the right to update the element is done in the directory-server - directoryService.updateElement(id, elementAttributes, userId); + directoryService.updateElement(id, elementAttributes); ElementAttributes elementsInfos = directoryService.getElementInfos(id); - notifyElementUpdated(elementsInfos, userId); + notifyElementUpdated(elementsInfos); } - private void notifyElementUpdated(ElementAttributes element, String userId) { + private void notifyElementUpdated(ElementAttributes element) { // send notification if the study name was updated if (STUDY.equals(element.getType())) { - studyService.notifyStudyUpdate(element.getElementUuid(), userId); + studyService.notifyStudyUpdate(element.getElementUuid()); } // the composite modification name has to be updated in order to match the new element name @@ -445,24 +448,24 @@ private void notifyElementUpdated(ElementAttributes element, String userId) { } } - private void notifyElementMoved(ElementAttributes element, String userId) { + private void notifyElementMoved(ElementAttributes element) { // send notification if the study name was updated if (STUDY.equals(element.getType())) { - studyService.notifyStudyUpdate(element.getElementUuid(), userId); + studyService.notifyStudyUpdate(element.getElementUuid()); } } - public void moveElementsDirectory(List elementsUuids, UUID targetDirectoryUuid, String userId) { - directoryService.moveElementsDirectory(elementsUuids, targetDirectoryUuid, userId); - List elementsAttributes = directoryService.getElementsInfos(elementsUuids, null, userId); - elementsAttributes.forEach(elementAttributes -> notifyElementMoved(elementAttributes, userId)); + public void moveElementsDirectory(List elementsUuids, UUID targetDirectoryUuid) { + directoryService.moveElementsDirectory(elementsUuids, targetDirectoryUuid); + List elementsAttributes = directoryService.getElementsInfos(elementsUuids, null); + elementsAttributes.forEach(this::notifyElementMoved); } - public String getUsersIdentities(List elementsUuids, String userId) { + public String getUsersIdentities(List elementsUuids) { // this returns names for owner and lastmodifiedby, // if we need it in the future, we can do separate requests. - List subs = directoryService.getElementsInfos(elementsUuids, null, userId).stream() + List subs = directoryService.getElementsInfos(elementsUuids, null).stream() .flatMap(x -> Stream.of(x.getOwner(), x.getLastModifiedBy())).distinct().filter(Objects::nonNull).toList(); return userIdentityService.getUsersIdentities(subs); } @@ -471,7 +474,7 @@ public String getUsersIdentities(List elementsUuids, String userId) { * Lists the elements using a shared element. There is one result per reference of the shared element. * Elements the user cannot read are omitted. */ - public List getReferencingElementInfos(UUID elementUuid, String userId) { + public List getReferencingElementInfos(UUID elementUuid) { // for now only STUDY_NODE references List referencedNodeUuids = directoryService.getElementInfos(elementUuid).getReferences().stream() .filter(reference -> reference.getReferenceType() == ReferenceAttributes.ReferenceType.STUDY_NODE) @@ -489,9 +492,9 @@ public List getReferencingElementInfos(UUID elementUuid return List.of(); } - Map studyByUuid = directoryService.getElementsInfos(studyUuids, null, userId, false) + Map studyByUuid = directoryService.getElementsInfos(studyUuids, null, false) .stream().collect(Collectors.toMap(ElementAttributes::getElementUuid, Function.identity())); - Map> parentDirectoryNamesByStudyUuid = getParentDirectoryNames(studyByUuid.keySet(), userId); + Map> parentDirectoryNamesByStudyUuid = getParentDirectoryNames(studyByUuid.keySet()); Map identityBySub = getIdentityBySub(studyByUuid.values()); return referencedNodeUuids.stream() @@ -521,8 +524,8 @@ private ReferencingElementInfos toReferencingElementInfos(NodeInfos nodeInfos, E .build(); } - private Map> getParentDirectoryNames(Collection elementUuids, String userId) { - return directoryService.getElementsPaths(List.copyOf(elementUuids), userId).entrySet().stream() + private Map> getParentDirectoryNames(Collection elementUuids) { + return directoryService.getElementsPaths(List.copyOf(elementUuids)).entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, entry -> { // a path ends with the element itself List elementPath = entry.getValue(); @@ -542,58 +545,56 @@ private Map getIdentityBySub(Collection rollback) { - executeWithRollback(() -> directoryService.createElement(elementAttributes, parentDirectoryUuid, userId), elementAttributes.getElementUuid(), userId, rollback); + private void createDirectoryElementOrDeleteElement(ElementAttributes elementAttributes, UUID parentDirectoryUuid, Consumer rollback) { + executeWithRollback(() -> directoryService.createElement(elementAttributes, parentDirectoryUuid), elementAttributes.getElementUuid(), rollback); } - private void createDirectoryElementWithNewNameOrDeleteElement(ElementAttributes elementAttributes, UUID parentDirectoryUuid, String userId, BiConsumer rollback) { - executeWithRollback(() -> directoryService.createElementWithNewName(elementAttributes, parentDirectoryUuid, userId, true), elementAttributes.getElementUuid(), userId, rollback); + private void createDirectoryElementWithNewNameOrDeleteElement(ElementAttributes elementAttributes, UUID parentDirectoryUuid, Consumer rollback) { + executeWithRollback(() -> directoryService.createElementWithNewName(elementAttributes, parentDirectoryUuid, true), elementAttributes.getElementUuid(), rollback); } - private void executeWithRollback(Runnable directoryAction, UUID elementId, String userId, BiConsumer rollback) { + private void executeWithRollback(Runnable directoryAction, UUID elementId, Consumer rollback) { try { directoryAction.run(); } catch (Exception directoryException) { try { - rollback.accept(elementId, userId); + rollback.accept(elementId); } catch (Exception rollbackException) { directoryException.addSuppressed(rollbackException); } @@ -601,13 +602,12 @@ private void executeWithRollback(Runnable directoryAction, UUID elementId, Strin } } - private void duplicateDirectoryElementOrDeleteElement(UUID elementToDuplicate, UUID elementDuplicated, UUID targetDirectoryId, - String userId, BiConsumer rollback) { - duplicateDirectoryElementOrDeleteElement(elementToDuplicate, elementDuplicated, targetDirectoryId, DirectoryElementStatus.CREATED, userId, rollback); + private void duplicateDirectoryElementOrDeleteElement(UUID elementToDuplicate, UUID elementDuplicated, UUID targetDirectoryId, Consumer rollback) { + duplicateDirectoryElementOrDeleteElement(elementToDuplicate, elementDuplicated, targetDirectoryId, DirectoryElementStatus.CREATED, rollback); } private void duplicateDirectoryElementOrDeleteElement(UUID elementToDuplicate, UUID elementDuplicated, UUID targetDirectoryId, - DirectoryElementStatus elementStatus, String userId, BiConsumer rollback) { - executeWithRollback(() -> directoryService.duplicateElement(elementToDuplicate, elementDuplicated, targetDirectoryId, elementStatus, userId), elementDuplicated, userId, rollback); + DirectoryElementStatus elementStatus, Consumer rollback) { + executeWithRollback(() -> directoryService.duplicateElement(elementToDuplicate, elementDuplicated, targetDirectoryId, elementStatus), elementDuplicated, rollback); } } diff --git a/src/main/java/org/gridsuite/explore/server/services/FilterService.java b/src/main/java/org/gridsuite/explore/server/services/FilterService.java index c370e200..61e024f2 100644 --- a/src/main/java/org/gridsuite/explore/server/services/FilterService.java +++ b/src/main/java/org/gridsuite/explore/server/services/FilterService.java @@ -8,9 +8,7 @@ import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; -import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; @@ -28,7 +26,6 @@ public class FilterService implements IDirectoryElementsService { private static final String FILTER_SERVER_API_VERSION = "v1"; private static final String DELIMITER = "/"; - private static final String HEADER_USER_ID = "userId"; private static final String FILTERS_ID_URL = "/filters/{id}"; private String filterServerBaseUri; @@ -45,32 +42,28 @@ public void setFilterServerBaseUri(String filterServerBaseUri) { } @Override - public void delete(UUID id, String userId) { + public void delete(UUID id) { String path = UriComponentsBuilder.fromPath(DELIMITER + FILTER_SERVER_API_VERSION + FILTERS_ID_URL) .buildAndExpand(id) .toUriString(); - restTemplate.exchange(filterServerBaseUri + path, HttpMethod.DELETE, new HttpEntity<>(getHeaders(userId)), - Void.class); + + restTemplate.exchange(filterServerBaseUri + path, HttpMethod.DELETE, HttpEntity.EMPTY, Void.class); } - public void insertFilter(String filter, UUID filterId, String userId) { + public void insertFilter(String filter, UUID filterId) { String path = UriComponentsBuilder.fromPath(DELIMITER + FILTER_SERVER_API_VERSION + "/filters?id={id}") .buildAndExpand(filterId) .toUriString(); - HttpHeaders headers = getHeaders(userId); - headers.setContentType(MediaType.APPLICATION_JSON); - HttpEntity httpEntity = new HttpEntity<>(filter, headers); - restTemplate.exchange(filterServerBaseUri + path, HttpMethod.POST, httpEntity, Void.class); + + restTemplate.exchange(filterServerBaseUri + path, HttpMethod.POST, new HttpEntity<>(filter), Void.class); } public UUID duplicateFilter(UUID filterId) { String path = UriComponentsBuilder.fromPath(DELIMITER + FILTER_SERVER_API_VERSION + "/filters/{uuid}/duplicate") .buildAndExpand(filterId) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - return restTemplate.exchange(filterServerBaseUri + path, HttpMethod.POST, new HttpEntity<>(headers), - UUID.class).getBody(); + + return restTemplate.exchange(filterServerBaseUri + path, HttpMethod.POST, HttpEntity.EMPTY, UUID.class).getBody(); } @Override @@ -80,18 +73,16 @@ public List> getMetadata(List filtersUuids) { .fromPath(DELIMITER + FILTER_SERVER_API_VERSION + "/filters/metadata" + "?ids=" + ids) .buildAndExpand() .toUriString(); - return restTemplate.exchange(filterServerBaseUri + path, HttpMethod.GET, null, - new ParameterizedTypeReference>>() { - }).getBody(); + return restTemplate.exchange(filterServerBaseUri + path, HttpMethod.GET, HttpEntity.EMPTY, + new ParameterizedTypeReference>>() { }).getBody(); } - public void updateFilter(UUID id, String filter, String userId) { - + public void updateFilter(UUID id, String filter) { String path = UriComponentsBuilder.fromPath(DELIMITER + FILTER_SERVER_API_VERSION + FILTERS_ID_URL) .buildAndExpand(id) .toUriString(); - restTemplate.exchange(filterServerBaseUri + path, HttpMethod.PUT, getHttpEntityWithUserHeaderAndJsonMediaType(userId, filter), Void.class); + restTemplate.exchange(filterServerBaseUri + path, HttpMethod.PUT, new HttpEntity<>(filter), Void.class); } @@ -99,19 +90,6 @@ public String getFilter(UUID id) { String path = UriComponentsBuilder.fromPath(DELIMITER + FILTER_SERVER_API_VERSION + FILTERS_ID_URL) .buildAndExpand(id) .toUriString(); - return restTemplate.exchange(filterServerBaseUri + path, HttpMethod.GET, null, String.class).getBody(); + return restTemplate.exchange(filterServerBaseUri + path, HttpMethod.GET, HttpEntity.EMPTY, String.class).getBody(); } - - private HttpHeaders getHeaders(String userId) { - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - return headers; - } - - private HttpEntity getHttpEntityWithUserHeaderAndJsonMediaType(String userId, String content) { - HttpHeaders headers = getHeaders(userId); - headers.setContentType(MediaType.APPLICATION_JSON); - return new HttpEntity<>(content, headers); - } - } diff --git a/src/main/java/org/gridsuite/explore/server/services/IDirectoryElementsService.java b/src/main/java/org/gridsuite/explore/server/services/IDirectoryElementsService.java index c2030369..42cc4ab0 100644 --- a/src/main/java/org/gridsuite/explore/server/services/IDirectoryElementsService.java +++ b/src/main/java/org/gridsuite/explore/server/services/IDirectoryElementsService.java @@ -22,14 +22,13 @@ */ interface IDirectoryElementsService { - String HEADER_USER_ID = "userId"; Logger LOGGER = LoggerFactory.getLogger(IDirectoryElementsService.class); default List> getMetadata(List uuidList) { return uuidList.stream().map(e -> Map.of("id", (Object) e)).collect(Collectors.toList()); } - void delete(UUID id, String userId); + void delete(UUID id); default List completeElementAttribute(List lstElementAttribute) { /* generating id -> elementAttribute map */ diff --git a/src/main/java/org/gridsuite/explore/server/services/MonitorService.java b/src/main/java/org/gridsuite/explore/server/services/MonitorService.java index b77613f6..fa551097 100644 --- a/src/main/java/org/gridsuite/explore/server/services/MonitorService.java +++ b/src/main/java/org/gridsuite/explore/server/services/MonitorService.java @@ -77,7 +77,7 @@ public UUID duplicateProcessConfig(UUID sourceProcessConfigUuid) { } @Override - public void delete(UUID id, String userId) { + public void delete(UUID id) { restClient.delete() .uri(PROCESS_CONFIGS_PATH + DELIMITER + "{id}", id) .retrieve() diff --git a/src/main/java/org/gridsuite/explore/server/services/NetworkConversionService.java b/src/main/java/org/gridsuite/explore/server/services/NetworkConversionService.java index ca96b1d6..72b916c1 100644 --- a/src/main/java/org/gridsuite/explore/server/services/NetworkConversionService.java +++ b/src/main/java/org/gridsuite/explore/server/services/NetworkConversionService.java @@ -10,9 +10,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; -import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @@ -25,7 +23,6 @@ public class NetworkConversionService { private static final String NETWORK_CONVERSION_API_VERSION = "v1"; private static final String DELIMITER = "/"; - private static final String HEADER_USER_ID = "userId"; @Setter private String networkConversionServerBaseUri; @@ -44,16 +41,13 @@ public String getCaseImportParameters(UUID caseUuid) { return restTemplate.exchange(networkConversionServerBaseUri + path, HttpMethod.GET, null, String.class).getBody(); } - public UUID convertCase(UUID caseUuid, String format, String fileName, String formatParameters, String userId) { + public UUID convertCase(UUID caseUuid, String format, String fileName, String formatParameters) { String path = UriComponentsBuilder.fromPath(DELIMITER + NETWORK_CONVERSION_API_VERSION + "/cases/{caseUuid}/convert/{format}") .queryParam("fileName", fileName) .buildAndExpand(caseUuid, format) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - headers.set(HEADER_USER_ID, userId); - return restTemplate.exchange(networkConversionServerBaseUri + path, HttpMethod.POST, new HttpEntity<>(formatParameters, headers), UUID.class).getBody(); + return restTemplate.exchange(networkConversionServerBaseUri + path, HttpMethod.POST, new HttpEntity<>(formatParameters), UUID.class).getBody(); } public ResponseEntity downloadFile(UUID exportUuid) { diff --git a/src/main/java/org/gridsuite/explore/server/services/NetworkModificationService.java b/src/main/java/org/gridsuite/explore/server/services/NetworkModificationService.java index 6eca9d13..ff22a1c3 100644 --- a/src/main/java/org/gridsuite/explore/server/services/NetworkModificationService.java +++ b/src/main/java/org/gridsuite/explore/server/services/NetworkModificationService.java @@ -28,7 +28,6 @@ public class NetworkModificationService implements IDirectoryElementsService { private static final String NETWORK_MODIFICATION_API_VERSION = "v1"; private static final String DELIMITER = "/"; - private static final String HEADER_USER_ID = "userId"; public static final String UUIDS = "uuids"; public static final String NAME = "name"; public static final String NETWORK_COMPOSITE_MODIFICATIONS_PATH = "network-composite-modifications"; @@ -91,14 +90,13 @@ public void updateCompositeModification(UUID compositeModificationId, String new } @Override - public void delete(UUID id, String userId) { + public void delete(UUID id) { String path = UriComponentsBuilder.fromPath(DELIMITER + NETWORK_MODIFICATION_API_VERSION + DELIMITER + NETWORK_MODIFICATIONS_PATH) .queryParam(UUIDS, List.of(id)) .buildAndExpand() .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - restTemplate.exchange(networkModificationServerBaseUri + path, HttpMethod.DELETE, new HttpEntity<>(headers), Void.class); + + restTemplate.exchange(networkModificationServerBaseUri + path, HttpMethod.DELETE, HttpEntity.EMPTY, Void.class); } @Override diff --git a/src/main/java/org/gridsuite/explore/server/services/NotificationService.java b/src/main/java/org/gridsuite/explore/server/services/NotificationService.java index eda656db..f0fe5077 100644 --- a/src/main/java/org/gridsuite/explore/server/services/NotificationService.java +++ b/src/main/java/org/gridsuite/explore/server/services/NotificationService.java @@ -8,6 +8,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import org.gridsuite.explore.server.UserAuthentication; import org.gridsuite.explore.server.dto.CaseAlertThresholdMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -15,6 +16,7 @@ import org.springframework.cloud.stream.function.StreamBridge; import org.springframework.messaging.Message; import org.springframework.messaging.support.MessageBuilder; +import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import java.time.Instant; import java.util.UUID; @@ -59,13 +61,15 @@ public NotificationService(StreamBridge updatePublisher, this.updatePublisher = updatePublisher; this.objectMapper = objectMapper; } + // TODO: faire un interceptor de messages envoyés ici ??? private void sendMessage(Message message, String bindingName) { MESSAGE_OUTPUT_LOGGER.debug(MESSAGE_LOG, message); updatePublisher.send(bindingName, message); } - public void emitUserMessage(String sub, String messageId, CaseAlertThresholdMessage message) { + public void emitUserMessage(String messageId, CaseAlertThresholdMessage message) { + String sub = ((UserAuthentication) SecurityContextHolder.getContext().getAuthentication()).getUserId(); try { sendMessage(MessageBuilder.withPayload(objectMapper.writeValueAsString(message)) .setHeader(HEADER_USER_MESSAGE, messageId) @@ -77,7 +81,8 @@ public void emitUserMessage(String sub, String messageId, CaseAlertThresholdMess } } - public void emitElementUpdated(UUID elementUuid, String modifiedBy) { + public void emitElementUpdated(UUID elementUuid) { + String modifiedBy = ((UserAuthentication) SecurityContextHolder.getContext().getAuthentication()).getUserId(); sendMessage(MessageBuilder.withPayload("") .setHeader(HEADER_ELEMENT_UUID, elementUuid) .setHeader(HEADER_MODIFIED_BY, modifiedBy) diff --git a/src/main/java/org/gridsuite/explore/server/services/ParametersService.java b/src/main/java/org/gridsuite/explore/server/services/ParametersService.java index c1ae3979..be1611d1 100644 --- a/src/main/java/org/gridsuite/explore/server/services/ParametersService.java +++ b/src/main/java/org/gridsuite/explore/server/services/ParametersService.java @@ -28,7 +28,6 @@ public class ParametersService implements IDirectoryElementsService { private static final String SERVER_API_VERSION = "v1"; private static final String DELIMITER = "/"; - private static final String HEADER_USER_ID = "userId"; private static final String COMPUTATION_PARAMETERS = "/parameters"; private static final String NETWORK_VISU_PARAMETERS = "/network-visualizations-params"; @@ -98,21 +97,19 @@ public void updateParameters(UUID parametersUuid, String parameters, ParametersT restTemplate.exchange(parametersServerBaseUri + path, HttpMethod.PUT, httpEntity, UUID.class); } - public UUID duplicateParameters(UUID sourceParametersUuid, ParametersType parametersType, String userId) { + public UUID duplicateParameters(UUID sourceParametersUuid, ParametersType parametersType) { String parametersServerBaseUri = remoteServicesProperties.getServiceUri(genericParametersServices.get(parametersType).getServerName()); Objects.requireNonNull(sourceParametersUuid); var path = UriComponentsBuilder .fromPath(DELIMITER + SERVER_API_VERSION + genericParametersServices.get(parametersType).getParametersBaseUrl() + DELIMITER + "{uuid}" + DELIMITER + "duplicate") .buildAndExpand(sourceParametersUuid) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - HttpEntity httpEntity = new HttpEntity<>(headers); - return restTemplate.exchange(parametersServerBaseUri + path, HttpMethod.POST, httpEntity, UUID.class).getBody(); + + return restTemplate.exchange(parametersServerBaseUri + path, HttpMethod.POST, HttpEntity.EMPTY, UUID.class).getBody(); } @Override - public void delete(UUID parametersUuid, String userId) { + public void delete(UUID parametersUuid) { ElementAttributes elementAttributes = directoryService.getElementInfos(parametersUuid); ParametersType parametersType = ParametersType.valueOf(elementAttributes.getType()); String parametersServerBaseUri = remoteServicesProperties.getServiceUri(genericParametersServices.get(parametersType).getServerName()); @@ -120,11 +117,7 @@ public void delete(UUID parametersUuid, String userId) { .buildAndExpand(parametersUuid) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - - restTemplate.exchange(parametersServerBaseUri + path, HttpMethod.DELETE, new HttpEntity<>(headers), - Void.class); + restTemplate.exchange(parametersServerBaseUri + path, HttpMethod.DELETE, HttpEntity.EMPTY, Void.class); } } diff --git a/src/main/java/org/gridsuite/explore/server/services/SingleLineDiagramService.java b/src/main/java/org/gridsuite/explore/server/services/SingleLineDiagramService.java index 7ef04705..f763ee43 100644 --- a/src/main/java/org/gridsuite/explore/server/services/SingleLineDiagramService.java +++ b/src/main/java/org/gridsuite/explore/server/services/SingleLineDiagramService.java @@ -27,7 +27,7 @@ public SingleLineDiagramService(RemoteServicesProperties remoteServicesPropertie } @Override - public void delete(UUID configUuid, String userId) { + public void delete(UUID configUuid) { Objects.requireNonNull(configUuid); var path = UriComponentsBuilder @@ -35,10 +35,7 @@ public void delete(UUID configUuid, String userId) { .buildAndExpand() .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - - restTemplate.exchange(singleLineDiagramServerBaseUri + path, HttpMethod.DELETE, new HttpEntity<>(headers), Void.class); + restTemplate.exchange(singleLineDiagramServerBaseUri + path, HttpMethod.DELETE, HttpEntity.EMPTY, Void.class); } public UUID createDiagramConfig(String diagramConfig) { diff --git a/src/main/java/org/gridsuite/explore/server/services/SpreadsheetConfigCollectionService.java b/src/main/java/org/gridsuite/explore/server/services/SpreadsheetConfigCollectionService.java index 67383d4d..2c50aa18 100644 --- a/src/main/java/org/gridsuite/explore/server/services/SpreadsheetConfigCollectionService.java +++ b/src/main/java/org/gridsuite/explore/server/services/SpreadsheetConfigCollectionService.java @@ -124,7 +124,7 @@ public void replaceAllSpreadsheetConfigsInCollection(UUID collectionId, List(headers), Void.class); + restTemplate.exchange(spreadsheetConfigServerBaseUri + path, HttpMethod.DELETE, HttpEntity.EMPTY, Void.class); } } diff --git a/src/main/java/org/gridsuite/explore/server/services/SpreadsheetConfigService.java b/src/main/java/org/gridsuite/explore/server/services/SpreadsheetConfigService.java index 6cd6c3bb..e163e2d6 100644 --- a/src/main/java/org/gridsuite/explore/server/services/SpreadsheetConfigService.java +++ b/src/main/java/org/gridsuite/explore/server/services/SpreadsheetConfigService.java @@ -94,18 +94,14 @@ public void updateSpreadsheetConfig(UUID configUuid, String config) { } @Override - public void delete(UUID configUuid, String userId) { + public void delete(UUID configUuid) { Objects.requireNonNull(configUuid); - var path = UriComponentsBuilder .fromPath(SPREADSHEET_CONFIG_SERVER_ROOT_PATH + DELIMITER + configUuid) .buildAndExpand() .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - - restTemplate.exchange(spreadsheetConfigServerBaseUri + path, HttpMethod.DELETE, new HttpEntity<>(headers), Void.class); + restTemplate.exchange(spreadsheetConfigServerBaseUri + path, HttpMethod.DELETE, HttpEntity.EMPTY, Void.class); } @Override diff --git a/src/main/java/org/gridsuite/explore/server/services/StudyService.java b/src/main/java/org/gridsuite/explore/server/services/StudyService.java index 9af8edef..1ae63708 100644 --- a/src/main/java/org/gridsuite/explore/server/services/StudyService.java +++ b/src/main/java/org/gridsuite/explore/server/services/StudyService.java @@ -38,7 +38,7 @@ public void setStudyServerBaseUri(String studyServerBaseUri) { this.studyServerBaseUri = studyServerBaseUri; } - public void insertStudyWithExistingCaseFile(UUID studyUuid, String userId, UUID caseUuid, String caseFormat, + public void insertStudyWithExistingCaseFile(UUID studyUuid, UUID caseUuid, String caseFormat, Map importParams, Boolean duplicateCase, String firstRootNetworkName) { var uriComponentsBuilder = UriComponentsBuilder.fromPath(DELIMITER + STUDY_SERVER_API_VERSION + "/studies/cases/{caseUuid}") @@ -50,30 +50,26 @@ public void insertStudyWithExistingCaseFile(UUID studyUuid, String userId, UUID uriComponentsBuilder.queryParam("firstRootNetworkName", firstRootNetworkName); } String path = uriComponentsBuilder.buildAndExpand(caseUuid).toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - headers.add(HEADER_USER_ID, userId); - HttpEntity> request = new HttpEntity<>( - importParams, headers); - restTemplate.exchange(studyServerBaseUri + path, HttpMethod.POST, request, Void.class); + + restTemplate.exchange(studyServerBaseUri + path, HttpMethod.POST, new HttpEntity<>(importParams), Void.class); } - public UUID duplicateStudy(UUID studyId, String userId) { + public UUID duplicateStudy(UUID studyId) { String path = UriComponentsBuilder.fromPath(DELIMITER + STUDY_SERVER_API_VERSION + "/studies/{uuid}/duplicate") .buildAndExpand(studyId) .toUriString(); - return restTemplate.exchange(studyServerBaseUri + path, HttpMethod.POST, new HttpEntity<>(getHeaders(userId)), - UUID.class).getBody(); + + return restTemplate.exchange(studyServerBaseUri + path, HttpMethod.POST, HttpEntity.EMPTY, UUID.class).getBody(); } @Override - public void delete(UUID studyUuid, String userId) { + public void delete(UUID studyUuid) { String path = UriComponentsBuilder.fromPath(DELIMITER + STUDY_SERVER_API_VERSION + "/studies/{studyUuid}") .buildAndExpand(studyUuid) .toUriString(); - restTemplate.exchange(studyServerBaseUri + path, HttpMethod.DELETE, new HttpEntity<>(getHeaders(userId)), - Void.class); + + restTemplate.exchange(studyServerBaseUri + path, HttpMethod.DELETE, HttpEntity.EMPTY, Void.class); } @Override @@ -98,21 +94,12 @@ public List getNodesInfos(List nodeUuids) { }).getBody(); } - private HttpHeaders getHeaders(String userId) { - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - headers.add(HEADER_USER_ID, userId); - return headers; - } - - public ResponseEntity notifyStudyUpdate(UUID studyUuid, String userId) { + public ResponseEntity notifyStudyUpdate(UUID studyUuid) { String path = UriComponentsBuilder.fromPath(DELIMITER + STUDY_SERVER_API_VERSION + "/studies/{studyUuid}/notification?type={metadata_updated}") .buildAndExpand(studyUuid, NOTIFICATION_TYPE_METADATA_UPDATED) .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.set(HEADER_USER_ID, userId); - return restTemplate.exchange(studyServerBaseUri + path, HttpMethod.POST, new HttpEntity<>(headers), Void.class); + return restTemplate.exchange(studyServerBaseUri + path, HttpMethod.POST, HttpEntity.EMPTY, Void.class); } } diff --git a/src/main/java/org/gridsuite/explore/server/services/SupervisionService.java b/src/main/java/org/gridsuite/explore/server/services/SupervisionService.java index fc9a5b73..e689ea6d 100644 --- a/src/main/java/org/gridsuite/explore/server/services/SupervisionService.java +++ b/src/main/java/org/gridsuite/explore/server/services/SupervisionService.java @@ -41,10 +41,10 @@ public SupervisionService(DirectoryService directoryService, RestTemplate restTe this.restTemplate = restTemplate; } - public void deleteElements(List uuids, String userId) { + public void deleteElements(List uuids) { uuids.forEach(id -> { try { - directoryService.deleteElement(id, userId); + directoryService.deleteElement(id); } catch (Exception e) { // if deletion fails (element does not exist, server is down...), the process keeps proceeding to at least delete references in directory-server // orphan elements will be deleted in a dedicated script diff --git a/src/main/java/org/gridsuite/explore/server/services/WorkspaceService.java b/src/main/java/org/gridsuite/explore/server/services/WorkspaceService.java index e0d8dce5..05c66c73 100644 --- a/src/main/java/org/gridsuite/explore/server/services/WorkspaceService.java +++ b/src/main/java/org/gridsuite/explore/server/services/WorkspaceService.java @@ -72,7 +72,7 @@ public void replaceWorkspace(UUID workspaceId, UUID sourceWorkspaceId) { } @Override - public void delete(UUID workspaceUuid, String userId) { + public void delete(UUID workspaceUuid) { Objects.requireNonNull(workspaceUuid); var path = UriComponentsBuilder @@ -80,9 +80,6 @@ public void delete(UUID workspaceUuid, String userId) { .buildAndExpand() .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.add(HEADER_USER_ID, userId); - - restTemplate.exchange(studyConfigServerBaseUri + path, HttpMethod.DELETE, new HttpEntity<>(headers), Void.class); + restTemplate.exchange(studyConfigServerBaseUri + path, HttpMethod.DELETE, HttpEntity.EMPTY, Void.class); } } diff --git a/src/test/java/org/gridsuite/explore/server/DynamicMappingTest.java b/src/test/java/org/gridsuite/explore/server/DynamicMappingTest.java index d43c47df..a14122a2 100644 --- a/src/test/java/org/gridsuite/explore/server/DynamicMappingTest.java +++ b/src/test/java/org/gridsuite/explore/server/DynamicMappingTest.java @@ -118,8 +118,8 @@ void createDynamicMapping() throws Exception { .content(DYNAMIC_MAPPING)) .andExpect(status().isOk()); - verify(directoryService, times(1)).checkPermission(List.of(DIRECTORY_ID), null, USER_ID, PermissionType.WRITE); - verify(directoryService, times(1)).createElementWithNewName(elementAttributesCaptor.capture(), eq(DIRECTORY_ID), eq(USER_ID), eq(true)); + verify(directoryService, times(1)).checkPermission(List.of(DIRECTORY_ID), null, PermissionType.WRITE); + verify(directoryService, times(1)).createElementWithNewName(elementAttributesCaptor.capture(), eq(DIRECTORY_ID), eq(true)); assertEquals(ID, elementAttributesCaptor.getValue().getElementUuid()); wireMockUtils.verifyPostRequest(stubId, URL_MAPPINGS, Map.of(), false); } @@ -139,8 +139,8 @@ void createDynamicMappingServerError() throws Exception { .content(DYNAMIC_MAPPING)) .andExpect(status().isInternalServerError()); - verify(directoryService, times(1)).checkPermission(List.of(DIRECTORY_ID), null, USER_ID, PermissionType.WRITE); - verify(directoryService, times(0)).createElementWithNewName(any(ElementAttributes.class), any(UUID.class), any(String.class), any(boolean.class)); + verify(directoryService, times(1)).checkPermission(List.of(DIRECTORY_ID), null, PermissionType.WRITE); + verify(directoryService, times(0)).createElementWithNewName(any(ElementAttributes.class), any(UUID.class), any(boolean.class)); wireMockUtils.verifyPostRequest(stubId, URL_MAPPINGS, Map.of(), false); } @@ -158,8 +158,8 @@ void updateDynamicMapping() throws Exception { .content(DYNAMIC_MAPPING)) .andExpect(status().isOk()); - verify(directoryService, times(1)).checkPermission(List.of(ID), null, USER_ID, PermissionType.WRITE); - verify(directoryService, times(1)).updateElement(eq(ID), elementAttributesCaptor.capture(), eq(USER_ID)); + verify(directoryService, times(1)).checkPermission(List.of(ID), null, PermissionType.WRITE); + verify(directoryService, times(1)).updateElement(eq(ID), elementAttributesCaptor.capture()); wireMockUtils.verifyPutRequest(stubId, URL_MAPPINGS + "/" + ID, Map.of(), false); } @@ -177,8 +177,8 @@ void updateDynamicMappingServerError() throws Exception { .content(DYNAMIC_MAPPING)) .andExpect(status().isInternalServerError()); - verify(directoryService, times(1)).checkPermission(List.of(ID), null, USER_ID, PermissionType.WRITE); - verify(directoryService, times(0)).updateElement(any(UUID.class), any(ElementAttributes.class), any(String.class)); + verify(directoryService, times(1)).checkPermission(List.of(ID), null, PermissionType.WRITE); + verify(directoryService, times(0)).updateElement(any(UUID.class), any(ElementAttributes.class)); wireMockUtils.verifyPutRequest(stubId, URL_MAPPINGS + "/" + ID, Map.of(), false); } @@ -195,9 +195,9 @@ void duplicateDynamicMapping() throws Exception { .header(QUERY_PARAM_USER_ID, USER_ID)) .andExpect(status().isOk()); - verify(directoryService, times(1)).checkPermission(List.of(ID), null, USER_ID, PermissionType.READ); - verify(directoryService, times(1)).checkPermission(List.of(DIRECTORY_ID), null, USER_ID, PermissionType.WRITE); - verify(directoryService, times(1)).duplicateElement(ID, NEW_ID, DIRECTORY_ID, CREATED, USER_ID); + verify(directoryService, times(1)).checkPermission(List.of(ID), null, PermissionType.READ); + verify(directoryService, times(1)).checkPermission(List.of(DIRECTORY_ID), null, PermissionType.WRITE); + verify(directoryService, times(1)).duplicateElement(ID, NEW_ID, DIRECTORY_ID, CREATED); wireMockUtils.verifyPostRequest(stubId, URL_MAPPINGS + "/" + ID + "/duplicate", Map.of(), false); } @@ -212,9 +212,9 @@ void duplicateDynamicMappingServerError() throws Exception { .header(QUERY_PARAM_USER_ID, USER_ID)) .andExpect(status().isInternalServerError()); - verify(directoryService, times(1)).checkPermission(List.of(ID), null, USER_ID, PermissionType.READ); - verify(directoryService, times(1)).checkPermission(List.of(DIRECTORY_ID), null, USER_ID, PermissionType.WRITE); - verify(directoryService, times(0)).duplicateElement(any(UUID.class), any(UUID.class), any(UUID.class), any(DirectoryElementStatus.class), any(String.class)); + verify(directoryService, times(1)).checkPermission(List.of(ID), null, PermissionType.READ); + verify(directoryService, times(1)).checkPermission(List.of(DIRECTORY_ID), null, PermissionType.WRITE); + verify(directoryService, times(0)).duplicateElement(any(UUID.class), any(UUID.class), any(UUID.class), any(DirectoryElementStatus.class)); wireMockUtils.verifyPostRequest(stubId, URL_MAPPINGS + "/" + ID + "/duplicate", Map.of(), false); } } diff --git a/src/test/java/org/gridsuite/explore/server/EndpointSecurityTest.java b/src/test/java/org/gridsuite/explore/server/EndpointSecurityTest.java new file mode 100644 index 00000000..5b647ef7 --- /dev/null +++ b/src/test/java/org/gridsuite/explore/server/EndpointSecurityTest.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2026, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +package org.gridsuite.explore.server; + +import org.gridsuite.explore.server.controller.SupervisionController; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.core.annotation.AnnotatedElementUtils; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Caroline Jeandat + */ +@SpringBootTest +class EndpointSecurityTest { + + @Autowired + @Qualifier("requestMappingHandlerMapping") + private RequestMappingHandlerMapping mappings; + + @Test + void allEndpointsMustHaveSecurityAnnotation() { + List unsecuredEndpoints = new ArrayList<>(); + + mappings.getHandlerMethods().forEach((info, handler) -> { + Method method = handler.getMethod(); + Class controller = handler.getBeanType(); + if (!controller.getPackageName().equals("org.gridsuite.explore.server.controller") + || controller == SupervisionController.class) { + return; + } + + if (!hasSecurityAnnotation(method, controller)) { + unsecuredEndpoints.add( + controller.getSimpleName() + "#" + method.getName() + ); + } + }); + + assertThat(unsecuredEndpoints).isEmpty(); + } + + private boolean hasSecurityAnnotation(Method method, Class controller) { + return AnnotatedElementUtils.hasAnnotation(method, PreAuthorize.class) + || AnnotatedElementUtils.hasAnnotation(controller, PreAuthorize.class); + } +} diff --git a/src/test/java/org/gridsuite/explore/server/ExploreServiceExceptionTest.java b/src/test/java/org/gridsuite/explore/server/ExploreServiceExceptionTest.java index 73ea7bd8..86ebfd2d 100644 --- a/src/test/java/org/gridsuite/explore/server/ExploreServiceExceptionTest.java +++ b/src/test/java/org/gridsuite/explore/server/ExploreServiceExceptionTest.java @@ -47,48 +47,47 @@ class ExploreServiceExceptionTest { void testDirectoryServerCrashesWithFilter() { // creation String creatingErrorMessage = "error when creating element from directory server"; - when(directoryService.createElement(any(), any(), any())).thenThrow(new RuntimeException(creatingErrorMessage)); - doNothing().when(filterService).insertFilter(any(), any(), any()); - doNothing().when(filterService).delete(any(), any()); + when(directoryService.createElement(any(), any())).thenThrow(new RuntimeException(creatingErrorMessage)); + doNothing().when(filterService).insertFilter(any(), any()); + doNothing().when(filterService).delete(any()); UUID parentDirectoryUuid = UUID.randomUUID(); String message = assertThrows(RuntimeException.class, () -> exploreService.createFilter("filterId", - "filterName", "description", parentDirectoryUuid, "userId")) + "filterName", "description", parentDirectoryUuid)) .getMessage(); ArgumentCaptor createdFilterId = ArgumentCaptor.forClass(UUID.class); - verify(filterService, times(1)).insertFilter(any(), createdFilterId.capture(), eq("userId")); - verify(filterService, times(1)).delete(createdFilterId.getValue(), "userId"); + verify(filterService, times(1)).insertFilter(any(), createdFilterId.capture()); + verify(filterService, times(1)).delete(createdFilterId.getValue()); assertEquals(creatingErrorMessage, message); reset(filterService); // duplication String duplicateErrorMessage = "error when duplicating element from directory server"; - when(directoryService.duplicateElement(any(), any(), any(), any(), any())).thenThrow(new RuntimeException(duplicateErrorMessage)); + when(directoryService.duplicateElement(any(), any(), any(), any())).thenThrow(new RuntimeException(duplicateErrorMessage)); UUID duplicatedFilterId = UUID.randomUUID(); when(filterService.duplicateFilter(any())).thenReturn(duplicatedFilterId); UUID sourceFilterId = UUID.randomUUID(); UUID targetDirectoryId = UUID.randomUUID(); - message = assertThrows(RuntimeException.class, () -> exploreService.duplicateFilter(sourceFilterId, targetDirectoryId, "userId")) + message = assertThrows(RuntimeException.class, () -> exploreService.duplicateFilter(sourceFilterId, targetDirectoryId)) .getMessage(); verify(filterService, times(1)).duplicateFilter(any()); - verify(filterService, times(1)).delete(eq(duplicatedFilterId), any()); + verify(filterService, times(1)).delete(eq(duplicatedFilterId)); assertEquals(duplicateErrorMessage, message); } @Test void testDirectoryServerCrashesWithNetworkModification() { String creatingErrorMessage = "error when creating element from directory server"; - when(directoryService.createElementWithNewName(any(), any(), any(), anyBoolean())).thenThrow(new RuntimeException(creatingErrorMessage)); + when(directoryService.createElementWithNewName(any(), any(), anyBoolean())).thenThrow(new RuntimeException(creatingErrorMessage)); UUID createdCompositeModificationId = UUID.randomUUID(); when(networkModificationService.createCompositeModification(anyList(), any())).thenReturn(createdCompositeModificationId); List modificationUuids = List.of(UUID.randomUUID()); UUID parentDirectoryUuid = UUID.randomUUID(); - String message = assertThrows(RuntimeException.class, () -> exploreService.createCompositeModification(modificationUuids, - "userId", "name", "description", parentDirectoryUuid)) + String message = assertThrows(RuntimeException.class, () -> exploreService.createCompositeModification(modificationUuids, "name", "description", parentDirectoryUuid)) .getMessage(); verify(networkModificationService, times(1)).createCompositeModification(any(), any()); - verify(networkModificationService, times(1)).delete(eq(createdCompositeModificationId), any()); + verify(networkModificationService, times(1)).delete(eq(createdCompositeModificationId)); assertEquals(creatingErrorMessage, message); } @@ -97,20 +96,20 @@ void testDirectoryServerCrashesAndDeleteElementToo() { // creation String creatingErrorMessage = "error when creating element from directory server"; String deletingErrorMessage = "error when deleting filter element"; - when(directoryService.createElement(any(), any(), any())).thenThrow(new RuntimeException(creatingErrorMessage)); - doNothing().when(filterService).insertFilter(any(), any(), any()); - doThrow(new RuntimeException(deletingErrorMessage)).when(filterService).delete(any(), any()); + when(directoryService.createElement(any(), any())).thenThrow(new RuntimeException(creatingErrorMessage)); + doNothing().when(filterService).insertFilter(any(), any()); + doThrow(new RuntimeException(deletingErrorMessage)).when(filterService).delete(any()); UUID parentDirectoryUuid = UUID.randomUUID(); Throwable throwable = assertThrows(RuntimeException.class, () -> exploreService.createFilter("filterId", - "filterName", "description", parentDirectoryUuid, "userId")); + "filterName", "description", parentDirectoryUuid)); String message = throwable.getMessage(); assertEquals(creatingErrorMessage, message); assertEquals(1, throwable.getSuppressed().length); assertEquals(deletingErrorMessage, throwable.getSuppressed()[0].getMessage()); ArgumentCaptor createdFilterId = ArgumentCaptor.forClass(UUID.class); - verify(filterService, times(1)).insertFilter(any(), createdFilterId.capture(), eq("userId")); - verify(filterService, times(1)).delete(createdFilterId.getValue(), "userId"); + verify(filterService, times(1)).insertFilter(any(), createdFilterId.capture()); + verify(filterService, times(1)).delete(createdFilterId.getValue()); reset(filterService); } } diff --git a/src/test/java/org/gridsuite/explore/server/ExploreTest.java b/src/test/java/org/gridsuite/explore/server/ExploreTest.java index 7c1c9abe..82b7bd80 100644 --- a/src/test/java/org/gridsuite/explore/server/ExploreTest.java +++ b/src/test/java/org/gridsuite/explore/server/ExploreTest.java @@ -199,6 +199,10 @@ class ExploreTest { @SuppressWarnings("checkstyle:MethodLength") @BeforeEach void setup(final MockWebServer server, TestInfo testInfo) throws Exception { + // Set up authentication + // UserAuthentication userAuthentication = new UserAuthentication(USER1, ""); + // SecurityContextHolder.getContext().setAuthentication(userAuthentication); + // Ask the server for its URL. You'll need this to make HTTP requests. HttpUrl baseHttpUrl = server.url(""); String baseUrl = baseHttpUrl.toString().substring(0, baseHttpUrl.toString().length() - 1); @@ -541,7 +545,7 @@ void teardown() { void testCreateStudyFromExistingCase() throws Exception { mockMvc.perform(post("/v1/explore/studies/" + STUDY1 + "/cases/" + CASE_UUID + "?description=desc&parentDirectoryUuid=" + PARENT_DIRECTORY_UUID) .param("duplicateCase", "false") - .header("userId", "userId") + .header("userId", USER1) .param("caseFormat", "XIIDM") .contentType(MediaType.APPLICATION_JSON) ).andExpect(status().isOk()); @@ -662,12 +666,14 @@ private void deleteElementInvalidType(UUID elementUUid) throws Exception { .andExpect(status().is2xxSuccessful()); } + // TODO: not admin user private void deleteElementNotAllowed(UUID elementUUid, int status) throws Exception { mockMvc.perform(delete("/v1/explore/elements/{elementUuid}", elementUUid).header("userId", NOT_ADMIN_USER)) .andExpect(status().is(status)); } + // TODO: not admin user private void deleteElementsNotAllowed(List elementUuids, UUID parentUuid, int status) throws Exception { var ids = elementUuids.stream().map(UUID::toString).collect(Collectors.joining(",")); mockMvc.perform(delete("/v1/explore/elements/{parentUuid}?ids=" + ids, parentUuid) @@ -999,6 +1005,7 @@ void testModifyCompositeModifications(final MockWebServer server) throws Excepti ).andExpect(status().isOk()); } + // TODO: not allowed user @Test void testGetDirectoryPermissions() throws Exception { MvcResult result = mockMvc.perform(get("/v1/explore/directories/{directoryUuid}/permissions", PARENT_DIRECTORY_UUID) @@ -1015,6 +1022,7 @@ void testGetDirectoryPermissions() throws Exception { .andExpect(status().isForbidden()); } + // TODO: not allowed user @Test void testSetDirectoryPermissions() throws Exception { List permissions = List.of( @@ -1062,6 +1070,7 @@ void testGetCompositeModificationContent() throws Exception { assertEquals(2, metadata.size()); } + // TODO: user with case limits exceeded @Test void testMaxCaseCreationExceeded() throws Exception { //test create a study with a user that already exceeded his cases limit @@ -1116,6 +1125,7 @@ void testMaxCaseCreationExceeded() throws Exception { assertTrue(result.getResponse().getContentAsString().contains(EXPLORE_MAX_ELEMENTS_EXCEEDED.value())); } + // TODO: user with case limits not exceeded @Test void testMaxCaseCreationNotExceeded() throws Exception { //test create a study with a user that hasn't already exceeded his cases limit @@ -1159,6 +1169,7 @@ void testMaxCaseCreationNotExceeded() throws Exception { .andExpect(status().isOk()); } + // TODO: not found user @Test void testMaxCaseCreationProfileNotSet() throws Exception { //test create a study with a user that has no profile to limit his case creation @@ -1202,6 +1213,7 @@ void testMaxCaseCreationProfileNotSet() throws Exception { .andExpect(status().isOk()); } + // TODO: user error @Test void testMaxCaseCreationWithRemoteException() throws Exception { //test create a study with a remote unexpected exception @@ -1244,6 +1256,7 @@ void testMaxCaseCreationWithRemoteException() throws Exception { .andExpect(status().isInternalServerError()); } + // TODO: user with case limits exceeded @Test void testCaseAlertThreshold(final MockWebServer server) throws Exception { //Perform a study creation while USER_WITH_CASE_LIMIT_NOT_EXCEEDED_2 has not yet reached the defined case alert threshold, no message sent to him @@ -1312,6 +1325,7 @@ void testMoveElementsDirectory() throws Exception { ).andExpect(status().isOk()); } + // TODO: not allowed user @Test void testUpdateElementNotOk() throws Exception { ElementAttributes elementAttributes = new ElementAttributes(); @@ -1439,6 +1453,7 @@ void testSearchElement(final MockWebServer server) throws Exception { assertTrue(requests.stream().anyMatch(r -> r.getPath().contains("/v1/elements/indexation-infos"))); } + // TODO: not admin user @Test void testHasRights(final MockWebServer server) throws Exception { // test read access allowed @@ -1506,14 +1521,14 @@ void testDeleteElementsFromDirectoryRevertsStatusWhenElementDeletionFails() thro .willReturn(WireMock.ok())); doThrow(new RuntimeException("simulated failure")) - .when(directoryService).deleteElement(FILTER_UUID, USER1); + .when(directoryService).deleteElement(FILTER_UUID); CountDownLatch reconciliationDone = new CountDownLatch(1); doAnswer(invocation -> { Object result = invocation.callRealMethod(); reconciliationDone.countDown(); return result; - }).when(directoryService).updateElementsStatus(List.of(FILTER_UUID), DirectoryElementStatus.CREATED, USER1); + }).when(directoryService).updateElementsStatus(List.of(FILTER_UUID), DirectoryElementStatus.CREATED); deleteElements(List.of(FILTER_UUID, PRIVATE_STUDY_UUID), PARENT_DIRECTORY_UUID); @@ -1524,6 +1539,7 @@ void testDeleteElementsFromDirectoryRevertsStatusWhenElementDeletionFails() thro wireMockServer.verify(1, WireMock.putRequestedFor(WireMock.urlMatching("/v1/elements\\?ids=" + FILTER_UUID + "&status=CREATED"))); } + // TODO: on doit verify les checkPermissions ??? ou le SecurityTest suffit ??? private void checkAuthorizationRequestDoneForDuplication(final MockWebServer server, UUID readElementUuid, UUID writeElementUuid) { // check that we called 2 times the directory server to checks authorization and 1 time the server to duplicate // check read authorization on the duplicated element and write authorization on the target directory diff --git a/src/test/java/org/gridsuite/explore/server/MonitorTest.java b/src/test/java/org/gridsuite/explore/server/MonitorTest.java index a0f78c68..48ffc73d 100644 --- a/src/test/java/org/gridsuite/explore/server/MonitorTest.java +++ b/src/test/java/org/gridsuite/explore/server/MonitorTest.java @@ -11,7 +11,6 @@ import com.github.tomakehurst.wiremock.client.WireMock; import org.gridsuite.explore.server.dto.DirectoryElementStatus; import org.gridsuite.explore.server.dto.ElementAttributes; -import org.gridsuite.explore.server.dto.PermissionType; import org.gridsuite.explore.server.services.DirectoryService; import org.gridsuite.explore.server.services.MonitorService; import org.gridsuite.explore.server.utils.WireMockUtils; @@ -29,7 +28,6 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; -import java.util.List; import java.util.Map; import java.util.UUID; import static com.github.tomakehurst.wiremock.client.WireMock.*; @@ -119,8 +117,7 @@ void createProcessConfig() throws Exception { UUID createdProcessConfigId = objectMapper.readValue(result, UUID.class); assertEquals(ID, createdProcessConfigId); - verify(directoryService, times(1)).checkPermission(List.of(DIRECTORY_ID), null, USER_ID, PermissionType.WRITE); - verify(directoryService, times(1)).createElementWithNewName(elementAttributesCaptor.capture(), eq(DIRECTORY_ID), eq(USER_ID), eq(true)); + verify(directoryService, times(1)).createElementWithNewName(elementAttributesCaptor.capture(), eq(DIRECTORY_ID), eq(true)); assertEquals(ID, elementAttributesCaptor.getValue().getElementUuid()); wireMockUtils.verifyPostRequest(stubId, URL_PROCESS_CONFIGS, Map.of(), false); } @@ -140,8 +137,7 @@ void createProcessConfigServerError() throws Exception { .content(PROCESS_CONFIG)) .andExpect(status().isInternalServerError()); - verify(directoryService, times(1)).checkPermission(List.of(DIRECTORY_ID), null, USER_ID, PermissionType.WRITE); - verify(directoryService, times(0)).createElementWithNewName(any(ElementAttributes.class), any(UUID.class), any(String.class), any(boolean.class)); + verify(directoryService, times(0)).createElementWithNewName(any(ElementAttributes.class), any(UUID.class), any(boolean.class)); wireMockUtils.verifyPostRequest(stubId, URL_PROCESS_CONFIGS, Map.of(), false); } @@ -159,8 +155,7 @@ void updateProcessConfig() throws Exception { .content(PROCESS_CONFIG)) .andExpect(status().isOk()); - verify(directoryService, times(1)).checkPermission(List.of(ID), null, USER_ID, PermissionType.WRITE); - verify(directoryService, times(1)).updateElement(eq(ID), elementAttributesCaptor.capture(), eq(USER_ID)); + verify(directoryService, times(1)).updateElement(eq(ID), elementAttributesCaptor.capture()); wireMockUtils.verifyPutRequest(stubId, URL_PROCESS_CONFIGS + "/" + ID, Map.of(), false); } @@ -178,8 +173,7 @@ void updateProcessConfigServerError() throws Exception { .content(PROCESS_CONFIG)) .andExpect(status().isInternalServerError()); - verify(directoryService, times(1)).checkPermission(List.of(ID), null, USER_ID, PermissionType.WRITE); - verify(directoryService, times(0)).updateElement(any(UUID.class), any(ElementAttributes.class), any(String.class)); + verify(directoryService, times(0)).updateElement(any(UUID.class), any(ElementAttributes.class)); wireMockUtils.verifyPutRequest(stubId, URL_PROCESS_CONFIGS + "/" + ID, Map.of(), false); } @@ -199,9 +193,7 @@ void duplicateProcessConfig() throws Exception { UUID duplicatedProcessConfigId = objectMapper.readValue(result, UUID.class); assertEquals(NEW_ID, duplicatedProcessConfigId); - verify(directoryService, times(1)).checkPermission(List.of(ID), null, USER_ID, PermissionType.READ); - verify(directoryService, times(1)).checkPermission(List.of(DIRECTORY_ID), null, USER_ID, PermissionType.WRITE); - verify(directoryService, times(1)).duplicateElement(ID, NEW_ID, DIRECTORY_ID, CREATED, USER_ID); + verify(directoryService, times(1)).duplicateElement(ID, NEW_ID, DIRECTORY_ID, CREATED); wireMockUtils.verifyPostRequest(stubId, URL_PROCESS_CONFIGS + "/" + ID + "/duplicate", Map.of(), false); } @@ -216,9 +208,7 @@ void duplicateProcessConfigServerError() throws Exception { .header(QUERY_PARAM_USER_ID, USER_ID)) .andExpect(status().isInternalServerError()); - verify(directoryService, times(1)).checkPermission(List.of(ID), null, USER_ID, PermissionType.READ); - verify(directoryService, times(1)).checkPermission(List.of(DIRECTORY_ID), null, USER_ID, PermissionType.WRITE); - verify(directoryService, times(0)).duplicateElement(any(UUID.class), any(UUID.class), any(UUID.class), any(DirectoryElementStatus.class), any(String.class)); + verify(directoryService, times(0)).duplicateElement(any(UUID.class), any(UUID.class), any(UUID.class), any(DirectoryElementStatus.class)); wireMockUtils.verifyPostRequest(stubId, URL_PROCESS_CONFIGS + "/" + ID + "/duplicate", Map.of(), false); } } diff --git a/src/test/java/org/gridsuite/explore/server/SingleLineDiagramTest.java b/src/test/java/org/gridsuite/explore/server/SingleLineDiagramTest.java index f9988873..755dccb4 100644 --- a/src/test/java/org/gridsuite/explore/server/SingleLineDiagramTest.java +++ b/src/test/java/org/gridsuite/explore/server/SingleLineDiagramTest.java @@ -99,8 +99,8 @@ void testCreateDiagramConfig() throws Exception { .andExpect(status().isOk()) .andReturn(); - verify(directoryService, times(1)).createElement(elementAttributesCaptor.capture(), eq(PARENT_DIRECTORY_UUID), eq(USER1)); - verify(directoryService, times(1)).checkPermission(List.of(PARENT_DIRECTORY_UUID), null, USER1, PermissionType.WRITE); + verify(directoryService, times(1)).createElement(elementAttributesCaptor.capture(), eq(PARENT_DIRECTORY_UUID)); + verify(directoryService, times(1)).checkPermission(List.of(PARENT_DIRECTORY_UUID), null, PermissionType.WRITE); assertEquals(NAD_CONFIG_UUID, elementAttributesCaptor.getValue().getElementUuid()); wireMockUtils.verifyPostRequest(stubId, USER_SINGLE_LINE_DIAGRAM_SERVER_BASE_URL, Map.of(), false); } @@ -123,8 +123,8 @@ void testUpdateDiagramConfig() throws Exception { .andExpect(status().isNoContent()) .andReturn(); - verify(directoryService, times(1)).updateElement(eq(NAD_CONFIG_UUID), elementAttributesCaptor.capture(), eq(USER1)); - verify(directoryService, times(1)).checkPermission(List.of(NAD_CONFIG_UUID), null, USER1, PermissionType.WRITE); + verify(directoryService, times(1)).updateElement(eq(NAD_CONFIG_UUID), elementAttributesCaptor.capture()); + verify(directoryService, times(1)).checkPermission(List.of(NAD_CONFIG_UUID), null, PermissionType.WRITE); wireMockUtils.verifyPutRequest(stubId, USER_SINGLE_LINE_DIAGRAM_SERVER_BASE_URL + "/" + NAD_CONFIG_UUID, Map.of(), false); } @@ -142,9 +142,9 @@ void testDuplicateDiagramConfig() throws Exception { .andExpect(status().isOk()) .andReturn(); - verify(directoryService, times(1)).duplicateElement(NAD_CONFIG_UUID, DUPLICATE_NAD_CONFIG_UUID, PARENT_DIRECTORY_UUID, CREATED, USER1); - verify(directoryService, times(1)).checkPermission(List.of(PARENT_DIRECTORY_UUID), null, USER1, PermissionType.WRITE); - verify(directoryService, times(1)).checkPermission(List.of(NAD_CONFIG_UUID), null, USER1, PermissionType.READ); + verify(directoryService, times(1)).duplicateElement(NAD_CONFIG_UUID, DUPLICATE_NAD_CONFIG_UUID, PARENT_DIRECTORY_UUID, CREATED); + verify(directoryService, times(1)).checkPermission(List.of(PARENT_DIRECTORY_UUID), null, PermissionType.WRITE); + verify(directoryService, times(1)).checkPermission(List.of(NAD_CONFIG_UUID), null, PermissionType.READ); wireMockUtils.verifyPostRequest(stubId, USER_SINGLE_LINE_DIAGRAM_SERVER_BASE_URL + "/" + NAD_CONFIG_UUID + "/duplicate", Map.of(), false); } } diff --git a/src/test/java/org/gridsuite/explore/server/SupervisionTest.java b/src/test/java/org/gridsuite/explore/server/SupervisionTest.java index 3dd75223..2f27b277 100644 --- a/src/test/java/org/gridsuite/explore/server/SupervisionTest.java +++ b/src/test/java/org/gridsuite/explore/server/SupervisionTest.java @@ -37,10 +37,10 @@ class SupervisionTest { @Test void testDeleteElements() { List uuidsToDelete = List.of(filter.getElementUuid(), study.getElementUuid()); - supervisionService.deleteElements(uuidsToDelete, "userId"); + supervisionService.deleteElements(uuidsToDelete); // deletions of both elements with foreach towards respective microservice - verify(directoryService, times(1)).deleteElement(filter.getElementUuid(), "userId"); - verify(directoryService, times(1)).deleteElement(study.getElementUuid(), "userId"); + verify(directoryService, times(1)).deleteElement(filter.getElementUuid()); + verify(directoryService, times(1)).deleteElement(study.getElementUuid()); // deletions of both elements in directory server verify(restTemplate, times(1)).exchange(matches(".*/supervision/.*"), eq(HttpMethod.DELETE), any(HttpEntity.class), eq(Void.class)); } @@ -50,12 +50,12 @@ void testDeleteElementsWithErrors() { List uuidsToDelete = List.of(filter.getElementUuid(), study.getElementUuid()); // one deletion will fail, this test checks deletions does not stop even when one of them is throwing an exception - doThrow(new RuntimeException("An error occured when deleting filter")).when(directoryService).deleteElement(filter.getElementUuid(), "userId"); + doThrow(new RuntimeException("An error occured when deleting filter")).when(directoryService).deleteElement(filter.getElementUuid()); - supervisionService.deleteElements(uuidsToDelete, "userId"); + supervisionService.deleteElements(uuidsToDelete); // deletions of both elements with foreach towards respective microservice - verify(directoryService, times(1)).deleteElement(filter.getElementUuid(), "userId"); - verify(directoryService, times(1)).deleteElement(study.getElementUuid(), "userId"); + verify(directoryService, times(1)).deleteElement(filter.getElementUuid()); + verify(directoryService, times(1)).deleteElement(study.getElementUuid()); // deletions of both elements in directory server verify(restTemplate, times(1)).exchange(matches(".*/supervision/.*"), eq(HttpMethod.DELETE), any(HttpEntity.class), eq(Void.class)); } diff --git a/src/test/java/org/gridsuite/explore/server/UserIdentityTest.java b/src/test/java/org/gridsuite/explore/server/UserIdentityTest.java index e2b7805b..2fa741eb 100644 --- a/src/test/java/org/gridsuite/explore/server/UserIdentityTest.java +++ b/src/test/java/org/gridsuite/explore/server/UserIdentityTest.java @@ -76,7 +76,7 @@ public void setUp() { wireMockServer.start(); userIdentityService.setUserIdentityServerBaseUri(wireMockServer.baseUrl()); - when(directoryService.getElementsInfos(List.of(ELEMENT_UUID), null, SUB)).thenReturn(List.of(new ElementAttributes( + when(directoryService.getElementsInfos(List.of(ELEMENT_UUID), null)).thenReturn(List.of(new ElementAttributes( ELEMENT_UUID, ELEMENT_NAME, "SOME TYPE", @@ -84,7 +84,7 @@ public void setUp() { 0L, null ))); - when(directoryService.getElementsInfos(List.of(ELEMENT_UNKNOWN_SUB_UUID), null, UNKNOWN_SUB)).thenReturn(List.of(new ElementAttributes( + when(directoryService.getElementsInfos(List.of(ELEMENT_UNKNOWN_SUB_UUID), null)).thenReturn(List.of(new ElementAttributes( ELEMENT_UNKNOWN_SUB_UUID, ELEMENT_UNKNOWN_SUB_NAME, "SOME TYPE", @@ -92,7 +92,7 @@ public void setUp() { 0L, null ))); - when(directoryService.getElementsInfos(List.of(ELEMENT_EXCEPTION_SUB_UUID), null, EXCEPTION_SUB)).thenReturn(List.of(new ElementAttributes( + when(directoryService.getElementsInfos(List.of(ELEMENT_EXCEPTION_SUB_UUID), null)).thenReturn(List.of(new ElementAttributes( ELEMENT_EXCEPTION_SUB_UUID, "exception", "SOME TYPE", @@ -100,7 +100,7 @@ public void setUp() { 0L, null ))); - when(directoryService.getElementsInfos(List.of(ELEMENT_NOT_FOUND_UUID), null, UNKNOWN_SUB)) + when(directoryService.getElementsInfos(List.of(ELEMENT_NOT_FOUND_UUID), null)) .thenThrow(new RuntimeException(String.format("Element '%s' not found", ELEMENT_NOT_FOUND_UUID))); } @@ -134,7 +134,7 @@ void testGetSubIdentity() throws Exception { assertTrue(usersInfos.contains("userFirstName")); assertTrue(usersInfos.contains("userLastName")); - verify(directoryService, times(1)).getElementsInfos(List.of(ELEMENT_UUID), null, SUB); + verify(directoryService, times(1)).getElementsInfos(List.of(ELEMENT_UUID), null); wireMockUtils.verifyGetRequest(stubId, USER_IDENTITY_SERVER_BASE_URL + "/identities", handleQueryParams(List.of(SUB)), false); } @@ -145,7 +145,7 @@ void testGetSubIdentityNotFoundElement() throws Exception { .header("userId", UNKNOWN_SUB)) .andExpect(status().isInternalServerError()); - verify(directoryService, times(1)).getElementsInfos(List.of(ELEMENT_NOT_FOUND_UUID), null, UNKNOWN_SUB); + verify(directoryService, times(1)).getElementsInfos(List.of(ELEMENT_NOT_FOUND_UUID), null); } @Test @@ -159,7 +159,9 @@ void testGetSubIdentityException() throws Exception { .andExpect(status().isInternalServerError()) .andExpect(result -> assertInstanceOf(HttpServerErrorException.class, result.getResolvedException())); - verify(directoryService, times(1)).getElementsInfos(List.of(ELEMENT_EXCEPTION_SUB_UUID), null, EXCEPTION_SUB); + // TODO: verify here + + verify(directoryService, times(1)).getElementsInfos(List.of(ELEMENT_EXCEPTION_SUB_UUID), null); wireMockUtils.verifyGetRequest(stubId, USER_IDENTITY_SERVER_BASE_URL + "/identities", handleQueryParams(List.of(EXCEPTION_SUB)), false); } diff --git a/src/test/java/org/gridsuite/explore/server/WorkspaceTest.java b/src/test/java/org/gridsuite/explore/server/WorkspaceTest.java index 62de7a9d..0984d0e8 100644 --- a/src/test/java/org/gridsuite/explore/server/WorkspaceTest.java +++ b/src/test/java/org/gridsuite/explore/server/WorkspaceTest.java @@ -106,8 +106,8 @@ void testCreateWorkspace() throws Exception { .header("userId", USER_ID)) .andExpect(status().isCreated()); - verify(directoryService, times(1)).createElement(elementAttributesCaptor.capture(), eq(PARENT_DIRECTORY_UUID), eq(USER_ID)); - verify(directoryService, times(1)).checkPermission(List.of(PARENT_DIRECTORY_UUID), null, USER_ID, PermissionType.WRITE); + verify(directoryService, times(1)).createElement(elementAttributesCaptor.capture(), eq(PARENT_DIRECTORY_UUID)); + verify(directoryService, times(1)).checkPermission(List.of(PARENT_DIRECTORY_UUID), null, PermissionType.WRITE); assertEquals(WORKSPACE_UUID, elementAttributesCaptor.getValue().getElementUuid()); } @@ -120,8 +120,8 @@ void testReplaceWorkspace() throws Exception { .header("userId", USER_ID)) .andExpect(status().isNoContent()); - verify(directoryService, times(1)).updateElement(eq(WORKSPACE_UUID), elementAttributesCaptor.capture(), eq(USER_ID)); - verify(directoryService, times(1)).checkPermission(List.of(WORKSPACE_UUID), null, USER_ID, PermissionType.WRITE); + verify(directoryService, times(1)).updateElement(eq(WORKSPACE_UUID), elementAttributesCaptor.capture()); + verify(directoryService, times(1)).checkPermission(List.of(WORKSPACE_UUID), null, PermissionType.WRITE); } @Test @@ -131,9 +131,9 @@ void testDuplicateWorkspace() throws Exception { .header("userId", USER_ID)) .andExpect(status().isCreated()); - verify(directoryService, times(1)).duplicateElement(SOURCE_WORKSPACE_UUID, WORKSPACE_UUID, PARENT_DIRECTORY_UUID, CREATED, USER_ID); - verify(directoryService, times(1)).checkPermission(List.of(PARENT_DIRECTORY_UUID), null, USER_ID, PermissionType.WRITE); - verify(directoryService, times(1)).checkPermission(List.of(SOURCE_WORKSPACE_UUID), null, USER_ID, PermissionType.READ); + verify(directoryService, times(1)).duplicateElement(SOURCE_WORKSPACE_UUID, WORKSPACE_UUID, PARENT_DIRECTORY_UUID, CREATED); + verify(directoryService, times(1)).checkPermission(List.of(PARENT_DIRECTORY_UUID), null, PermissionType.WRITE); + verify(directoryService, times(1)).checkPermission(List.of(SOURCE_WORKSPACE_UUID), null, PermissionType.READ); } @Test @@ -142,7 +142,7 @@ void testDuplicateWorkspaceInSameDirectory() throws Exception { .header("userId", USER_ID)) .andExpect(status().isCreated()); - verify(directoryService, times(1)).duplicateElement(SOURCE_WORKSPACE_UUID, WORKSPACE_UUID, null, CREATED, USER_ID); + verify(directoryService, times(1)).duplicateElement(SOURCE_WORKSPACE_UUID, WORKSPACE_UUID, null, CREATED); } @Test diff --git a/src/test/java/org/gridsuite/explore/server/RestTemplateConfigTest.java b/src/test/java/org/gridsuite/explore/server/config/RestTemplateConfigTest.java similarity index 79% rename from src/test/java/org/gridsuite/explore/server/RestTemplateConfigTest.java rename to src/test/java/org/gridsuite/explore/server/config/RestTemplateConfigTest.java index 4c3885b9..7ee140fe 100644 --- a/src/test/java/org/gridsuite/explore/server/RestTemplateConfigTest.java +++ b/src/test/java/org/gridsuite/explore/server/config/RestTemplateConfigTest.java @@ -4,8 +4,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -package org.gridsuite.explore.server; +package org.gridsuite.explore.server.config; +import org.gridsuite.explore.server.UserAuthentication; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -14,14 +15,13 @@ import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureWebClient; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; -import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.client.response.MockRestResponseCreators; import org.springframework.web.client.RestTemplate; import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; @@ -43,7 +43,9 @@ class RestTemplateConfigTest { private MockRestServiceServer mockServer; private static final String ROLES_HEADER = "roles"; + private static final String USER_ID_HEADER = "userId"; private static final String TEST_ROLES = "ADMIN|USER"; + private static final String TEST_USER_ID = "user"; private static final String TEST_ENDPOINT = "http://test-service/api/resource"; @BeforeEach @@ -54,20 +56,19 @@ void setUp() { @AfterEach void tearDown() { // Clean up the RequestContextHolder after each test - RequestContextHolder.resetRequestAttributes(); + RequestContextHolder.resetRequestAttributes(); // ça sert à quoi ?? + SecurityContextHolder.clearContext(); } @Test - void testRoleHeaderIsPropagated() { - // Setup mock incoming request with roles header - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addHeader(ROLES_HEADER, TEST_ROLES); - RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); + void testRoleAndUserIdHeaderIsPropagated() { + setAuthentication(TEST_USER_ID, TEST_ROLES); // Setup mock response for the outgoing request mockServer.expect(requestTo(TEST_ENDPOINT)) .andExpect(method(HttpMethod.GET)) - .andExpect(header(ROLES_HEADER, TEST_ROLES)) // This verifies our interceptor works + .andExpect(header(ROLES_HEADER, TEST_ROLES)) + .andExpect(header(USER_ID_HEADER, TEST_USER_ID)) // This verifies our interceptor works .andRespond(MockRestResponseCreators.withSuccess("{\"result\":\"success\"}", MediaType.APPLICATION_JSON)); // Execute request through our RestTemplate @@ -78,12 +79,8 @@ void testRoleHeaderIsPropagated() { } @Test - void testNoRoleHeaderPropagationWhenNotPresent() { - // Setup mock incoming request WITHOUT roles header - MockHttpServletRequest request = new MockHttpServletRequest(); - RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); - - // Setup mock response - here we expect NOT to see the roles header + void testNoRoleAndUserIdHeaderPropagationWhenNotPresent() { + // Setup mock response - here we expect NOT to see the roles and userId header mockServer.expect(requestTo(TEST_ENDPOINT)) .andExpect(method(HttpMethod.GET)) .andExpect(req -> { @@ -91,6 +88,9 @@ void testNoRoleHeaderPropagationWhenNotPresent() { if (req.getHeaders().containsKey(ROLES_HEADER)) { throw new AssertionError("Roles header should not be present"); } + if (req.getHeaders().containsKey(USER_ID_HEADER)) { + throw new AssertionError("UserId header should not be present"); + } }) .andRespond(MockRestResponseCreators.withSuccess("{\"result\":\"success\"}", MediaType.APPLICATION_JSON)); @@ -103,12 +103,9 @@ void testNoRoleHeaderPropagationWhenNotPresent() { @Test void testEmptyRoleHeaderNotPropagated() { - // Setup mock incoming request with EMPTY roles header - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addHeader(ROLES_HEADER, ""); // Empty value - RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); + setAuthentication(TEST_USER_ID, ""); - // Setup mock - we don't expect the header to be forwarded if empty + // Setup mock - we don't expect the roles header to be forwarded if empty mockServer.expect(requestTo(TEST_ENDPOINT)) .andExpect(method(HttpMethod.GET)) .andExpect(req -> { @@ -125,6 +122,7 @@ void testEmptyRoleHeaderNotPropagated() { mockServer.verify(); } + // TODO: delete @Test void testContextHolderIsNull() { // Make sure the context holder is null @@ -146,4 +144,9 @@ void testContextHolderIsNull() { // Verify mockServer.verify(); } + + void setAuthentication(String userId, String roles) { + UserAuthentication userAuthentication = new UserAuthentication(userId, roles); + SecurityContextHolder.getContext().setAuthentication(userAuthentication); + } } diff --git a/src/test/java/org/gridsuite/explore/server/controllers/NetworkConversionControllerTest.java b/src/test/java/org/gridsuite/explore/server/controllers/NetworkConversionControllerTest.java index 4fce1a43..25a25f91 100644 --- a/src/test/java/org/gridsuite/explore/server/controllers/NetworkConversionControllerTest.java +++ b/src/test/java/org/gridsuite/explore/server/controllers/NetworkConversionControllerTest.java @@ -47,11 +47,11 @@ void getCaseImportParametersForwardsCaseUuid() { @Test void convertCaseForwardsArguments() { UUID response = EXPORT_UUID; - when(networkConversionService.convertCase(CASE_UUID, "CGMES", "network.zip", "{}", "userId")).thenReturn(response); + when(networkConversionService.convertCase(CASE_UUID, "CGMES", "network.zip", "{}")).thenReturn(response); - assertSame(response, controller.convertCase(CASE_UUID, "CGMES", "network.zip", "{}", "userId").getBody()); + assertSame(response, controller.convertCase(CASE_UUID, "CGMES", "network.zip", "{}").getBody()); - verify(networkConversionService).convertCase(CASE_UUID, "CGMES", "network.zip", "{}", "userId"); + verify(networkConversionService).convertCase(CASE_UUID, "CGMES", "network.zip", "{}"); } @Test diff --git a/src/test/java/org/gridsuite/explore/server/services/DirectoryServiceTest.java b/src/test/java/org/gridsuite/explore/server/services/DirectoryServiceTest.java index 984486ca..7f5d3b00 100644 --- a/src/test/java/org/gridsuite/explore/server/services/DirectoryServiceTest.java +++ b/src/test/java/org/gridsuite/explore/server/services/DirectoryServiceTest.java @@ -41,11 +41,10 @@ class DirectoryServiceTest { void testSearchElementsWithSpecialCharacters() { String userInput = "a+éè{}\\`b"; String directoryUuid = UUID.randomUUID().toString(); - String userId = "testUser"; when(restTemplate.exchange(any(URI.class), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class))) .thenReturn(responseEntity); - directoryService.searchElements(userInput, directoryUuid, userId); + directoryService.searchElements(userInput, directoryUuid); ArgumentCaptor uriCaptor = ArgumentCaptor.forClass(URI.class); verify(restTemplate).exchange(uriCaptor.capture(), any(), any(), any(Class.class)); diff --git a/src/test/java/org/gridsuite/explore/server/services/NetworkConversionServiceTest.java b/src/test/java/org/gridsuite/explore/server/services/NetworkConversionServiceTest.java index 297386b7..a833162c 100644 --- a/src/test/java/org/gridsuite/explore/server/services/NetworkConversionServiceTest.java +++ b/src/test/java/org/gridsuite/explore/server/services/NetworkConversionServiceTest.java @@ -66,7 +66,7 @@ void convertCaseForwardsPathQueryHeaderAndBody() { .andExpect(content().string(JSON)) .andRespond(withSuccess("\"" + CONVERSION_UUID + "\"", MediaType.APPLICATION_JSON)); - UUID response = networkConversionService.convertCase(CASE_UUID, "CGMES", "network.zip", JSON, "userId"); + UUID response = networkConversionService.convertCase(CASE_UUID, "CGMES", "network.zip", JSON); assertEquals(CONVERSION_UUID, response); server.verify();