diff --git a/src/main/java/eu/hbp/mip/configurations/GalaxyAuthentication.java b/src/main/java/eu/hbp/mip/configurations/GalaxyAuthentication.java index 41888d3ea276138e425e790cde46867f8ce3e31b..e8a5df4bc7311cc86683c546f27de0208a850d20 100644 --- a/src/main/java/eu/hbp/mip/configurations/GalaxyAuthentication.java +++ b/src/main/java/eu/hbp/mip/configurations/GalaxyAuthentication.java @@ -3,8 +3,7 @@ package eu.hbp.mip.configurations; import com.google.gson.Gson; import com.google.gson.JsonObject; import eu.hbp.mip.services.ActiveUserService; -import eu.hbp.mip.utils.Logging; -import org.springframework.beans.factory.annotation.Autowired; +import eu.hbp.mip.utils.Logger; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -19,8 +18,7 @@ import java.util.Base64; @RestController public class GalaxyAuthentication { - @Autowired - private ActiveUserService activeUserService; + private final ActiveUserService activeUserService; @Value("#{'${services.galaxy.galaxyUsername:admin}'}") private String galaxyUsername; @@ -31,20 +29,25 @@ public class GalaxyAuthentication { @Value("#{'${services.galaxy.galaxpathoyContext:nativeGalaxy}'}") private String galaxyContext; + public GalaxyAuthentication(ActiveUserService activeUserService) { + this.activeUserService = activeUserService; + } + /** * Get Galaxy Reverse Proxy basic access token. * * @return Return a @{@link ResponseEntity} with the token. */ @RequestMapping(path = "/galaxy", method = RequestMethod.GET, produces = "application/json") - @PreAuthorize("hasRole('Data Manager')") + @PreAuthorize("hasRole('WORKFLOW_ADMIN')") @ResponseStatus(value = HttpStatus.OK) public ResponseEntity getGalaxyConfiguration() { + Logger logger = new Logger(activeUserService.getActiveUser().getUsername(), "(GET) /user/galaxy"); String stringEncoded = Base64.getEncoder().encodeToString((galaxyUsername + ":" + galaxyPassword).getBytes()); JsonObject object = new JsonObject(); object.addProperty("authorization", stringEncoded); object.addProperty("context", galaxyContext); - Logging.LogUserAction(activeUserService.getActiveUser().getUsername(), "(GET) /user/galaxy", "Successfully Loaded galaxy information."); + logger.LogUserAction("Successfully Loaded galaxy information."); return ResponseEntity.ok(new Gson().toJson(object)); } diff --git a/src/main/java/eu/hbp/mip/configurations/SecurityConfiguration.java b/src/main/java/eu/hbp/mip/configurations/SecurityConfiguration.java index ea5cf7860977aa39746d273c08c7cae6224063de..2b2e549d46dc7f8a71fc981f6c8d000f606630c9 100644 --- a/src/main/java/eu/hbp/mip/configurations/SecurityConfiguration.java +++ b/src/main/java/eu/hbp/mip/configurations/SecurityConfiguration.java @@ -22,7 +22,6 @@ import org.springframework.security.web.csrf.CsrfTokenRepository; import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.filter.CorsFilter; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.util.WebUtils; @@ -43,6 +42,10 @@ public class SecurityConfiguration extends KeycloakWebSecurityConfigurerAdapter @Value("#{'${authentication.enabled}'}") private boolean authenticationEnabled; + public SecurityConfiguration(HttpServletRequest request) { + this.request = request; + } + @Override protected void configure(HttpSecurity http) throws Exception { super.configure(http); @@ -54,7 +57,7 @@ public class SecurityConfiguration extends KeycloakWebSecurityConfigurerAdapter "/v2/api-docs", "/swagger-ui/**", "/swagger-resources/**" // Swagger URLs ).permitAll() .antMatchers("/galaxy*", "/galaxy/*").hasRole("DATA MANAGER") - .anyRequest().hasRole("RESEARCHER") + .antMatchers("/**").authenticated() .and().csrf().ignoringAntMatchers("/logout").csrfTokenRepository(csrfTokenRepository()) .and().addFilterAfter(csrfHeaderFilter(), CsrfFilter.class); } else { @@ -92,8 +95,7 @@ public class SecurityConfiguration extends KeycloakWebSecurityConfigurerAdapter return repository; } - @Autowired - private HttpServletRequest request; + private final HttpServletRequest request; @GetMapping(value = "/logout") public String logout() throws ServletException { diff --git a/src/main/java/eu/hbp/mip/controllers/ActiveUserAPI.java b/src/main/java/eu/hbp/mip/controllers/ActiveUserAPI.java index 7e5209b75b5ec2e112dd56c6a4ee8ef778221e39..aca62c4b6c2771e45ffa60a9cbc09040b1a3248a 100644 --- a/src/main/java/eu/hbp/mip/controllers/ActiveUserAPI.java +++ b/src/main/java/eu/hbp/mip/controllers/ActiveUserAPI.java @@ -2,10 +2,9 @@ package eu.hbp.mip.controllers; import eu.hbp.mip.models.DAOs.UserDAO; import eu.hbp.mip.services.ActiveUserService; -import eu.hbp.mip.utils.Logging; +import eu.hbp.mip.utils.Logger; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -21,14 +20,17 @@ import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; @Api(value = "/activeUser") public class ActiveUserAPI { - @Autowired - private ActiveUserService activeUserService; + private final ActiveUserService activeUserService; + + public ActiveUserAPI(ActiveUserService activeUserService) { + this.activeUserService = activeUserService; + } @ApiOperation(value = "Get the active user", response = UserDAO.class) @RequestMapping(method = RequestMethod.GET) public ResponseEntity<UserDAO> getTheActiveUser(HttpServletResponse response) { - Logging.LogUserAction(activeUserService.getActiveUser().getUsername(), "(GET) /activeUser", - "Loading the details of the activeUser"); + Logger logger = new Logger(activeUserService.getActiveUser().getUsername(), "(GET) /activeUser"); + logger.LogUserAction("Loading the details of the activeUser"); return ResponseEntity.ok(activeUserService.getActiveUser()); } @@ -36,8 +38,8 @@ public class ActiveUserAPI { @ApiOperation(value = "The active user agrees to the NDA", response = UserDAO.class) @RequestMapping(value = "/agreeNDA", method = RequestMethod.POST) public ResponseEntity<UserDAO> activeUserServiceAgreesToNDA(@RequestBody(required = false) UserDAO userDAO) { - Logging.LogUserAction(activeUserService.getActiveUser().getUsername(), "(GET) /activeUser/agreeNDA", - "The user agreed to the NDA"); + Logger logger = new Logger(activeUserService.getActiveUser().getUsername(), "(GET) /activeUser/agreeNDA"); + logger.LogUserAction("The user agreed to the NDA"); return ResponseEntity.ok(activeUserService.agreeToNDA()); } diff --git a/src/main/java/eu/hbp/mip/controllers/AlgorithmsAPI.java b/src/main/java/eu/hbp/mip/controllers/AlgorithmsAPI.java index 001409d25552ff77a12f6df12e79c46c297754c2..48500bb10470059f1fe7d37079dfb391ef395b31 100644 --- a/src/main/java/eu/hbp/mip/controllers/AlgorithmsAPI.java +++ b/src/main/java/eu/hbp/mip/controllers/AlgorithmsAPI.java @@ -9,14 +9,13 @@ import com.google.gson.reflect.TypeToken; import eu.hbp.mip.controllers.galaxy.retrofit.RetroFitGalaxyClients; import eu.hbp.mip.controllers.galaxy.retrofit.RetrofitClientInstance; import eu.hbp.mip.models.DTOs.AlgorithmDTO; -import eu.hbp.mip.services.ActiveUserService; import eu.hbp.mip.models.galaxy.WorkflowDTO; +import eu.hbp.mip.services.ActiveUserService; import eu.hbp.mip.utils.CustomResourceLoader; import eu.hbp.mip.utils.HTTPUtil; -import eu.hbp.mip.utils.Logging; +import eu.hbp.mip.utils.Logger; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.http.ResponseEntity; @@ -41,8 +40,7 @@ public class AlgorithmsAPI { private static final Gson gson = new Gson(); - @Autowired - private ActiveUserService activeUserService; + private final ActiveUserService activeUserService; @Value("#{'${services.exareme.algorithmsUrl}'}") private String exaremeAlgorithmsUrl; @@ -56,38 +54,40 @@ public class AlgorithmsAPI { @Value("#{'${files.disabledAlgorithms_json}'}") private String disabledAlgorithmsFilePath; + public AlgorithmsAPI(ActiveUserService activeUserService, CustomResourceLoader resourceLoader) { + this.activeUserService = activeUserService; + this.resourceLoader = resourceLoader; + } + @ApiOperation(value = "List all algorithms", response = String.class) @RequestMapping(method = RequestMethod.GET) public ResponseEntity<List<AlgorithmDTO>> getAlgorithms() { - String username = activeUserService.getActiveUser().getUsername(); - String endpoint = "(GET) /algorithms"; - Logging.LogUserAction(username, endpoint, "Executing..."); + Logger logger = new Logger(activeUserService.getActiveUser().getUsername(), "(GET) /algorithms"); + + logger.LogUserAction("Executing..."); - LinkedList<AlgorithmDTO> exaremeAlgorithms = getExaremeAlgorithms(); - Logging.LogUserAction(username, endpoint, "Loaded " + exaremeAlgorithms.size() + " exareme algorithms"); - LinkedList<AlgorithmDTO> galaxyAlgorithms = getGalaxyWorkflows(); - Logging.LogUserAction(username, endpoint, "Loaded " + galaxyAlgorithms.size() + " galaxy algorithms"); + LinkedList<AlgorithmDTO> exaremeAlgorithms = getExaremeAlgorithms(logger); + logger.LogUserAction("Loaded " + exaremeAlgorithms.size() + " exareme algorithms"); + LinkedList<AlgorithmDTO> galaxyAlgorithms = getGalaxyWorkflows(logger); + logger.LogUserAction("Loaded " + galaxyAlgorithms.size() + " galaxy algorithms"); LinkedList<AlgorithmDTO> algorithms = new LinkedList<>(); if (exaremeAlgorithms != null) { algorithms.addAll(exaremeAlgorithms); } else { - Logging.LogUserAction(username, endpoint, - "Getting exareme algorithms failed and returned null"); + logger.LogUserAction("Getting exareme algorithms failed and returned null"); } if (galaxyAlgorithms != null) { algorithms.addAll(galaxyAlgorithms); } else { - Logging.LogUserAction(username, endpoint, - "Getting galaxy workflows failed and returned null"); + logger.LogUserAction("Getting galaxy workflows failed and returned null"); } List<String> disabledAlgorithms = new ArrayList<>(); try { disabledAlgorithms = getDisabledAlgorithms(); } catch (IOException e) { - Logging.LogUserAction(username, endpoint, - "The disabled algorithms could not be loaded."); + logger.LogUserAction("The disabled algorithms could not be loaded."); } // Remove any disabled algorithm @@ -97,8 +97,7 @@ public class AlgorithmsAPI { allowedAlgorithms.add(algorithm); } } - Logging.LogUserAction(username, endpoint, - "Successfully listed " + allowedAlgorithms.size() + " algorithms"); + logger.LogUserAction("Successfully listed " + allowedAlgorithms.size() + " algorithms"); return ResponseEntity.ok(allowedAlgorithms); } @@ -107,10 +106,8 @@ public class AlgorithmsAPI { * * @return a list of AlgorithmDTOs or null if something fails */ - public LinkedList<AlgorithmDTO> getExaremeAlgorithms() { - String username = activeUserService.getActiveUser().getUsername(); - String endpoint = "(GET) /algorithms"; - LinkedList<AlgorithmDTO> algorithms = new LinkedList<>(); + public LinkedList<AlgorithmDTO> getExaremeAlgorithms(Logger logger) { + LinkedList<AlgorithmDTO> algorithms; // Get exareme algorithms try { StringBuilder response = new StringBuilder(); @@ -122,12 +119,11 @@ public class AlgorithmsAPI { }.getType() ); } catch (IOException e) { - Logging.LogUserAction(username, endpoint, "An exception occurred: " + e.getMessage()); + logger.LogUserAction("An exception occurred: " + e.getMessage()); return null; } - Logging.LogUserAction(username, endpoint, - "Completed, returned " + algorithms.size() + " algorithms."); + logger.LogUserAction("Completed, returned " + algorithms.size() + " algorithms."); return algorithms; } @@ -136,9 +132,7 @@ public class AlgorithmsAPI { * * @return a list of AlgorithmDTOs or null if something fails */ - public LinkedList<AlgorithmDTO> getGalaxyWorkflows() { - String username = activeUserService.getActiveUser().getUsername(); - String endpoint = "(GET) /algorithms"; + public LinkedList<AlgorithmDTO> getGalaxyWorkflows(Logger logger) { List<Workflow> workflowList; try { // Get all the workflows with the galaxy client @@ -147,7 +141,7 @@ public class AlgorithmsAPI { workflowList = new ArrayList<>(workflowsClient.getWorkflows()); } catch (Exception e) { - Logging.LogUserAction(username, endpoint, "Error when calling list galaxy workflows: " + e.getMessage()); + logger.LogUserAction("Error when calling list galaxy workflows: " + e.getMessage()); return null; } @@ -166,33 +160,31 @@ public class AlgorithmsAPI { } else { // Something unexpected happened String msgErr = gson.toJson(response.errorBody()); - Logging.LogUserAction(username, endpoint, "Error Response: " + msgErr); + logger.LogUserAction("Error Response: " + msgErr); return null; } } catch (Exception e) { - Logging.LogUserAction(username, endpoint, "An exception occurred: " + e.getMessage()); + logger.LogUserAction("An exception occurred: " + e.getMessage()); return null; } } - Logging.LogUserAction(username, endpoint, "Workflows fetched: " + workflows.size()); + logger.LogUserAction("Workflows fetched: " + workflows.size()); // Convert the workflows to algorithms LinkedList<AlgorithmDTO> algorithms = new LinkedList<>(); for (WorkflowDTO workflow : workflows) { - Logging.LogUserAction(username, endpoint, "Converting workflow: " + workflow); + logger.LogUserAction("Converting workflow: " + workflow); algorithms.add(workflow.convertToAlgorithmDTO()); - Logging.LogUserAction(username, endpoint, - "Converted algorithm: " + algorithms.get(algorithms.size() - 1)); + logger.LogUserAction("Converted algorithm: " + algorithms.get(algorithms.size() - 1)); } - Logging.LogUserAction(username, endpoint, "Completed!"); + logger.LogUserAction("Completed!"); return algorithms; } - @Autowired - private CustomResourceLoader resourceLoader; + private final CustomResourceLoader resourceLoader; /** * Fetches the disabled algorithms from a .json file @@ -204,11 +196,10 @@ public class AlgorithmsAPI { Resource resource = resourceLoader.getResource(disabledAlgorithmsFilePath); - List<String> response = gson.fromJson(convertInputStreamToString( + return gson.fromJson(convertInputStreamToString( resource.getInputStream()), new TypeToken<List<String>>() { }.getType() ); - return response; } } diff --git a/src/main/java/eu/hbp/mip/controllers/ExperimentAPI.java b/src/main/java/eu/hbp/mip/controllers/ExperimentAPI.java index 5c002c0b8dc1fc800706e5f4508b308a37ad0f0f..e5d0b04c54b0fd8652f5d284cb8690eaf14d3acf 100644 --- a/src/main/java/eu/hbp/mip/controllers/ExperimentAPI.java +++ b/src/main/java/eu/hbp/mip/controllers/ExperimentAPI.java @@ -2,8 +2,10 @@ package eu.hbp.mip.controllers; import eu.hbp.mip.models.DTOs.ExperimentDTO; +import eu.hbp.mip.services.ActiveUserService; import eu.hbp.mip.services.ExperimentService; import eu.hbp.mip.utils.JsonConverters; +import eu.hbp.mip.utils.Logger; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @@ -27,14 +29,18 @@ import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; public class ExperimentAPI { private final ExperimentService experimentService; - - public ExperimentAPI(ExperimentService experimentService) { + private final ActiveUserService activeUserService; + public ExperimentAPI( + ExperimentService experimentService, + ActiveUserService activeUserService + ) { this.experimentService = experimentService; + this.activeUserService = activeUserService; } @ApiOperation(value = "Get experiments", response = Map.class, responseContainer = "List") @RequestMapping(method = RequestMethod.GET) - public ResponseEntity<String> getExperiments( + public ResponseEntity<String> getExperiments(Authentication authentication, @RequestParam(name = "name", required = false) String name, @RequestParam(name = "algorithm", required = false) String algorithm, @RequestParam(name = "shared", required = false) Boolean shared, @@ -45,7 +51,7 @@ public class ExperimentAPI { @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "10") int size ) { - Map experiments = experimentService.getExperiments( + Map experiments = experimentService.getExperiments(authentication, name, algorithm, shared, @@ -55,16 +61,16 @@ public class ExperimentAPI { size, orderBy, descending, - "(GET) /experiments"); + new Logger(activeUserService.getActiveUser().getUsername(),"(GET) /experiments")); return new ResponseEntity(experiments, HttpStatus.OK); } @ApiOperation(value = "Get an experiment", response = ExperimentDTO.class) @RequestMapping(value = "/{uuid}", method = RequestMethod.GET) - public ResponseEntity<String> getExperiment( + public ResponseEntity<String> getExperiment(Authentication authentication, @ApiParam(value = "uuid", required = true) @PathVariable("uuid") String uuid) { - ExperimentDTO experimentDTO = experimentService.getExperiment(uuid, "(GET) /experiments/{uuid}"); + ExperimentDTO experimentDTO = experimentService.getExperiment(authentication, uuid, new Logger(activeUserService.getActiveUser().getUsername(),"(GET) /experiments/{uuid}")); return new ResponseEntity<>(JsonConverters.convertObjectToJsonString(experimentDTO), HttpStatus.OK); } @@ -72,7 +78,7 @@ public class ExperimentAPI { @ApiOperation(value = "Create an experiment", response = ExperimentDTO.class) @RequestMapping(method = RequestMethod.POST) public ResponseEntity<String> createExperiment(Authentication authentication, @RequestBody ExperimentDTO experimentDTO) { - experimentDTO = experimentService.createExperiment(authentication, experimentDTO, "(POST) /experiments"); + experimentDTO = experimentService.createExperiment(authentication, experimentDTO, new Logger(activeUserService.getActiveUser().getUsername(),"(POST) /experiments")); return new ResponseEntity<>(JsonConverters.convertObjectToJsonString(experimentDTO), HttpStatus.CREATED); } @@ -80,7 +86,7 @@ public class ExperimentAPI { @ApiOperation(value = "Update an experiment", response = ExperimentDTO.class) @RequestMapping(value = "/{uuid}", method = RequestMethod.PATCH) public ResponseEntity<String> updateExperiment(@RequestBody ExperimentDTO experimentDTO, @ApiParam(value = "uuid", required = true) @PathVariable("uuid") String uuid) { - experimentDTO = experimentService.updateExperiment(uuid, experimentDTO, "(PATCH) /experiments/{uuid}"); + experimentDTO = experimentService.updateExperiment(uuid, experimentDTO, new Logger(activeUserService.getActiveUser().getUsername(),"(PATCH) /experiments/{uuid}")); return new ResponseEntity<>(JsonConverters.convertObjectToJsonString(experimentDTO), HttpStatus.OK); } @@ -89,7 +95,7 @@ public class ExperimentAPI { @RequestMapping(value = "/{uuid}", method = RequestMethod.DELETE) public ResponseEntity<String> deleteExperiment( @ApiParam(value = "uuid", required = true) @PathVariable("uuid") String uuid) { - experimentService.deleteExperiment(uuid, "(DELETE) /experiments/{uuid}"); + experimentService.deleteExperiment(uuid, new Logger(activeUserService.getActiveUser().getUsername(), "(DELETE) /experiments/{uuid}")); return new ResponseEntity<>(HttpStatus.OK); } @@ -97,8 +103,7 @@ public class ExperimentAPI { @ApiOperation(value = "Create a transient experiment", response = ExperimentDTO.class) @RequestMapping(value = "/transient", method = RequestMethod.POST) public ResponseEntity<String> createTransientExperiment(Authentication authentication, @RequestBody ExperimentDTO experimentDTO) { - experimentDTO = experimentService.createTransientExperiment(authentication, experimentDTO, "(POST) /experiments/transient"); - + experimentDTO = experimentService.createTransientExperiment(authentication, experimentDTO, new Logger(activeUserService.getActiveUser().getUsername(), "(POST) /experiments/transient")); return new ResponseEntity<>(JsonConverters.convertObjectToJsonString(experimentDTO), HttpStatus.OK); } } \ No newline at end of file diff --git a/src/main/java/eu/hbp/mip/controllers/PathologiesAPI.java b/src/main/java/eu/hbp/mip/controllers/PathologiesAPI.java index f79052ff5e07e73ae14f5e96ec676e09727838fd..175ad297761e25356f50b4b6686fcc01d9f5fa2d 100644 --- a/src/main/java/eu/hbp/mip/controllers/PathologiesAPI.java +++ b/src/main/java/eu/hbp/mip/controllers/PathologiesAPI.java @@ -8,9 +8,8 @@ import eu.hbp.mip.utils.ClaimUtils; import eu.hbp.mip.utils.CustomResourceLoader; import eu.hbp.mip.utils.Exceptions.BadRequestException; import eu.hbp.mip.utils.InputStreamConverter; -import eu.hbp.mip.utils.Logging; +import eu.hbp.mip.utils.Logger; import io.swagger.annotations.Api; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.http.ResponseEntity; @@ -31,8 +30,6 @@ public class PathologiesAPI { private static final Gson gson = new Gson(); - @Autowired - private ActiveUserService activeUserService; // Enable HBP collab authentication (1) or disable it (0). Default is 1 @Value("#{'${authentication.enabled}'}") @@ -41,14 +38,19 @@ public class PathologiesAPI { @Value("#{'${files.pathologies_json}'}") private String pathologiesFilePath; - @Autowired - private CustomResourceLoader resourceLoader; + private final ActiveUserService activeUserService; + + private final CustomResourceLoader resourceLoader; + + public PathologiesAPI(ActiveUserService activeUserService, CustomResourceLoader resourceLoader) { + this.activeUserService = activeUserService; + this.resourceLoader = resourceLoader; + } @RequestMapping(name = "/pathologies", method = RequestMethod.GET) public ResponseEntity<String> getPathologies(Authentication authentication) { - String endpoint = "(GET) /pathologies"; - String username = activeUserService.getActiveUser().getUsername(); - Logging.LogUserAction(username, endpoint, "Loading pathologies ..."); + Logger logger = new Logger(activeUserService.getActiveUser().getUsername(), "(GET) /pathologies"); + logger.LogUserAction("Loading pathologies ..."); // Load pathologies from file Resource resource = resourceLoader.getResource(pathologiesFilePath); @@ -57,18 +59,18 @@ public class PathologiesAPI { allPathologies = gson.fromJson(InputStreamConverter.convertInputStreamToString(resource.getInputStream()), new TypeToken<List<PathologyDTO>>() { }.getType()); } catch (IOException e) { - Logging.LogUserAction(username, endpoint, "Unable to load pathologies"); + logger.LogUserAction("Unable to load pathologies"); throw new BadRequestException("The pathologies could not be loaded."); } // If authentication is disabled return everything if (!authenticationIsEnabled) { - Logging.LogUserAction(username, endpoint, "Successfully loaded " + allPathologies.size() + " pathologies"); + logger.LogUserAction("Successfully loaded " + allPathologies.size() + " pathologies"); return ResponseEntity.ok().body(gson.toJson(allPathologies)); } - Logging.LogUserAction(username, endpoint, "Successfully loaded all authorized pathologies"); + logger.LogUserAction("Successfully loaded all authorized pathologies"); return ResponseEntity.ok().body(ClaimUtils.getAuthorizedPathologies( - username, authentication.getAuthorities(), allPathologies)); + activeUserService.getActiveUser().getUsername(), logger, authentication.getAuthorities(), allPathologies)); } } diff --git a/src/main/java/eu/hbp/mip/services/ActiveUserService.java b/src/main/java/eu/hbp/mip/services/ActiveUserService.java index 61bad973c94cc04da2adccf5952949378030ce92..f1fe049c24673aa2a11cec62f4b266225e17376a 100644 --- a/src/main/java/eu/hbp/mip/services/ActiveUserService.java +++ b/src/main/java/eu/hbp/mip/services/ActiveUserService.java @@ -8,6 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; +import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; @@ -19,12 +20,15 @@ import javax.inject.Named; public class ActiveUserService { @Value("#{'${authentication.enabled}'}") - private boolean authentication; + private boolean authenticationIsEnabled; private UserDAO user; - @Autowired - private UserRepository userRepository; + private final UserRepository userRepository; + + public ActiveUserService(UserRepository userRepository) { + this.userRepository = userRepository; + } /** * Fetches the details of the active user. @@ -39,13 +43,13 @@ public class ActiveUserService { return user; // If Authentication is OFF, create anonymous user with accepted NDA - if (!authentication) { + if (!authenticationIsEnabled) { user = new UserDAO("anonymous", "anonymous", "anonymous@anonymous.com"); user.setAgreeNDA(true); userRepository.save(user); return user; } - + //TODO: // If authentication is ON get user info from Token KeycloakPrincipal keycloakPrincipal = (KeycloakPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); diff --git a/src/main/java/eu/hbp/mip/services/ExperimentService.java b/src/main/java/eu/hbp/mip/services/ExperimentService.java index 56861903cf8c9e07b1ef3b3bbbd89e219aa3a09d..e12c0b858d5573ce76a7bdb6f67d19e8c246f395 100644 --- a/src/main/java/eu/hbp/mip/services/ExperimentService.java +++ b/src/main/java/eu/hbp/mip/services/ExperimentService.java @@ -23,7 +23,7 @@ import eu.hbp.mip.utils.ClaimUtils; import eu.hbp.mip.utils.Exceptions.*; import eu.hbp.mip.utils.HTTPUtil; import eu.hbp.mip.utils.JsonConverters; -import eu.hbp.mip.utils.Logging; +import eu.hbp.mip.utils.Logger; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.springframework.beans.factory.annotation.Value; @@ -79,34 +79,36 @@ public class ExperimentService { * @param size is the size of each page * @param orderBy is the column that is required to ordered by * @param descending is a boolean to determine if the experiments will be order by descending or ascending - * @param endpoint is the endpoint that called the function + * @param logger contains username and the endpoint. * @return a list of mapped experiments */ - public Map getExperiments(String name, String algorithm, Boolean shared, Boolean viewed, boolean includeShared, int page, int size, String orderBy, Boolean descending, String endpoint) { + public Map getExperiments(Authentication authentication, String name, String algorithm, Boolean shared, Boolean viewed, boolean includeShared, int page, int size, String orderBy, Boolean descending, Logger logger) { + UserDAO user = activeUserService.getActiveUser(); - Logging.LogUserAction(user.getUsername(), endpoint, "Listing my experiments."); + logger.LogUserAction("Listing my experiments."); if (size > 50) throw new BadRequestException("Invalid size input, max size is 50."); - /*TODO:if(role == master){ - Specification<ExperimentDAO> spec = Specification - .where(new ExperimentSpecifications.ExperimentWithName(name)) - .and(new ExperimentSpecifications.ExperimentWithAlgorithm(algorithm)) - .and(new ExperimentSpecifications.ExperimentWithShared(shared)) - .and(new ExperimentSpecifications.ExperimentWithViewed(viewed)) - .and(new ExperimentSpecifications.ExperimentOrderBy(orderBy, descending)); - } - else - */ - Specification<ExperimentDAO> spec = Specification - .where(new ExperimentSpecifications.MyExperiment(user.getUsername())) - .or(new ExperimentSpecifications.SharedExperiment(includeShared)) - .and(new ExperimentSpecifications.ExperimentWithAlgorithm(algorithm)) - .and(new ExperimentSpecifications.ExperimentWithShared(shared)) - .and(new ExperimentSpecifications.ExperimentWithViewed(viewed)) - .and(new ExperimentSpecifications.ExperimentWithName(name)) - .and(new ExperimentSpecifications.ExperimentOrderBy(orderBy, descending)); - + Specification<ExperimentDAO> spec; + if(authenticationIsEnabled && ClaimUtils.validateAccessRightsOnExperiments(user.getUsername(), authentication.getAuthorities(), logger)) + { + spec = Specification + .where(new ExperimentSpecifications.ExperimentWithName(name)) + .and(new ExperimentSpecifications.ExperimentWithAlgorithm(algorithm)) + .and(new ExperimentSpecifications.ExperimentWithShared(shared)) + .and(new ExperimentSpecifications.ExperimentWithViewed(viewed)) + .and(new ExperimentSpecifications.ExperimentOrderBy(orderBy, descending)); + } + else { + spec = Specification + .where(new ExperimentSpecifications.MyExperiment(user.getUsername())) + .or(new ExperimentSpecifications.SharedExperiment(includeShared)) + .and(new ExperimentSpecifications.ExperimentWithAlgorithm(algorithm)) + .and(new ExperimentSpecifications.ExperimentWithShared(shared)) + .and(new ExperimentSpecifications.ExperimentWithViewed(viewed)) + .and(new ExperimentSpecifications.ExperimentWithName(name)) + .and(new ExperimentSpecifications.ExperimentOrderBy(orderBy, descending)); + } Pageable paging = PageRequest.of(page, size); Page<ExperimentDAO> pageExperiments = experimentRepository.findAll(spec, paging); List<ExperimentDAO> experimentDAOs = pageExperiments.getContent(); @@ -130,24 +132,27 @@ public class ExperimentService { * The getExperiment will retrieve the experiment from database according to the input uuid * * @param uuid is the id of the experiment to be retrieved - * @param endpoint is the endpoint that called the function + * @param logger contains username and the endpoint. * @return the experiment information that was retrieved from the database */ - public ExperimentDTO getExperiment(String uuid, String endpoint) { + public ExperimentDTO getExperiment(Authentication authentication, String uuid, Logger logger) { ExperimentDAO experimentDAO; UserDAO user = activeUserService.getActiveUser(); - Logging.LogUserAction(user.getUsername(), endpoint, "Loading Experiment with uuid : " + uuid); + logger.LogUserAction("Loading Experiment with uuid : " + uuid); - experimentDAO = loadExperiment(uuid, endpoint); - //TODO: if (!experimentDAO.isShared() && !experimentDAO.getCreatedBy().getUsername().equals(user.getUsername()) && if not master) { - if (!experimentDAO.isShared() && !experimentDAO.getCreatedBy().getUsername().equals(user.getUsername()) ) { - Logging.LogUserAction(user.getUsername(), endpoint, "Accessing Experiment is unauthorized."); + experimentDAO = loadExperiment(uuid, logger); + if ( + !experimentDAO.isShared() + && !experimentDAO.getCreatedBy().getUsername().equals(user.getUsername()) + && ClaimUtils.validateAccessRightsOnExperiments(user.getUsername(), authentication.getAuthorities(), logger) + ) { + logger.LogUserAction("Accessing Experiment is unauthorized."); throw new UnauthorizedException("You don't have access to the experiment."); } ExperimentDTO experimentDTO = experimentDAO.convertToDTO(true); - Logging.LogUserAction(user.getUsername(), endpoint, "Experiment was Loaded with uuid : " + uuid + "."); + logger.LogUserAction("Experiment was Loaded with uuid : " + uuid + "."); return experimentDTO; } @@ -157,37 +162,37 @@ public class ExperimentService { * * @param authentication is the role of the user * @param experimentDTO is the experiment information - * @param endpoint is the endpoint that called the function + * @param logger contains username and the endpoint. * @return the experiment information which was created */ - public ExperimentDTO createExperiment(Authentication authentication, ExperimentDTO experimentDTO, String endpoint) { + public ExperimentDTO createExperiment(Authentication authentication, ExperimentDTO experimentDTO, Logger logger) { UserDAO user = activeUserService.getActiveUser(); //Checking if check (POST) /experiments has proper input. - checkPostExperimentProperInput(experimentDTO, endpoint); + checkPostExperimentProperInput(experimentDTO, logger); // Get the type and name of algorithm String algorithmType = experimentDTO.getAlgorithm().getType(); if(algorithmType == null){ - Logging.LogUserAction(user.getUsername(), endpoint, "Please provide algorithm type."); + logger.LogUserAction("Please provide algorithm type."); throw new BadRequestException("Please provide algorithm type."); } - algorithmParametersLogging(experimentDTO, endpoint); + algorithmParametersLogging(experimentDTO, logger); if (authenticationIsEnabled) { - String experimentDatasets = getDatasetFromExperimentParameters(experimentDTO, endpoint); - ClaimUtils.validateAccessRightsOnDatasets(user.getUsername(), authentication.getAuthorities(), experimentDatasets, endpoint); + String experimentDatasets = getDatasetFromExperimentParameters(experimentDTO, logger); + ClaimUtils.validateAccessRightsOnDatasets(user.getUsername(), authentication.getAuthorities(), experimentDatasets, logger); } // Run with the appropriate engine if (algorithmType.equals("workflow")) { - Logging.LogUserAction(user.getUsername(), endpoint, "Algorithm runs on Galaxy."); - return runGalaxyWorkflow(experimentDTO, endpoint); + logger.LogUserAction("Algorithm runs on Galaxy."); + return runGalaxyWorkflow(experimentDTO, logger); } else { - Logging.LogUserAction(user.getUsername(), endpoint, "Algorithm runs on Exareme."); - return createExaremeExperiment(experimentDTO, endpoint); + logger.LogUserAction("Algorithm runs on Exareme."); + return createExaremeExperiment(experimentDTO, logger); } } @@ -196,14 +201,14 @@ public class ExperimentService { * * @param authentication is the role of the user * @param experimentDTO is the experiment information - * @param endpoint is the endpoint that called the function + * @param logger contains username and the endpoint. * @return the experiment information which was created */ - public ExperimentDTO createTransientExperiment(Authentication authentication, ExperimentDTO experimentDTO, String endpoint) { + public ExperimentDTO createTransientExperiment(Authentication authentication, ExperimentDTO experimentDTO, Logger logger) { UserDAO user = activeUserService.getActiveUser(); //Checking if check (POST) /experiments has proper input. - checkPostExperimentProperInput(experimentDTO, endpoint); + checkPostExperimentProperInput(experimentDTO, logger); // Get the parameters List<AlgorithmDTO.AlgorithmParamDTO> algorithmParameters @@ -212,24 +217,23 @@ public class ExperimentService { // Get the type and name of algorithm String algorithmName = experimentDTO.getAlgorithm().getName(); - algorithmParametersLogging(experimentDTO, endpoint); + algorithmParametersLogging(experimentDTO, logger); if (authenticationIsEnabled) { - String experimentDatasets = getDatasetFromExperimentParameters(experimentDTO, endpoint); - ClaimUtils.validateAccessRightsOnDatasets(user.getUsername(), authentication.getAuthorities(), experimentDatasets, endpoint); + String experimentDatasets = getDatasetFromExperimentParameters(experimentDTO, logger); + ClaimUtils.validateAccessRightsOnDatasets(user.getUsername(), authentication.getAuthorities(), experimentDatasets, logger); } String body = gson.toJson(algorithmParameters); String url = queryExaremeUrl + "/" + algorithmName; - Logging.LogUserAction(user.getUsername(), endpoint, "url: " + url + ", body: " + body); + logger.LogUserAction("url: " + url + ", body: " + body); - Logging.LogUserAction(user.getUsername(), endpoint, - "Completed, returning: " + experimentDTO.toString()); + logger.LogUserAction("Completed, returning: " + experimentDTO.toString()); // Results are stored in the experiment object ExaremeResult exaremeResult = runExaremeExperiment(url, body, experimentDTO); - Logging.LogUserAction(user.getUsername(), endpoint, "Experiment with uuid: " + experimentDTO.getUuid() + "gave response code: " + exaremeResult.getCode() + " and result: " + exaremeResult.getResults()); + logger.LogUserAction("Experiment with uuid: " + experimentDTO.getUuid() + "gave response code: " + exaremeResult.getCode() + " and result: " + exaremeResult.getResults()); experimentDTO.setResult((exaremeResult.getCode() >= 400) ? null : exaremeResult.getResults()); experimentDTO.setStatus((exaremeResult.getCode() >= 400) ? ExperimentDAO.Status.error : ExperimentDAO.Status.success); @@ -242,18 +246,17 @@ public class ExperimentService { * * @param uuid is the id of the experiment to be updated * @param experimentDTO is the experiment information to be updated - * @param endpoint is the endpoint that called the function - * @return the updated experiment information + * @param logger contains username and the endpoint. */ - public ExperimentDTO updateExperiment(String uuid, ExperimentDTO experimentDTO, String endpoint) { + public ExperimentDTO updateExperiment(String uuid, ExperimentDTO experimentDTO, Logger logger) { ExperimentDAO experimentDAO; UserDAO user = activeUserService.getActiveUser(); - Logging.LogUserAction(user.getUsername(), endpoint, "Updating experiment with uuid : " + uuid + "."); + logger.LogUserAction("Updating experiment with uuid : " + uuid + "."); - experimentDAO = loadExperiment(uuid, endpoint); + experimentDAO = loadExperiment(uuid, logger); //Verify (PATCH) /experiments non editable fields. - verifyPatchExperimentNonEditableFields(uuid, experimentDTO, experimentDAO, endpoint); + verifyPatchExperimentNonEditableFields(experimentDTO, logger); if (!experimentDAO.getCreatedBy().getUsername().equals(user.getUsername())) throw new UnauthorizedException("You don't have access to the experiment."); @@ -272,11 +275,11 @@ public class ExperimentService { try { experimentRepository.save(experimentDAO); } catch (Exception e) { - Logging.LogUserAction(user.getUsername(), endpoint, "Attempted to save changes to database but an error ocurred : " + e.getMessage() + "."); + logger.LogUserAction("Attempted to save changes to database but an error ocurred : " + e.getMessage() + "."); throw new InternalServerError(e.getMessage()); } - Logging.LogUserAction(user.getUsername(), endpoint, "Updated experiment with uuid : " + uuid + "."); + logger.LogUserAction("Updated experiment with uuid : " + uuid + "."); experimentDTO = experimentDAO.convertToDTO(true); return experimentDTO; @@ -286,14 +289,14 @@ public class ExperimentService { * The deleteExperiment will delete an experiment from the database * * @param uuid is the id of the experiment to be deleted - * @param endpoint is the endpoint that called the function + * @param logger contains username and the endpoint. */ - public void deleteExperiment(String uuid, String endpoint) { + public void deleteExperiment(String uuid, Logger logger) { ExperimentDAO experimentDAO; UserDAO user = activeUserService.getActiveUser(); - Logging.LogUserAction(user.getUsername(), endpoint, "Deleting experiment with uuid : " + uuid + "."); + logger.LogUserAction("Deleting experiment with uuid : " + uuid + "."); - experimentDAO = loadExperiment(uuid, endpoint); + experimentDAO = loadExperiment(uuid, logger); if (!experimentDAO.getCreatedBy().getUsername().equals(user.getUsername())) throw new UnauthorizedException("You don't have access to the experiment."); @@ -301,16 +304,16 @@ public class ExperimentService { try { experimentRepository.delete(experimentDAO); } catch (Exception e) { - Logging.LogUserAction(user.getUsername(), endpoint, "Attempted to delete an experiment to database but an error ocurred : " + e.getMessage() + "."); + logger.LogUserAction("Attempted to delete an experiment to database but an error ocurred : " + e.getMessage() + "."); throw new InternalServerError(e.getMessage()); } - Logging.LogUserAction(user.getUsername(), endpoint, "Deleted experiment with uuid : " + uuid + "."); + logger.LogUserAction("Deleted experiment with uuid : " + uuid + "."); } // /* ------------------------------- PRIVATE METHODS ----------------------------------------------------*/ - private void checkPostExperimentProperInput(ExperimentDTO experimentDTO, String endpoint) { + private void checkPostExperimentProperInput(ExperimentDTO experimentDTO, Logger logger) { boolean properInput = experimentDTO.getShared() == null @@ -322,50 +325,39 @@ public class ExperimentService { && experimentDTO.getUuid() == null; if (!properInput) { - Logging.LogUserAction(activeUserService.getActiveUser().getUsername(), endpoint, "Invalid input."); + logger.LogUserAction( "Invalid input."); throw new BadRequestException("Please provide proper input."); } } - private void verifyPatchExperimentNonEditableFields(String uuid, ExperimentDTO experimentDTO, ExperimentDAO experimentDAO, String endpoint) { + private void verifyPatchExperimentNonEditableFields(ExperimentDTO experimentDTO, Logger logger) { if (experimentDTO.getUuid() != null ) { - Logging.LogUserAction(activeUserService.getActiveUser().getUsername(), endpoint, "Uuid is not editable."); + logger.LogUserAction( "Uuid is not editable."); throw new BadRequestException("Uuid is not editable."); } if (experimentDTO.getAlgorithm() != null ) { - Logging.LogUserAction(activeUserService.getActiveUser().getUsername(), endpoint, "Algorithm is not editable."); + logger.LogUserAction( "Algorithm is not editable."); throw new BadRequestException("Algorithm is not editable."); } if (experimentDTO.getCreated() != null) { - Logging.LogUserAction(activeUserService.getActiveUser().getUsername(), endpoint, "CreatedBy is not editable."); - throw new BadRequestException("CreatedBy is not editable."); - } - - if (experimentDTO.getAlgorithm() != null) { - Logging.LogUserAction(activeUserService.getActiveUser().getUsername(), endpoint, "AlgorithmDetails is not editable."); - throw new BadRequestException("AlgorithmDetails is not editable."); - } - - if (experimentDTO.getCreated() != null) { - Logging.LogUserAction(activeUserService.getActiveUser().getUsername(), endpoint, "Created is not editable."); + logger.LogUserAction( "Created is not editable."); throw new BadRequestException("Created is not editable."); } if (experimentDTO.getResult() != null) { - Logging.LogUserAction(activeUserService.getActiveUser().getUsername(), endpoint, "Status is not editable."); + logger.LogUserAction( "Status is not editable."); throw new BadRequestException("Status is not editable."); } if (experimentDTO.getStatus() != null) { - Logging.LogUserAction(activeUserService.getActiveUser().getUsername(), endpoint, "Status is not editable."); + logger.LogUserAction( "Status is not editable."); throw new BadRequestException("Status is not editable."); } } - private void algorithmParametersLogging(ExperimentDTO experimentDTO, String endpoint) { - UserDAO user = activeUserService.getActiveUser(); + private void algorithmParametersLogging(ExperimentDTO experimentDTO, Logger logger) { String algorithmName = experimentDTO.getAlgorithm().getName(); StringBuilder parametersLogMessage = new StringBuilder(", Parameters:\n"); experimentDTO.getAlgorithm().getParameters().forEach( @@ -375,17 +367,17 @@ public class ExperimentService { .append(" -> ") .append(params.getValue()) .append("\n")); - Logging.LogUserAction(user.getUsername(), endpoint, "Executing " + algorithmName + parametersLogMessage); + logger.LogUserAction("Executing " + algorithmName + parametersLogMessage); } /** * The getDatasetFromExperimentParameters will retrieve the dataset from the experiment parameters * * @param experimentDTO is the experiment information - * @param endpoint is the endpoint that called the function + * @param logger contains username and the endpoint. * @return the dataset from the experiment */ - private String getDatasetFromExperimentParameters(ExperimentDTO experimentDTO, String endpoint) { + private String getDatasetFromExperimentParameters(ExperimentDTO experimentDTO, Logger logger) { String experimentDatasets = null; for (AlgorithmDTO.AlgorithmParamDTO parameter : experimentDTO.getAlgorithm().getParameters()) { @@ -396,8 +388,7 @@ public class ExperimentService { } if (experimentDatasets == null || experimentDatasets.equals("")) { - Logging.LogUserAction(activeUserService.getActiveUser().getUsername(), endpoint, - "A dataset should be specified to run an algorithm."); + logger.LogUserAction("A dataset should be specified to run an algorithm."); throw new BadRequestException("Please provide at least one dataset to run the algorithm."); } return experimentDatasets; @@ -409,20 +400,20 @@ public class ExperimentService { * @param uuid is the id of the experiment to be retrieved * @return the experiment information that was retrieved from database */ - private ExperimentDAO loadExperiment(String uuid, String endpoint) { + private ExperimentDAO loadExperiment(String uuid, Logger logger) { UUID experimentUuid; ExperimentDAO experimentDAO; try { experimentUuid = UUID.fromString(uuid); } catch (Exception e) { - Logging.LogUserAction(activeUserService.getActiveUser().getUsername(), endpoint, e.getMessage()); + logger.LogUserAction( e.getMessage()); throw new BadRequestException(e.getMessage()); } experimentDAO = experimentRepository.findByUuid(experimentUuid); if (experimentDAO == null) { - Logging.LogUserAction(activeUserService.getActiveUser().getUsername(), endpoint, "Experiment with uuid : " + uuid + "was not found."); + logger.LogUserAction( "Experiment with uuid : " + uuid + "was not found."); throw new ExperimentNotFoundException("Experiment with uuid : " + uuid + " was not found."); } @@ -437,7 +428,7 @@ public class ExperimentService { * @Note In the database there will be stored Algorithm Details that is the whole information about the algorithm * and an Algorithm column that is required for the filtering with algorithm name in the GET /experiments. */ - private ExperimentDAO createExperimentInTheDatabase(ExperimentDTO experimentDTO, String endpoint) { + private ExperimentDAO createExperimentInTheDatabase(ExperimentDTO experimentDTO, Logger logger) { UserDAO user = activeUserService.getActiveUser(); ExperimentDAO experimentDAO = new ExperimentDAO(); @@ -451,42 +442,41 @@ public class ExperimentService { try { experimentRepository.save(experimentDAO); } catch (Exception e) { - Logging.LogUserAction(user.getUsername(), endpoint, "Attempted to save changes to database but an error ocurred : " + e.getMessage() + "."); + logger.LogUserAction("Attempted to save changes to database but an error ocurred : " + e.getMessage() + "."); throw new InternalServerError(e.getMessage()); } - Logging.LogUserAction(user.getUsername(), endpoint, " id : " + experimentDAO.getUuid()); - Logging.LogUserAction(user.getUsername(), endpoint, " algorithms : " + experimentDAO.getAlgorithmDetails()); - Logging.LogUserAction(user.getUsername(), endpoint, " name : " + experimentDAO.getName()); + logger.LogUserAction(" id : " + experimentDAO.getUuid()); + logger.LogUserAction(" algorithms : " + experimentDAO.getAlgorithmDetails()); + logger.LogUserAction(" name : " + experimentDAO.getName()); return experimentDAO; } - private void saveExperiment(ExperimentDAO experimentDAO, String endpoint) { - UserDAO user = activeUserService.getActiveUser(); + private void saveExperiment(ExperimentDAO experimentDAO, Logger logger) { - Logging.LogUserAction(user.getUsername(), endpoint, " id : " + experimentDAO.getUuid()); - Logging.LogUserAction(user.getUsername(), endpoint, " algorithms : " + experimentDAO.getAlgorithmDetails()); - Logging.LogUserAction(user.getUsername(), endpoint, " name : " + experimentDAO.getName()); - Logging.LogUserAction(user.getUsername(), endpoint, " historyId : " + experimentDAO.getWorkflowHistoryId()); - Logging.LogUserAction(user.getUsername(), endpoint, " status : " + experimentDAO.getStatus()); + logger.LogUserAction(" id : " + experimentDAO.getUuid()); + logger.LogUserAction(" algorithms : " + experimentDAO.getAlgorithmDetails()); + logger.LogUserAction(" name : " + experimentDAO.getName()); + logger.LogUserAction(" historyId : " + experimentDAO.getWorkflowHistoryId()); + logger.LogUserAction(" status : " + experimentDAO.getStatus()); try { experimentRepository.save(experimentDAO); } catch (Exception e) { - Logging.LogUserAction(user.getUsername(), endpoint, "Attempted to save changes to database but an error ocurred : " + e.getMessage() + "."); + logger.LogUserAction("Attempted to save changes to database but an error ocurred : " + e.getMessage() + "."); throw new InternalServerError(e.getMessage()); } - Logging.LogUserAction(user.getUsername(), endpoint, "Saved experiment"); + logger.LogUserAction("Saved experiment"); } - private void finishExperiment(ExperimentDAO experimentDAO, String endpoint) { + private void finishExperiment(ExperimentDAO experimentDAO, Logger logger) { experimentDAO.setFinished(new Date()); try { experimentRepository.save(experimentDAO); } catch (Exception e) { - Logging.LogUserAction(activeUserService.getActiveUser().getUsername(), endpoint, "Attempted to save changes to database but an error ocurred : " + e.getMessage() + "."); + logger.LogUserAction( "Attempted to save changes to database but an error ocurred : " + e.getMessage() + "."); throw new InternalServerError(e.getMessage()); } } @@ -497,16 +487,15 @@ public class ExperimentService { * The createExaremeExperiment will POST the algorithm to the exareme client * * @param experimentDTO is the request with the experiment information - * @param endpoint is the endpoint that called the function + * @param logger contains username and the endpoint. * @return the experiment information that was retrieved from exareme */ - public ExperimentDTO createExaremeExperiment(ExperimentDTO experimentDTO, String endpoint) { - UserDAO user = activeUserService.getActiveUser(); + public ExperimentDTO createExaremeExperiment(ExperimentDTO experimentDTO, Logger logger) { - Logging.LogUserAction(user.getUsername(), endpoint, "Running the algorithm..."); + logger.LogUserAction("Running the algorithm..."); - ExperimentDAO experimentDAO = createExperimentInTheDatabase(experimentDTO, endpoint); - Logging.LogUserAction(user.getUsername(), endpoint, "Created experiment with uuid :" + experimentDAO.getUuid()); + ExperimentDAO experimentDAO = createExperimentInTheDatabase(experimentDTO, logger); + logger.LogUserAction("Created experiment with uuid :" + experimentDAO.getUuid()); // Run the 1st algorithm from the list String algorithmName = experimentDTO.getAlgorithm().getName(); @@ -517,35 +506,33 @@ public class ExperimentService { String body = gson.toJson(algorithmParameters); String url = queryExaremeUrl + "/" + algorithmName; - Logging.LogUserAction(user.getUsername(), endpoint, "url: " + url + ", body: " + body); + logger.LogUserAction("url: " + url + ", body: " + body); - Logging.LogUserAction(user.getUsername(), endpoint, - "Completed, returning: " + experimentDTO.toString()); + logger.LogUserAction("Completed, returning: " + experimentDTO.toString()); - Logging.LogUserAction(user.getUsername(), endpoint, - "Starting exareme execution thread"); + logger.LogUserAction("Starting exareme execution thread"); ExperimentDTO finalExperimentDTO = experimentDTO; new Thread(() -> { // ATTENTION: Inside the Thread only LogExperimentAction should be used, not LogUserAction! - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Thread named :" + Thread.currentThread().getName() + " with id :" + Thread.currentThread().getId() + " started!"); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Thread named :" + Thread.currentThread().getName() + " with id :" + Thread.currentThread().getId() + " started!"); try { // Results are stored in the experiment object ExaremeResult exaremeResult = runExaremeExperiment(url, body, finalExperimentDTO); - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Experiment with uuid: " + experimentDAO.getUuid() + "gave response code: " + exaremeResult.getCode() + " and result: " + exaremeResult.getResults()); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Experiment with uuid: " + experimentDAO.getUuid() + "gave response code: " + exaremeResult.getCode() + " and result: " + exaremeResult.getResults()); experimentDAO.setResult((exaremeResult.getCode() >= 400) ? null : JsonConverters.convertObjectToJsonString(exaremeResult.getResults())); experimentDAO.setStatus((exaremeResult.getCode() >= 400) ? ExperimentDAO.Status.error : ExperimentDAO.Status.success); } catch (Exception e) { - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "There was an exception: " + e.getMessage()); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "There was an exception: " + e.getMessage()); experimentDAO.setStatus(ExperimentDAO.Status.error); } - finishExperiment(experimentDAO, endpoint); - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Finished the experiment: " + experimentDAO.toString()); + finishExperiment(experimentDAO, logger); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Finished the experiment: " + experimentDAO.toString()); }).start(); experimentDTO = experimentDAO.convertToDTO(true); return experimentDTO; @@ -568,7 +555,7 @@ public class ExperimentService { } catch (Exception e) { throw new InternalServerError("Error occurred : " + e.getMessage()); } - Logging.LogExperimentAction(experimentDTO.getName(), experimentDTO.getUuid(), "Algorithm finished with code: " + code); + Logger.LogExperimentAction(experimentDTO.getName(), experimentDTO.getUuid(), "Algorithm finished with code: " + code); // Results are stored in the experiment object ExperimentDTO experimentDTOWithOnlyResult = JsonConverters.convertJsonStringToObject(String.valueOf(results), ExperimentDTO.class); @@ -586,12 +573,11 @@ public class ExperimentService { * @param experimentDTO is the request with the experiment information * @return the response to be returned */ - public ExperimentDTO runGalaxyWorkflow(ExperimentDTO experimentDTO, String endpoint) { - UserDAO user = activeUserService.getActiveUser(); - Logging.LogUserAction(user.getUsername(), endpoint, "Running a workflow..."); + public ExperimentDTO runGalaxyWorkflow(ExperimentDTO experimentDTO, Logger logger) { + logger.LogUserAction("Running a workflow..."); - ExperimentDAO experimentDAO = createExperimentInTheDatabase(experimentDTO, endpoint); - Logging.LogUserAction(user.getUsername(), endpoint, "Created experiment with uuid :" + experimentDAO.getUuid()); + ExperimentDAO experimentDAO = createExperimentInTheDatabase(experimentDTO, logger); + logger.LogUserAction("Created experiment with uuid :" + experimentDAO.getUuid()); // Run the 1st algorithm from the list @@ -620,8 +606,7 @@ public class ExperimentService { } } if (workflow == null) { - Logging.LogUserAction(user.getUsername(), endpoint, - "Could not find algorithm code: " + workflowId); + logger.LogUserAction("Could not find algorithm code: " + workflowId); throw new BadRequestException("Could not find galaxy algorithm."); } final WorkflowDetails workflowDetails = workflowsClient.showWorkflow(workflow.getId()); @@ -638,7 +623,7 @@ public class ExperimentService { // Create the request client RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); - Logging.LogUserAction(user.getUsername(), endpoint, "Running Galaxy workflow with id: " + workflow.getId()); + logger.LogUserAction("Running Galaxy workflow with id: " + workflow.getId()); // Call Galaxy to run the workflow Call<PostWorkflowToGalaxyDtoResponse> call = service.postWorkflowToGalaxy(workflow.getId(), galaxyApiKey, requestBodyJson); @@ -647,7 +632,7 @@ public class ExperimentService { if (response.code() == 200) { // Call succeeded String responseBody = gson.toJson(response.body()); - Logging.LogUserAction(user.getUsername(), endpoint, "Response: " + responseBody); + logger.LogUserAction("Response: " + responseBody); String historyId = (String) new JSONObject(responseBody).get("history_id"); experimentDAO.setWorkflowHistoryId(historyId); @@ -655,7 +640,7 @@ public class ExperimentService { } else { // Something unexpected happened String msgErr = gson.toJson(response.errorBody()); - Logging.LogUserAction(user.getUsername(), endpoint, "Error Response: " + msgErr); + logger.LogUserAction("Error Response: " + msgErr); // Values are read from streams. JSONObject jObjectError = new JSONObject(msgErr); @@ -665,15 +650,15 @@ public class ExperimentService { } } catch (Exception e) { - Logging.LogUserAction(user.getUsername(), endpoint, "An exception occurred: " + e.getMessage()); + logger.LogUserAction("An exception occurred: " + e.getMessage()); experimentDAO.setStatus(ExperimentDAO.Status.error); } - saveExperiment(experimentDAO, endpoint); + saveExperiment(experimentDAO, logger); // Start the process of fetching the status - updateWorkflowExperiment(experimentDAO, endpoint); + updateWorkflowExperiment(experimentDAO, logger); - Logging.LogUserAction(user.getUsername(), endpoint, "Run workflow completed!"); + logger.LogUserAction("Run workflow completed!"); experimentDTO = experimentDAO.convertToDTO(true); return experimentDTO; @@ -685,59 +670,56 @@ public class ExperimentService { * * @param experimentDAO will be used to fetch it's workflow status, it should have the workflowHistoryId initialized * and the result should not already be fetched - * @return nothing, just updates the experiment */ - public void updateWorkflowExperiment(ExperimentDAO experimentDAO, String endpoint) { - UserDAO user = activeUserService.getActiveUser(); + public void updateWorkflowExperiment(ExperimentDAO experimentDAO, Logger logger) { if (experimentDAO == null) { - Logging.LogUserAction(user.getUsername(), endpoint, "The experiment does not exist."); + logger.LogUserAction("The experiment does not exist."); return; } - Logging.LogUserAction(user.getUsername(), endpoint, - " Experiment id : " + experimentDAO.getUuid()); + logger.LogUserAction(" Experiment id : " + experimentDAO.getUuid()); if (experimentDAO.getWorkflowHistoryId() == null) { - Logging.LogUserAction(user.getUsername(), endpoint, "History Id does not exist."); + logger.LogUserAction("History Id does not exist."); return; } - Logging.LogUserAction(user.getUsername(), endpoint, "Starting Thread..."); + logger.LogUserAction("Starting Thread..."); new Thread(() -> { while (true) { // ATTENTION: Inside the Thread only LogExperimentAction should be used, not LogExperimentAction! - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Thread is running..."); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Thread is running..."); try { sleep(2000); } catch (InterruptedException e) { - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Sleep was disrupted: " + e.getMessage()); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Sleep was disrupted: " + e.getMessage()); } - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Fetching status for experiment Id: " + experimentDAO.getUuid()); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Fetching status for experiment Id: " + experimentDAO.getUuid()); String state = getWorkflowStatus(experimentDAO); - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "State is: " + state); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "State is: " + state); switch (state) { case "running": // Do nothing, when the experiment is created the status is set to running - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Workflow is still running."); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Workflow is still running."); break; case "completed": // Get only the job result that is visible List<GalaxyWorkflowResult> workflowJobsResults = getWorkflowResults(experimentDAO); - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Results are: " + workflowJobsResults.toString()); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Results are: " + workflowJobsResults.toString()); boolean resultFound = false; for (GalaxyWorkflowResult jobResult : workflowJobsResults) { if (jobResult.getVisible()) { - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Visible result are: " + jobResult.getId()); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Visible result are: " + jobResult.getId()); String result = getWorkflowResultBody(experimentDAO, jobResult.getId()); - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "ResultDTO: " + result); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "ResultDTO: " + result); if (result == null) { experimentDAO.setStatus(ExperimentDAO.Status.error); } else { @@ -749,26 +731,26 @@ public class ExperimentService { } if (!resultFound) { // If there is no visible result - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "No visible result"); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "No visible result"); experimentDAO.setStatus(ExperimentDAO.Status.error); } - finishExperiment(experimentDAO, endpoint); + finishExperiment(experimentDAO, logger); break; case "error": // Get the job result that failed workflowJobsResults = getWorkflowResults(experimentDAO); - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Error results are: " + workflowJobsResults.toString()); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Error results are: " + workflowJobsResults.toString()); boolean failedJobFound = false; for (GalaxyWorkflowResult jobResult : workflowJobsResults) { if (jobResult.getState().equals("error")) { - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Failed job is: " + jobResult.getId()); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Failed job is: " + jobResult.getId()); String result = getWorkflowJobError(jobResult.getId(), experimentDAO); - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Job result: " + result); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "Job result: " + result); if (result == null) { experimentDAO.setStatus(ExperimentDAO.Status.error); } @@ -778,22 +760,22 @@ public class ExperimentService { } if (!failedJobFound) { // If there is no visible failed job - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "No failed result"); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "No failed result"); experimentDAO.setStatus(ExperimentDAO.Status.error); } - finishExperiment(experimentDAO, endpoint); + finishExperiment(experimentDAO, logger); break; default: // InternalError or unexpected result - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "An unexpected error occurred."); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "An unexpected error occurred."); experimentDAO.setStatus(ExperimentDAO.Status.error); - finishExperiment(experimentDAO, endpoint); + finishExperiment(experimentDAO, logger); break; } // If result exists return if (experimentDAO.getResult() != null) { - Logging.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "ResultDTO exists: " + experimentDAO.getResult()); + Logger.LogExperimentAction(experimentDAO.getName(), experimentDAO.getUuid(), "ResultDTO exists: " + experimentDAO.getResult()); return; } } @@ -814,7 +796,7 @@ public class ExperimentService { UUID experimentId = experimentDAO.getUuid(); // ATTENTION: This function is used from a Thread. Only LogExperimentAction should be used, not LogUserAction! - Logging.LogExperimentAction(experimentName, experimentId, " History Id : " + historyId); + Logger.LogExperimentAction(experimentName, experimentId, " History Id : " + historyId); // Create the request client RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); @@ -824,15 +806,15 @@ public class ExperimentService { try { Response<Object> response = call.execute(); if (response.code() >= 400) { - Logging.LogExperimentAction(experimentName, experimentId, " Response code: " + Logger.LogExperimentAction(experimentName, experimentId, " Response code: " + response.code() + "" + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return "internalError"; } result = new Gson().toJson(response.body()); - Logging.LogExperimentAction(experimentName, experimentId, " ResultDTO: " + result); + Logger.LogExperimentAction(experimentName, experimentId, " ResultDTO: " + result); } catch (IOException e) { - Logging.LogExperimentAction(experimentName, experimentId, " An exception happened: " + e.getMessage()); + Logger.LogExperimentAction(experimentName, experimentId, " An exception happened: " + e.getMessage()); return "internalError"; } @@ -841,11 +823,11 @@ public class ExperimentService { JSONObject resultJson = new JSONObject(result); state = resultJson.getString("state"); } catch (JSONException e) { - Logging.LogExperimentAction(experimentName, experimentId, " An exception happened: " + e.getMessage()); + Logger.LogExperimentAction(experimentName, experimentId, " An exception happened: " + e.getMessage()); return "internalError"; } - Logging.LogExperimentAction(experimentName, experimentId, " Completed!"); + Logger.LogExperimentAction(experimentName, experimentId, " Completed!"); switch (state) { case "ok": return "completed"; @@ -870,7 +852,7 @@ public class ExperimentService { String historyId = experimentDAO.getWorkflowHistoryId(); String experimentName = experimentDAO.getName(); UUID experimentId = experimentDAO.getUuid(); - Logging.LogExperimentAction(experimentName, experimentId, " historyId : " + historyId); + Logger.LogExperimentAction(experimentName, experimentId, " historyId : " + historyId); RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); Call<List<GalaxyWorkflowResult>> call = service.getWorkflowResultsFromGalaxy(historyId, galaxyApiKey); @@ -879,19 +861,19 @@ public class ExperimentService { try { Response<List<GalaxyWorkflowResult>> response = call.execute(); if (response.code() >= 400) { - Logging.LogExperimentAction(experimentName, experimentId, " Response code: " + Logger.LogExperimentAction(experimentName, experimentId, " Response code: " + response.code() + "" + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return null; } getGalaxyWorkflowResultList = response.body(); - Logging.LogExperimentAction(experimentName, experimentId, " ResultDTO: " + response.body()); + Logger.LogExperimentAction(experimentName, experimentId, " ResultDTO: " + response.body()); } catch (IOException e) { - Logging.LogExperimentAction(experimentName, experimentId, " An exception happened: " + e.getMessage()); + Logger.LogExperimentAction(experimentName, experimentId, " An exception happened: " + e.getMessage()); return null; } - Logging.LogExperimentAction(experimentName, experimentId, " Completed!"); + Logger.LogExperimentAction(experimentName, experimentId, " Completed!"); return getGalaxyWorkflowResultList; } @@ -907,7 +889,7 @@ public class ExperimentService { String experimentName = experimentDAO.getName(); UUID experimentId = experimentDAO.getUuid(); - Logging.LogExperimentAction(experimentName, experimentId, " historyId : " + historyId); + Logger.LogExperimentAction(experimentName, experimentId, " historyId : " + historyId); RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); Call<Object> call = @@ -917,20 +899,20 @@ public class ExperimentService { try { Response<Object> response = call.execute(); if (response.code() >= 400) { - Logging.LogExperimentAction(experimentName, experimentId, " Response code: " + Logger.LogExperimentAction(experimentName, experimentId, " Response code: " + response.code() + "" + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return null; } resultJson = new Gson().toJson(response.body()); - Logging.LogExperimentAction(experimentName, experimentId, " ResultDTO: " + resultJson); + Logger.LogExperimentAction(experimentName, experimentId, " ResultDTO: " + resultJson); } catch (IOException e) { - Logging.LogExperimentAction(experimentName, experimentId, + Logger.LogExperimentAction(experimentName, experimentId, " An exception happened: " + e.getMessage()); return null; } - Logging.LogExperimentAction(experimentName, experimentId, " Completed!"); + Logger.LogExperimentAction(experimentName, experimentId, " Completed!"); return resultJson; } @@ -943,7 +925,7 @@ public class ExperimentService { String experimentName = experimentDAO.getName(); UUID experimentId = experimentDAO.getUuid(); - Logging.LogExperimentAction(experimentName, experimentId, " jobId : " + jobId); + Logger.LogExperimentAction(experimentName, experimentId, " jobId : " + jobId); RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); Call<Object> callError = service.getErrorMessageOfWorkflowFromGalaxy(jobId, galaxyApiKey); @@ -952,7 +934,7 @@ public class ExperimentService { try { Response<Object> response = callError.execute(); if (response.code() >= 400) { - Logging.LogExperimentAction(experimentName, experimentId, "Response code: " + Logger.LogExperimentAction(experimentName, experimentId, "Response code: " + response.code() + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return null; } @@ -962,19 +944,19 @@ public class ExperimentService { JsonElement jsonElement = new JsonParser().parse(jsonString); JsonObject rootObject = jsonElement.getAsJsonObject(); fullError = rootObject.get("stderr").getAsString(); - Logging.LogExperimentAction(experimentName, experimentId, "Error: " + fullError); + Logger.LogExperimentAction(experimentName, experimentId, "Error: " + fullError); String[] arrOfStr = fullError.split("ValueError", 0); String specError = arrOfStr[arrOfStr.length - 1]; returnError = specError.substring(1); - Logging.LogExperimentAction(experimentName, experimentId, "Parsed Error: " + returnError); + Logger.LogExperimentAction(experimentName, experimentId, "Parsed Error: " + returnError); } catch (IOException e) { - Logging.LogExperimentAction(experimentName, experimentId, "Exception: " + e.getMessage()); + Logger.LogExperimentAction(experimentName, experimentId, "Exception: " + e.getMessage()); return null; } - Logging.LogExperimentAction(experimentName, experimentId, "Completed successfully!"); + Logger.LogExperimentAction(experimentName, experimentId, "Completed successfully!"); return returnError; } diff --git a/src/main/java/eu/hbp/mip/utils/ClaimUtils.java b/src/main/java/eu/hbp/mip/utils/ClaimUtils.java index 5eb90a2d076b68c2e871d054890239ccbd019907..501cea1b09a5755d7129450c16721fa71aba1602 100644 --- a/src/main/java/eu/hbp/mip/utils/ClaimUtils.java +++ b/src/main/java/eu/hbp/mip/utils/ClaimUtils.java @@ -2,14 +2,10 @@ package eu.hbp.mip.utils; import com.google.gson.Gson; import eu.hbp.mip.models.DTOs.PathologyDTO; -import eu.hbp.mip.utils.Exceptions.BadRequestException; import eu.hbp.mip.utils.Exceptions.UnauthorizedException; import org.springframework.security.core.GrantedAuthority; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; +import java.util.*; public class ClaimUtils { @@ -17,67 +13,62 @@ public class ClaimUtils { private static final Gson gson = new Gson(); public static String allDatasetsAllowedClaim() { - return "role_dataset_all"; + return "role_research_dataset_all"; + } + + public static String allExperimentsAllowedClaim() { + return "role_research_experiment_all"; } public static String getDatasetClaim(String datasetCode) { - return "role_dataset_" + datasetCode.toLowerCase(); + return "role_research_dataset_" + datasetCode.toLowerCase(); } public static void validateAccessRightsOnDatasets(String username, Collection<? extends GrantedAuthority> authorities, - String experimentDatasets, String endpoint) { - - List<String> userClaims = Arrays.asList(authorities.toString().toLowerCase() - .replaceAll("[\\s+\\]\\[]", "").split(",")); - Logging.LogUserAction(username, endpoint, userClaims.toString()); + String experimentDatasets, Logger logger) { // Don't check for dataset claims if "super" claim exists allowing everything - if (!userClaims.contains(ClaimUtils.allDatasetsAllowedClaim())) { + if (!hasRoleAccess(username, authorities, ClaimUtils.allDatasetsAllowedClaim(), logger)) { for (String dataset : experimentDatasets.split(",")) { String datasetRole = ClaimUtils.getDatasetClaim(dataset); - if (!userClaims.contains(datasetRole.toLowerCase())) { - Logging.LogUserAction(username, endpoint, - "You are not allowed to use dataset: " + dataset); + if (!hasRoleAccess(username, authorities, datasetRole, logger)) { + logger.LogUserAction("You are not allowed to use dataset: " + dataset); throw new UnauthorizedException("You are not authorized to use these datasets."); } } - Logging.LogUserAction(username, endpoint, - "User is authorized to use the datasets: " + experimentDatasets); + logger.LogUserAction("User is authorized to use the datasets: " + experimentDatasets); } } - public static String getAuthorizedPathologies(String username, Collection<? extends GrantedAuthority> authorities, - List<PathologyDTO> allPathologies) { - // --- Providing only the allowed pathologies/datasets to the user --- - Logging.LogUserAction(username, - "(GET) /pathologies", "Filter out the unauthorised datasets."); + public static boolean validateAccessRightsOnExperiments(String username, Collection<? extends GrantedAuthority> authorities, Logger logger) { - List<String> userClaims = Arrays.asList(authorities.toString().toLowerCase() - .replaceAll("[\\s+\\]\\[]", "").split(",")); + // Check for experiment_all claims + return hasRoleAccess(username, authorities, ClaimUtils.allExperimentsAllowedClaim(), logger); + } - Logging.LogUserAction(username, - "(GET) /pathologies", "User Claims: " + userClaims); + public static String getAuthorizedPathologies(String username, Logger logger, Collection<? extends GrantedAuthority> authorities, + List<PathologyDTO> allPathologies) { + // --- Providing only the allowed pathologies/datasets to the user --- + logger.LogUserAction("Filter out the unauthorised datasets."); // If the "dataset_all" claim exists then return everything - if (userClaims.contains(ClaimUtils.allDatasetsAllowedClaim())) { + if (hasRoleAccess(username, authorities, ClaimUtils.allDatasetsAllowedClaim(), logger)) { return gson.toJson(allPathologies); } List<PathologyDTO> userPathologies = new ArrayList<>(); for (PathologyDTO curPathology : allPathologies) { - List<PathologyDTO.PathologyDatasetDTO> userPathologyDatasets = new ArrayList<PathologyDTO.PathologyDatasetDTO>(); + List<PathologyDTO.PathologyDatasetDTO> userPathologyDatasets = new ArrayList<>(); for (PathologyDTO.PathologyDatasetDTO dataset : curPathology.getDatasets()) { - if (userClaims.contains(ClaimUtils.getDatasetClaim(dataset.getCode()))) { - Logging.LogUserAction(username, "(GET) /pathologies", - "Added dataset: " + dataset.getCode()); + if (hasRoleAccess(username, authorities, ClaimUtils.getDatasetClaim(dataset.getCode()), logger)) { + logger.LogUserAction("Added dataset: " + dataset.getCode()); userPathologyDatasets.add(dataset); } } if (userPathologyDatasets.size() > 0) { - Logging.LogUserAction(username, "(GET) /pathologies", - "Added pathology '" + curPathology.getLabel() + logger.LogUserAction("Added pathology '" + curPathology.getLabel() + "' with datasets: '" + userPathologyDatasets + "'"); PathologyDTO userPathology = new PathologyDTO(); @@ -92,4 +83,12 @@ public class ClaimUtils { return gson.toJson(userPathologies); } + private static boolean hasRoleAccess(String username, Collection<? extends GrantedAuthority> authorities,String role, Logger logger) + { + List<String> userClaims = Arrays.asList(authorities.toString().toLowerCase() + .replaceAll("[\\s+\\]\\[]", "").split(",")); + + logger.LogUserAction("User Claims: " + userClaims); + return userClaims.contains(role.toLowerCase()); + } } diff --git a/src/main/java/eu/hbp/mip/utils/Logging.java b/src/main/java/eu/hbp/mip/utils/Logger.java similarity index 53% rename from src/main/java/eu/hbp/mip/utils/Logging.java rename to src/main/java/eu/hbp/mip/utils/Logger.java index 9b75de636fc7c1721fca6dba59e2ce38cced1a7d..1e25d2c921f0338235bed01c2f2fcd55ab4cf94a 100644 --- a/src/main/java/eu/hbp/mip/utils/Logging.java +++ b/src/main/java/eu/hbp/mip/utils/Logger.java @@ -1,16 +1,23 @@ package eu.hbp.mip.utils; -import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.UUID; -public class Logging { - private static final Logger LOGGER = LoggerFactory.getLogger(Logging.class); +public class Logger { - public static void LogUserAction(String userName, String endpoint, String actionInfo) { - LOGGER.info(" User -> " + userName + " ," + private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(Logger.class); + private String username; + private String endpoint; + + public Logger(String username, String endpoint){ + this.username = username; + this.endpoint = endpoint; + } + + public void LogUserAction(String actionInfo) { + LOGGER.info(" User -> " + username + " ," + "Endpoint -> " + endpoint + " ," + "Info -> " + actionInfo); }