diff --git a/src/main/java/eu/hbp/mip/configuration/SecurityConfiguration.java b/src/main/java/eu/hbp/mip/configuration/SecurityConfiguration.java index 2d21b61bdc202bf858f3103c78585c481a38c7f2..69c899b8b9de71c2b747038d55141b6881d92581 100644 --- a/src/main/java/eu/hbp/mip/configuration/SecurityConfiguration.java +++ b/src/main/java/eu/hbp/mip/configuration/SecurityConfiguration.java @@ -69,186 +69,181 @@ import java.util.Map; @EnableOAuth2Client public class SecurityConfiguration extends WebSecurityConfigurerAdapter { - private static final Logger LOGGER = LoggerFactory.getLogger(SecurityConfiguration.class); - - @Autowired - private OAuth2ClientContext oauth2ClientContext; - - /** - * Enable HBP collab authentication (1) or disable it (0). Default is 1 - */ - @Value("#{'${hbp.authentication.enabled:1}'}") - private boolean authentication; - - /** - * Absolute URL to redirect to when login is required - */ - @Value("#{'${frontend.loginUrl:/login/hbp}'}") - private String loginUrl; - - /** - * Absolute URL to redirect to when logout is required - */ - @Value("#{'${hbp.client.logoutUri}'}") - private String logoutUri; - - /** - * Absolute URL to redirect to after successful login - */ - @Value("#{'${frontend.redirectAfterLoginUrl:http://frontend/home}'}") - private String frontendRedirectAfterLogin; - - /** - * Absolute URL to redirect to after logout has occurred - */ - @Value("#{'${frontend.redirectAfterLogoutUrl:/login/hbp}'}") - private String redirectAfterLogoutUrl; - - /** - * URL to revoke auth token - */ - @Value("#{'${hbp.resource.revokeTokenUri:https://services.humanbrainproject.eu/oidc/revoke}'}") - private String revokeTokenURI; - - + private static final Logger LOGGER = LoggerFactory.getLogger(SecurityConfiguration.class); + + @Autowired + private OAuth2ClientContext oauth2ClientContext; + + /** + * Enable HBP collab authentication (1) or disable it (0). Default is 1 + */ + @Value("#{'${hbp.authentication.enabled:1}'}") + private boolean authentication; + + /** + * Absolute URL to redirect to when login is required + */ + @Value("#{'${frontend.loginUrl:/login/hbp}'}") + private String loginUrl; + + /** + * Absolute URL to redirect to when logout is required + */ + @Value("#{'${hbp.client.logoutUri}'}") + private String logoutUri; + + /** + * Absolute URL to redirect to after successful login + */ + @Value("#{'${frontend.redirectAfterLoginUrl:http://frontend/home}'}") + private String frontendRedirectAfterLogin; + + /** + * Absolute URL to redirect to after logout has occurred + */ + @Value("#{'${frontend.redirectAfterLogoutUrl:/login/hbp}'}") + private String redirectAfterLogoutUrl; + + /** + * URL to revoke auth token + */ + @Value("#{'${hbp.resource.revokeTokenUri:https://services.humanbrainproject.eu/oidc/revoke}'}") + private String revokeTokenURI; + // @Autowired // private HttpServletRequest request; - @Override - protected void configure(HttpSecurity http) throws Exception { - disableCertificateValidation(); - // @formatter:off - http.addFilterBefore(new CORSFilter(), ChannelProcessingFilter.class); - - if (authentication) { - http.antMatcher("/**") - .authorizeRequests() - .antMatchers( - "/", "/login/**", "/health/**", "/info/**", "/metrics/**", "/trace/**", "/frontend/**", "/webjars/**", "/v2/api-docs", "/swagger-ui.html", "/swagger-resources/**" - ) - .permitAll() - .antMatchers("/galaxy*","/galaxy/*").hasRole("Data Manager") - //.anyRequest().authenticated() - .anyRequest().hasRole("Researcher") - .and().exceptionHandling().authenticationEntryPoint(new CustomLoginUrlAuthenticationEntryPoint(loginUrl)) - .and().logout().addLogoutHandler(authLogoutHandler()).logoutSuccessUrl(redirectAfterLogoutUrl) - .and().logout().permitAll() - .and().csrf().ignoringAntMatchers("/logout").csrfTokenRepository(csrfTokenRepository()) - .and().addFilterAfter(csrfHeaderFilter(), CsrfFilter.class) - .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class); - } - else { + @Override + protected void configure(HttpSecurity http) throws Exception { + disableCertificateValidation(); + // @formatter:off + http.addFilterBefore(new CORSFilter(), ChannelProcessingFilter.class); + + if (authentication) { + http.antMatcher("/**") + .authorizeRequests() + .antMatchers( + "/", "/login/**", "/health/**", "/info/**", "/metrics/**", "/trace/**", "/frontend/**", "/webjars/**", "/v2/api-docs", "/swagger-ui.html", "/swagger-resources/**" + ) + .permitAll() + .antMatchers("/galaxy*", "/galaxy/*").hasRole("Data Manager") + //.anyRequest().authenticated() + .anyRequest().hasRole("Researcher") + .and().exceptionHandling().authenticationEntryPoint(new CustomLoginUrlAuthenticationEntryPoint(loginUrl)) + .and().logout().addLogoutHandler(authLogoutHandler()).logoutSuccessUrl(redirectAfterLogoutUrl) + .and().logout().permitAll() + .and().csrf().ignoringAntMatchers("/logout").csrfTokenRepository(csrfTokenRepository()) + .and().addFilterAfter(csrfHeaderFilter(), CsrfFilter.class) + .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class); + } else { http.antMatcher("/**") .authorizeRequests() .antMatchers("/**").permitAll().and().csrf().disable(); - } - } - - private Filter ssoFilter() { - OAuth2ClientAuthenticationProcessingFilter hbpFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/hbp"); - OAuth2RestTemplate hbpTemplate = new OAuth2RestTemplate(hbp(), oauth2ClientContext); - hbpFilter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler(frontendRedirectAfterLogin)); - hbpFilter.setRestTemplate(hbpTemplate); - hbpFilter.setTokenServices(new UserInfoTokenServices(hbpResource().getUserInfoUri(), hbp().getClientId())); - return hbpFilter; - } - - @Bean - public FilterRegistrationBean oauth2ClientFilterRegistration( - OAuth2ClientContextFilter filter) { - FilterRegistrationBean registration = new FilterRegistrationBean(); - registration.setFilter(filter); - registration.setOrder(-100); - return registration; - } - - @Bean(name="hbp") - @ConfigurationProperties("hbp.client") - public BaseOAuth2ProtectedResourceDetails hbp() { - return new AuthorizationCodeResourceDetails(); - } - - @Bean(name="hbpResource") - @ConfigurationProperties("hbp.resource") - public ResourceServerProperties hbpResource() { - return new ResourceServerProperties(); - } - - public boolean isAuthentication() { - return authentication; - } - - public String getFrontendRedirectAfterLogin() { - return frontendRedirectAfterLogin; - } - - private Filter csrfHeaderFilter() { - return new OncePerRequestFilter() { - @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, - FilterChain filterChain) throws ServletException, IOException { - CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); - if (csrf != null) { - Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN"); - String token = csrf.getToken(); - if (cookie == null || token != null && !token.equals(cookie.getValue())) { - cookie = new Cookie("XSRF-TOKEN", token); - cookie.setPath("/"); - response.addCookie(cookie); - } - } - filterChain.doFilter(request, response); - } - }; - } - - private CsrfTokenRepository csrfTokenRepository() { - HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); - repository.setHeaderName("X-XSRF-TOKEN"); - return repository; - } - - private class CustomLogoutHandler implements LogoutHandler { - @Override - public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) { - - // Hackish way of accessing to this information... - final UserInfo userInfo = (UserInfo) httpServletRequest.getSession().getAttribute("userInfo"); - if (userInfo != null) { - userInfo.setFakeAuth(false); - } - - if (oauth2ClientContext == null || oauth2ClientContext.getAccessToken() == null) - { - return; - } - - String idToken = oauth2ClientContext.getAccessToken().getAdditionalInformation().get("id_token").toString(); - - StringBuilder query = new StringBuilder(); - query.append("{"); - query.append("\"token\":"); - query.append("\"").append(idToken).append("\""); - query.append("}"); - - try { - int responseCode = HTTPUtil.sendPost(revokeTokenURI, query.toString(), new StringBuilder()); - if (responseCode != 200) - { - LOGGER.warn("Cannot send request to OIDC server for revocation ! "); - } - else{ - LOGGER.info("Should be logged out"); - } - } catch (IOException e) { - LOGGER.warn("Cannot notify logout to OIDC server !"); - LOGGER.trace("Cannot notify logout", e); - } - - } - } - + } + } + + private Filter ssoFilter() { + OAuth2ClientAuthenticationProcessingFilter hbpFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/hbp"); + OAuth2RestTemplate hbpTemplate = new OAuth2RestTemplate(hbp(), oauth2ClientContext); + hbpFilter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler(frontendRedirectAfterLogin)); + hbpFilter.setRestTemplate(hbpTemplate); + hbpFilter.setTokenServices(new UserInfoTokenServices(hbpResource().getUserInfoUri(), hbp().getClientId())); + return hbpFilter; + } + + @Bean + public FilterRegistrationBean oauth2ClientFilterRegistration( + OAuth2ClientContextFilter filter) { + FilterRegistrationBean registration = new FilterRegistrationBean(); + registration.setFilter(filter); + registration.setOrder(-100); + return registration; + } + + @Bean(name = "hbp") + @ConfigurationProperties("hbp.client") + public BaseOAuth2ProtectedResourceDetails hbp() { + return new AuthorizationCodeResourceDetails(); + } + + @Bean(name = "hbpResource") + @ConfigurationProperties("hbp.resource") + public ResourceServerProperties hbpResource() { + return new ResourceServerProperties(); + } + + public boolean isAuthentication() { + return authentication; + } + + public String getFrontendRedirectAfterLogin() { + return frontendRedirectAfterLogin; + } + + private Filter csrfHeaderFilter() { + return new OncePerRequestFilter() { + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { + CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); + if (csrf != null) { + Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN"); + String token = csrf.getToken(); + if (cookie == null || token != null && !token.equals(cookie.getValue())) { + cookie = new Cookie("XSRF-TOKEN", token); + cookie.setPath("/"); + response.addCookie(cookie); + } + } + filterChain.doFilter(request, response); + } + }; + } + + private CsrfTokenRepository csrfTokenRepository() { + HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); + repository.setHeaderName("X-XSRF-TOKEN"); + return repository; + } + + private class CustomLogoutHandler implements LogoutHandler { + @Override + public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) { + + // Hackish way of accessing to this information... + final UserInfo userInfo = (UserInfo) httpServletRequest.getSession().getAttribute("userInfo"); + if (userInfo != null) { + userInfo.setFakeAuth(false); + } + + if (oauth2ClientContext == null || oauth2ClientContext.getAccessToken() == null) { + return; + } + + String idToken = oauth2ClientContext.getAccessToken().getAdditionalInformation().get("id_token").toString(); + + StringBuilder query = new StringBuilder(); + query.append("{"); + query.append("\"token\":"); + query.append("\"").append(idToken).append("\""); + query.append("}"); + + try { + int responseCode = HTTPUtil.sendPost(revokeTokenURI, query.toString(), new StringBuilder()); + if (responseCode != 200) { + LOGGER.warn("Cannot send request to OIDC server for revocation ! "); + } else { + LOGGER.info("Should be logged out"); + } + } catch (IOException e) { + LOGGER.warn("Cannot notify logout to OIDC server !"); + LOGGER.trace("Cannot notify logout", e); + } + + } + } + @Bean public AuthoritiesExtractor keycloakAuthoritiesExtractor() { return new KeycloakAuthoritiesExtractor(); @@ -276,68 +271,69 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { return String.join(",", authorities); } } - - - private LogoutHandler authLogoutHandler() { - return (request, response, authentication) -> { - logout(); - }; + + + private LogoutHandler authLogoutHandler() { + return (request, response, authentication) -> { + logout(); + }; } - - - public void logout() { - // POSTã™ã‚‹ãƒªã‚¯ã‚¨ã‚¹ãƒˆãƒ‘ãƒ©ãƒ¡ãƒ¼ã‚¿ãƒ¼ã‚’ä½œæˆ - UserActionLogging.LogAction("refresh token ", this.oauth2ClientContext.getAccessToken().getRefreshToken().getValue()); - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap<String, String> formParams = new LinkedMultiValueMap<>(); - formParams.add("client_id", hbp().getClientId()); + + + public void logout() { + // POSTã™ã‚‹ãƒªã‚¯ã‚¨ã‚¹ãƒˆãƒ‘ãƒ©ãƒ¡ãƒ¼ã‚¿ãƒ¼ã‚’ä½œæˆ + UserActionLogging.LogAction("refresh token ", this.oauth2ClientContext.getAccessToken().getRefreshToken().getValue()); + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap<String, String> formParams = new LinkedMultiValueMap<>(); + formParams.add("client_id", hbp().getClientId()); formParams.add("client_secret", hbp().getClientSecret()); - formParams.add("refresh_token", this.oauth2ClientContext.getAccessToken().getRefreshToken().getValue()); - // ãƒªã‚¯ã‚¨ã‚¹ãƒˆãƒ˜ãƒƒãƒ€ãƒ¼ã‚’ä½œæˆ - HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE); - // ãƒªã‚¯ã‚¨ã‚¹ãƒˆã‚’ä½œæˆ - UserActionLogging.LogAction("logoutUri is ", logoutUri); - RequestEntity<MultiValueMap<String, String>> requestEntity = - new RequestEntity<>(formParams, httpHeaders, HttpMethod.POST, - URI.create(logoutUri)); - // POSTリクエストé€ä¿¡ï¼ˆãƒã‚°ã‚¢ã‚¦ãƒˆå®Ÿè¡Œï¼‰ - - ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity, String.class); + formParams.add("refresh_token", this.oauth2ClientContext.getAccessToken().getRefreshToken().getValue()); + // ãƒªã‚¯ã‚¨ã‚¹ãƒˆãƒ˜ãƒƒãƒ€ãƒ¼ã‚’ä½œæˆ + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE); + // ãƒªã‚¯ã‚¨ã‚¹ãƒˆã‚’ä½œæˆ + UserActionLogging.LogAction("logoutUri is ", logoutUri); + RequestEntity<MultiValueMap<String, String>> requestEntity = + new RequestEntity<>(formParams, httpHeaders, HttpMethod.POST, + URI.create(logoutUri)); + // POSTリクエストé€ä¿¡ï¼ˆãƒã‚°ã‚¢ã‚¦ãƒˆå®Ÿè¡Œï¼‰ + + ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity, String.class); } - - @Value("#{'${services.keycloak.keycloakUrl}'}") - private String keycloakUrl; - + + @Value("#{'${services.keycloak.keycloakUrl}'}") + private String keycloakUrl; + // static { - // disableCertificateValidation(); + // disableCertificateValidation(); // } public void disableCertificateValidation() { - LOGGER.info("disabling certificate validation host : " + keycloakUrl); + LOGGER.info("disabling certificate validation host : " + keycloakUrl); // Create a trust manager that does not validate certificate chains - TrustManager[] trustAllCerts = new TrustManager[] { + TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } - public void checkClientTrusted(X509Certificate[] certs, String authType) {} - public void checkServerTrusted(X509Certificate[] certs, String authType) {} - } }; + + public void checkClientTrusted(X509Certificate[] certs, String authType) { + } + + public void checkServerTrusted(X509Certificate[] certs, String authType) { + } + }}; // Ignore differences between given hostname and certificate hostname HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { - + // System.out.println("Warning: URL Host: " + hostname + " vs. " - // + session.getPeerHost()); - if(hostname.equals(keycloakUrl) && session.getPeerHost().equals(keycloakUrl)) - { + // + session.getPeerHost()); + if (hostname.equals(keycloakUrl) && session.getPeerHost().equals(keycloakUrl)) { return true; - } - else - { + } else { return false; } } @@ -349,8 +345,9 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(hv); - } catch (Exception e) {} + } catch (Exception e) { + } - } + } } diff --git a/src/main/java/eu/hbp/mip/controllers/AlgorithmsApi.java b/src/main/java/eu/hbp/mip/controllers/AlgorithmsApi.java index efe69c07207cd1b247b20cc9a953a37cb8bea7b5..6b92c691a633ecbd4c16ccea813fc8b3c3533742 100644 --- a/src/main/java/eu/hbp/mip/controllers/AlgorithmsApi.java +++ b/src/main/java/eu/hbp/mip/controllers/AlgorithmsApi.java @@ -8,11 +8,13 @@ import com.google.gson.Gson; import eu.hbp.mip.controllers.galaxy.retrofit.RetroFitGalaxyClients; import eu.hbp.mip.controllers.galaxy.retrofit.RetrofitClientInstance; import eu.hbp.mip.model.AlgorithmDTO; +import eu.hbp.mip.model.UserInfo; import eu.hbp.mip.model.galaxy.WorkflowDTO; import eu.hbp.mip.utils.HTTPUtil; import eu.hbp.mip.utils.UserActionLogging; 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.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; @@ -35,6 +37,9 @@ public class AlgorithmsApi { private static final Gson gson = new Gson(); + @Autowired + private UserInfo userInfo; + @Value("#{'${services.exareme.algorithmsUrl}'}") private String exaremeAlgorithmsUrl; @@ -47,7 +52,7 @@ public class AlgorithmsApi { @ApiOperation(value = "List all algorithms", response = String.class) @RequestMapping(method = RequestMethod.GET) public ResponseEntity<List<AlgorithmDTO>> getAlgorithms() { - UserActionLogging.LogAction("List all algorithms", ""); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List all algorithms", ""); List<AlgorithmDTO> exaremeAlgorithms = getExaremeAlgorithms(); List<AlgorithmDTO> galaxyAlgorithms = getGalaxyWorkflows(); @@ -56,13 +61,13 @@ public class AlgorithmsApi { if (exaremeAlgorithms != null) { algorithms.addAll(exaremeAlgorithms); } else { - UserActionLogging.LogAction("List all algorithms", + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List all algorithms", "Getting exareme algorithms failed and returned null"); } if (galaxyAlgorithms != null) { algorithms.addAll(galaxyAlgorithms); } else { - UserActionLogging.LogAction("List all algorithms", + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List all algorithms", "Getting galaxy workflows failed and returned null"); } @@ -75,7 +80,7 @@ public class AlgorithmsApi { * @return a list of AlgorithmDTOs or null if something fails */ public List<AlgorithmDTO> getExaremeAlgorithms() { - UserActionLogging.LogAction("List exareme algorithms", ""); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List exareme algorithms", ""); List<AlgorithmDTO> algorithms = new LinkedList<>(); // Get exareme algorithms @@ -85,11 +90,11 @@ public class AlgorithmsApi { algorithms = gson.fromJson(response.toString(), algorithms.getClass()); } catch (IOException e) { - UserActionLogging.LogAction("List exareme algorithms", "An exception occurred: " + e.getMessage()); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List exareme algorithms", "An exception occurred: " + e.getMessage()); return null; } - UserActionLogging.LogAction("List exareme algorithms", + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List exareme algorithms", "Completed, returned " + algorithms.size() + " algorithms."); return algorithms; } @@ -100,7 +105,7 @@ public class AlgorithmsApi { * @return a list of AlgorithmDTOs or null if something fails */ public List<AlgorithmDTO> getGalaxyWorkflows() { - UserActionLogging.LogAction("List Galaxy workflows", ""); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List Galaxy workflows", ""); List<Workflow> workflowList = null; try { @@ -110,7 +115,7 @@ public class AlgorithmsApi { workflowList = new ArrayList<>(workflowsClient.getWorkflows()); } catch (Exception e) { - UserActionLogging.LogAction("List Galaxy workflows", "Error when calling list galaxy workflows: " + e.getMessage()); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List Galaxy workflows", "Error when calling list galaxy workflows: " + e.getMessage()); return null; } @@ -130,28 +135,28 @@ public class AlgorithmsApi { } else { // Something unexpected happened String msgErr = gson.toJson(response.errorBody()); - UserActionLogging.LogAction("List Galaxy workflows", "Error Response: " + msgErr); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List Galaxy workflows", "Error Response: " + msgErr); return null; } } catch (Exception e) { - UserActionLogging.LogAction("List Galaxy workflows", "An exception occurred: " + e.getMessage()); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List Galaxy workflows", "An exception occurred: " + e.getMessage()); return null; } } - UserActionLogging.LogAction("List Galaxy workflows", "Workflows fetched: " + workflows.size()); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List Galaxy workflows", "Workflows fetched: " + workflows.size()); // Convert the workflows to algorithms List<AlgorithmDTO> algorithms = new LinkedList<>(); for (WorkflowDTO workflow : workflows) { - UserActionLogging.LogAction("List Galaxy workflows", "Converting workflow: " + workflow); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List Galaxy workflows", "Converting workflow: " + workflow); algorithms.add(workflow.convertToAlgorithmDTO()); - UserActionLogging.LogAction("List Galaxy workflows", + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List Galaxy workflows", "Converted algorithm: " + algorithms.get(algorithms.size() - 1)); } - UserActionLogging.LogAction("List Galaxy workflows", "Completed!"); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List Galaxy workflows", "Completed!"); return algorithms; } } diff --git a/src/main/java/eu/hbp/mip/controllers/ArticlesApi.java b/src/main/java/eu/hbp/mip/controllers/ArticlesApi.java index 963b181576f0626620d76b3a0370dcb840767778..2e5fb3dc551a96cf0fd34b89cd4d159d7fcbb67f 100644 --- a/src/main/java/eu/hbp/mip/controllers/ArticlesApi.java +++ b/src/main/java/eu/hbp/mip/controllers/ArticlesApi.java @@ -66,7 +66,7 @@ public class ArticlesApi { } } } - UserActionLogging.LogAction("Get articles", "id : Get All articles"); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Get articles", "id : Get All articles"); return ResponseEntity.ok(articles); } @@ -127,7 +127,7 @@ public class ArticlesApi { } articleRepository.save(article); - UserActionLogging.LogAction("Created article", "id : " + article.getSlug()); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Created article", "id : " + article.getSlug()); return new ResponseEntity<>(HttpStatus.CREATED); } @@ -137,7 +137,7 @@ public class ArticlesApi { public ResponseEntity<Article> getAnArticle( @ApiParam(value = "slug", required = true) @PathVariable("slug") String slug ) { - UserActionLogging.LogAction("Getting an article", "id : " + slug); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Getting an article", "id : " + slug); User user = userInfo.getUser(); Article article; @@ -165,7 +165,7 @@ public class ArticlesApi { @ApiParam(value = "slug", required = true) @PathVariable("slug") String slug, @RequestBody @ApiParam(value = "Article to update", required = true) @Valid Article article ) { - UserActionLogging.LogAction("Update an article", "id : " + slug); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Update an article", "id : " + slug); User user = userInfo.getUser(); diff --git a/src/main/java/eu/hbp/mip/controllers/ExperimentApi.java b/src/main/java/eu/hbp/mip/controllers/ExperimentApi.java index 943605b66736f71e47bac8c44989bf88e7b6140c..722a5a9b04f2049b54e8eabc879ffeaa12b94573 100644 --- a/src/main/java/eu/hbp/mip/controllers/ExperimentApi.java +++ b/src/main/java/eu/hbp/mip/controllers/ExperimentApi.java @@ -51,6 +51,9 @@ public class ExperimentApi { private static final Gson gson = new Gson(); + @Autowired + private UserInfo userInfo; + private static final Gson gsonOnlyExposed = new GsonBuilder().serializeNulls() .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").excludeFieldsWithoutExposeAnnotation().create(); @@ -69,9 +72,6 @@ public class ExperimentApi { @Value("#{'${services.galaxy.galaxyApiKey}'}") private String galaxyApiKey; - @Autowired - private UserInfo userInfo; - @Autowired private ModelRepository modelRepository; @@ -323,7 +323,7 @@ public class ExperimentApi { experiment.setFinished(new Date()); experimentRepository.save(experiment); - UserActionLogging.LogThreadAction("Experiment finished!", ""); + UserActionLogging.LogAction("Experiment finished!", ""); } /* -------------------------------------- EXAREME CALLS ---------------------------------------------------------*/ @@ -357,17 +357,17 @@ public class ExperimentApi { UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run exareme algorithm", "Starting exareme execution thread"); new Thread(() -> { - // ATTENTION: Inside the Thread only LogThreadAction should be used, not LogAction! - UserActionLogging.LogThreadAction("Run exareme algorithm", + // ATTENTION: Inside the Thread only LogAction should be used, not LogAction! + UserActionLogging.LogAction("Run exareme algorithm", "Thread started!"); try { - UserActionLogging.LogThreadAction("Run exareme algorithm", + UserActionLogging.LogAction("Run exareme algorithm", "Thread started!"); StringBuilder results = new StringBuilder(); int code = HTTPUtil.sendPost(url, body, results); - UserActionLogging.LogThreadAction("Run exareme algorithm", + UserActionLogging.LogAction("Run exareme algorithm", "Algorithm finished with code: " + code); // Results are stored in the experiment object @@ -375,18 +375,18 @@ public class ExperimentApi { experiment.setHasError(code >= 400); experiment.setHasServerError(code >= 500); } catch (Exception e) { - UserActionLogging.LogThreadAction("Run exareme algorithm", + UserActionLogging.LogAction("Run exareme algorithm", "There was an exception: " + e.getMessage()); experiment.setHasError(true); experiment.setHasServerError(true); experiment.setResult(e.getMessage()); } - UserActionLogging.LogThreadAction("Run exareme algorithm", + UserActionLogging.LogAction("Run exareme algorithm", "Finished the experiment: " + experiment.toString()); finishExperiment(experiment); - UserActionLogging.LogThreadAction("Run exareme algorithm", + UserActionLogging.LogAction("Run exareme algorithm", "Finished!"); }).start(); @@ -524,44 +524,44 @@ public class ExperimentApi { UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Update workflow experiment", "Starting Thread..."); new Thread(() -> { while (true) { - // ATTENTION: Inside the Thread only LogThreadAction should be used, not LogAction! - UserActionLogging.LogThreadAction("Update workflow experiment", "Thread is running..."); + // ATTENTION: Inside the Thread only LogAction should be used, not LogAction! + UserActionLogging.LogAction("Update workflow experiment", "Thread is running..."); try { sleep(2000); } catch (InterruptedException e) { - UserActionLogging.LogThreadAction("Update workflow experiment", + UserActionLogging.LogAction("Update workflow experiment", "Sleep was disrupted: " + e.getMessage()); } - UserActionLogging.LogThreadAction("Update workflow experiment", + UserActionLogging.LogAction("Update workflow experiment", "Fetching status for experiment Id: " + experiment.getUuid()); String state = getWorkflowStatus(experiment.getWorkflowHistoryId()); - UserActionLogging.LogThreadAction("Update workflow experiment", "State is: " + state); + UserActionLogging.LogAction("Update workflow experiment", "State is: " + state); switch (state) { case "running": // Do nothing, when the experiment is created the status is set to running - UserActionLogging.LogThreadAction("Update workflow experiment", + UserActionLogging.LogAction("Update workflow experiment", "Workflow is still running."); break; case "completed": // Get only the job result that is visible List<GalaxyWorkflowResult> workflowJobsResults = getWorkflowResults(experiment.getWorkflowHistoryId()); - UserActionLogging.LogThreadAction("Update workflow experiment", + UserActionLogging.LogAction("Update workflow experiment", "Results are: " + workflowJobsResults.toString()); boolean resultFound = false; for (GalaxyWorkflowResult jobResult : workflowJobsResults) { if (jobResult.getVisible()) { - UserActionLogging.LogThreadAction("Update workflow experiment", + UserActionLogging.LogAction("Update workflow experiment", "Visible result are: " + jobResult.getId()); String result = getWorkflowResultBody(experiment.getWorkflowHistoryId(), jobResult.getId()); - UserActionLogging.LogThreadAction("Update workflow experiment", "Result: " + result); + UserActionLogging.LogAction("Update workflow experiment", "Result: " + result); if (result == null) { experiment.setHasError(true); experiment.setHasServerError(true); @@ -573,7 +573,7 @@ public class ExperimentApi { } if (!resultFound) { // If there is no visible result - UserActionLogging.LogThreadAction("Update workflow experiment", "No visible result"); + UserActionLogging.LogAction("Update workflow experiment", "No visible result"); experiment.setResult("[" + new ErrorResponse("The workflow has no visible result.").toString() + "]"); experiment.setHasError(true); experiment.setHasServerError(true); @@ -585,18 +585,18 @@ public class ExperimentApi { case "error": // Get the job result that failed workflowJobsResults = getWorkflowResults(experiment.getWorkflowHistoryId()); - UserActionLogging.LogThreadAction("Update workflow experiment", + UserActionLogging.LogAction("Update workflow experiment", "Error results are: " + workflowJobsResults.toString()); boolean failedJobFound = false; for (GalaxyWorkflowResult jobResult : workflowJobsResults) { if (jobResult.getState().equals("error")) { - UserActionLogging.LogThreadAction("Update workflow experiment", + UserActionLogging.LogAction("Update workflow experiment", "Failed job is: " + jobResult.getId()); String result = getWorkflowJobError(jobResult.getId()); - UserActionLogging.LogThreadAction("Update workflow experiment", "Job result: " + result); + UserActionLogging.LogAction("Update workflow experiment", "Job result: " + result); if (result == null) { experiment.setHasError(true); experiment.setHasServerError(true); @@ -608,7 +608,7 @@ public class ExperimentApi { } if (!failedJobFound) { // If there is no visible failed job - UserActionLogging.LogThreadAction("Update workflow experiment", "No failed result"); + UserActionLogging.LogAction("Update workflow experiment", "No failed result"); experiment.setResult("[" + new ErrorResponse("The workflow has no failed result.").toString() + "]"); experiment.setHasError(true); experiment.setHasServerError(true); @@ -626,7 +626,7 @@ public class ExperimentApi { // If result exists return if (experiment.getResult() != null) { - UserActionLogging.LogThreadAction("Update workflow experiment", + UserActionLogging.LogAction("Update workflow experiment", "Result exists: " + experiment.getResult()); return; } @@ -643,8 +643,8 @@ public class ExperimentApi { * "completed" -> When the workflow completed successfully */ public String getWorkflowStatus(String historyId) { - // ATTENTION: This function is used from a Thread. Only LogThreadAction should be used, not LogAction! - UserActionLogging.LogThreadAction("Get workflow status", " History Id : " + historyId); + // ATTENTION: This function is used from a Thread. Only LogAction should be used, not LogAction! + UserActionLogging.LogAction("Get workflow status", " History Id : " + historyId); // Create the request client RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); @@ -654,15 +654,15 @@ public class ExperimentApi { try { Response<Object> response = call.execute(); if (response.code() >= 400) { - UserActionLogging.LogThreadAction("Get workflow status", " Response code: " + UserActionLogging.LogAction("Get workflow status", " Response code: " + response.code() + "" + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return "internalError"; } result = new Gson().toJson(response.body()); - UserActionLogging.LogThreadAction("Get workflow status", " Result: " + result); + UserActionLogging.LogAction("Get workflow status", " Result: " + result); } catch (IOException e) { - UserActionLogging.LogThreadAction("Get workflow status" + UserActionLogging.LogAction("Get workflow status" , " An exception happened: " + e.getMessage()); return "internalError"; } @@ -672,12 +672,12 @@ public class ExperimentApi { JSONObject resultJson = new JSONObject(result); state = resultJson.getString("state"); } catch (JSONException e) { - UserActionLogging.LogThreadAction("Get workflow status" + UserActionLogging.LogAction("Get workflow status" , " An exception happened: " + e.getMessage()); return "internalError"; } - UserActionLogging.LogThreadAction("Get workflow status", " Completed!"); + UserActionLogging.LogAction("Get workflow status", " Completed!"); switch (state) { case "ok": return "completed"; @@ -698,7 +698,7 @@ public class ExperimentApi { * @return a List<GalaxyWorkflowResult> or null when an error occurred */ public List<GalaxyWorkflowResult> getWorkflowResults(String historyId) { - UserActionLogging.LogThreadAction("Get workflow results", " historyId : " + historyId); + UserActionLogging.LogAction("Get workflow results", " historyId : " + historyId); RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); Call<List<GalaxyWorkflowResult>> call = service.getWorkflowResultsFromGalaxy(historyId, galaxyApiKey); @@ -707,20 +707,20 @@ public class ExperimentApi { try { Response<List<GalaxyWorkflowResult>> response = call.execute(); if (response.code() >= 400) { - UserActionLogging.LogThreadAction("Get workflow results", " Response code: " + UserActionLogging.LogAction("Get workflow results", " Response code: " + response.code() + "" + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return null; } getGalaxyWorkflowResultList = response.body(); - UserActionLogging.LogThreadAction("Get workflow results", " Result: " + response.body()); + UserActionLogging.LogAction("Get workflow results", " Result: " + response.body()); } catch (IOException e) { - UserActionLogging.LogThreadAction("Get workflow results" + UserActionLogging.LogAction("Get workflow results" , " An exception happened: " + e.getMessage()); return null; } - UserActionLogging.LogThreadAction("Get workflow results", " Completed!"); + UserActionLogging.LogAction("Get workflow results", " Completed!"); return getGalaxyWorkflowResultList; } @@ -731,7 +731,7 @@ public class ExperimentApi { * @return the result of the specific workflow job, null if there was an error */ public String getWorkflowResultBody(String historyId, String contentId) { - UserActionLogging.LogThreadAction("Get workflow results Body", " historyId : " + historyId); + UserActionLogging.LogAction("Get workflow results Body", " historyId : " + historyId); RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); Call<Object> call = @@ -741,20 +741,20 @@ public class ExperimentApi { try { Response<Object> response = call.execute(); if (response.code() >= 400) { - UserActionLogging.LogThreadAction("Get workflow results Body", " Response code: " + UserActionLogging.LogAction("Get workflow results Body", " Response code: " + response.code() + "" + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return null; } resultJson = new Gson().toJson(response.body()); - UserActionLogging.LogThreadAction("Get workflow results Body", " Result: " + resultJson); + UserActionLogging.LogAction("Get workflow results Body", " Result: " + resultJson); } catch (IOException e) { - UserActionLogging.LogThreadAction("Get workflow results Body", + UserActionLogging.LogAction("Get workflow results Body", " An exception happened: " + e.getMessage()); return null; } - UserActionLogging.LogThreadAction("Get workflow results Body", " Completed!"); + UserActionLogging.LogAction("Get workflow results Body", " Completed!"); return resultJson; } @@ -764,7 +764,7 @@ public class ExperimentApi { * @return the error that was produced or null if an error occurred */ public String getWorkflowJobError(String jobId) { - UserActionLogging.LogThreadAction("Get workflow job error", " jobId : " + jobId); + UserActionLogging.LogAction("Get workflow job error", " jobId : " + jobId); RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); Call<Object> callError = service.getErrorMessageOfWorkflowFromGalaxy(jobId, galaxyApiKey); @@ -774,7 +774,7 @@ public class ExperimentApi { try { Response<Object> response = callError.execute(); if (response.code() >= 400) { - UserActionLogging.LogThreadAction("Get workflow job error", "Response code: " + UserActionLogging.LogAction("Get workflow job error", "Response code: " + response.code() + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return null; } @@ -784,19 +784,19 @@ public class ExperimentApi { JsonElement jsonElement = new JsonParser().parse(jsonString); JsonObject rootObject = jsonElement.getAsJsonObject(); fullError = rootObject.get("stderr").getAsString(); - UserActionLogging.LogThreadAction("Get workflow job error", "Error: " + fullError); + UserActionLogging.LogAction("Get workflow job error", "Error: " + fullError); String[] arrOfStr = fullError.split("ValueError", 0); String specError = arrOfStr[arrOfStr.length - 1]; returnError = specError.substring(1); - UserActionLogging.LogThreadAction("Get workflow job error", "Parsed Error: " + returnError); + UserActionLogging.LogAction("Get workflow job error", "Parsed Error: " + returnError); } catch (IOException e) { - UserActionLogging.LogThreadAction("Get workflow job error", "Exception: " + e.getMessage()); + UserActionLogging.LogAction("Get workflow job error", "Exception: " + e.getMessage()); return null; } - UserActionLogging.LogThreadAction("Get workflow job error", "Completed successfully!"); + UserActionLogging.LogAction("Get workflow job error", "Completed successfully!"); return returnError; } diff --git a/src/main/java/eu/hbp/mip/controllers/FilesAPI.java b/src/main/java/eu/hbp/mip/controllers/FilesAPI.java index 5acdb38ca88a851cb96a3c375c51165b1e157531..3b4ec96ab88749ea8cfb64777c8bd79f090fa12d 100644 --- a/src/main/java/eu/hbp/mip/controllers/FilesAPI.java +++ b/src/main/java/eu/hbp/mip/controllers/FilesAPI.java @@ -36,12 +36,12 @@ public class FilesAPI { public ResponseEntity<Void> getProtectedFile( @ApiParam(value = "filename", required = true) @PathVariable("filename") String filename ) { - UserActionLogging.LogAction("Get protected file", " filename : " + filename); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Get protected file", " filename : " + filename); String filepath = "/protected/" + filename; String user = userInfo.getUser().getUsername(); String time = LocalDateTime.now().toString(); - UserActionLogging.LogAction("User " + user + " downloaded " + filepath, ""); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Downloaded " + filepath, ""); HttpHeaders headers = new HttpHeaders(); headers.add("X-Accel-Redirect", filepath); diff --git a/src/main/java/eu/hbp/mip/controllers/MiningApi.java b/src/main/java/eu/hbp/mip/controllers/MiningApi.java index 3adcc6269e8120147c6c81367c91b928c1d5d486..fba6ecf93718de3a4a4eea7b34af56e81e8e23a0 100644 --- a/src/main/java/eu/hbp/mip/controllers/MiningApi.java +++ b/src/main/java/eu/hbp/mip/controllers/MiningApi.java @@ -51,7 +51,7 @@ public class MiningApi { @ApiOperation(value = "Create a histogram on Exareme", response = String.class) @RequestMapping(value = "/histograms", method = RequestMethod.POST) public ResponseEntity runExaremeHistograms(@RequestBody List<HashMap<String, String>> queryList) { - UserActionLogging.LogAction("Run an histogram", ""); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run an histogram", ""); String query = gson.toJson(queryList); String url = queryExaremeUrl + "/" + "MULTIPLE_HISTOGRAMS"; @@ -69,7 +69,7 @@ public class MiningApi { @ApiOperation(value = "Create a descriptive statistic on Exareme", response = String.class) @RequestMapping(value = "/descriptive_stats", method = RequestMethod.POST) public ResponseEntity runExaremeDescriptiveStats(@RequestBody List<HashMap<String, String>> queryList) { - UserActionLogging.LogAction("Run descriptive stats", ""); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run descriptive stats", ""); String query = gson.toJson(queryList); String url = queryExaremeUrl + "/" + "DESCRIPTIVE_STATS"; @@ -87,7 +87,7 @@ public class MiningApi { @ApiOperation(value = "Check if a formula is valid", response = String.class) @RequestMapping(value = "/checkFormula", method = RequestMethod.POST) public ResponseEntity checkFormulaValidity(String formula) { - UserActionLogging.LogAction("Check Formula Validity", ""); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Check Formula Validity", ""); return ResponseEntity.ok(""); } diff --git a/src/main/java/eu/hbp/mip/controllers/ModelsApi.java b/src/main/java/eu/hbp/mip/controllers/ModelsApi.java index 02ee9ac6b25b353876566a7261a7e6deba962574..633c01783d340a9b76bd71723fc62dd16db16fb1 100644 --- a/src/main/java/eu/hbp/mip/controllers/ModelsApi.java +++ b/src/main/java/eu/hbp/mip/controllers/ModelsApi.java @@ -54,7 +54,7 @@ public class ModelsApi { @ApiParam(value = "Only ask own models") @RequestParam(value = "own", required = false) Boolean own, @ApiParam(value = "Only ask published models") @RequestParam(value = "valid", required = false) Boolean valid ) { - UserActionLogging.LogAction("Get models",""); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Get models",""); User user = userInfo.getUser(); @@ -98,7 +98,7 @@ public class ModelsApi { @RequestBody @ApiParam(value = "Model to create", required = true) Model model ) { - UserActionLogging.LogAction("Create a model",""); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Create a model",""); User user = userInfo.getUser(); @@ -129,7 +129,7 @@ public class ModelsApi { } modelRepository.save(model); - UserActionLogging.LogAction("Model saved (also saved model.config and model.query)"," id : " + model.getSlug()); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Model saved (also saved model.config and model.query)"," id : " + model.getSlug()); return ResponseEntity.status(HttpStatus.CREATED).body(model); } @@ -192,7 +192,7 @@ public class ModelsApi { public ResponseEntity<Model> getAModel( @ApiParam(value = "slug", required = true) @PathVariable("slug") String slug ) { - UserActionLogging.LogAction("Get a model", " id : " + slug); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Get a model", " id : " + slug); User user = userInfo.getUser(); @@ -224,7 +224,7 @@ public class ModelsApi { @ApiParam(value = "slug", required = true) @PathVariable("slug") String slug, @RequestBody @ApiParam(value = "Model to update", required = true) Model model ) { - UserActionLogging.LogAction("Update a model", " id : "+ slug); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Update a model", " id : "+ slug); User user = userInfo.getUser(); Model oldModel = modelRepository.findOne(slug); @@ -269,7 +269,7 @@ public class ModelsApi { datasetRepository.save(model.getDataset()); modelRepository.save(model); - UserActionLogging.LogAction("Model updated (also saved/updated model.config and model.query)", " id : "+ slug); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Model updated (also saved/updated model.config and model.query)", " id : "+ slug); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } diff --git a/src/main/java/eu/hbp/mip/controllers/PathologiesApi.java b/src/main/java/eu/hbp/mip/controllers/PathologiesApi.java index 27f635d3278e9a2990489b4a3c01bd0d9851c34a..5b8b4421a2e1f96d73b045582847810ae880e02d 100644 --- a/src/main/java/eu/hbp/mip/controllers/PathologiesApi.java +++ b/src/main/java/eu/hbp/mip/controllers/PathologiesApi.java @@ -5,6 +5,7 @@ package eu.hbp.mip.controllers; import com.fasterxml.jackson.core.type.TypeReference; +import eu.hbp.mip.model.UserInfo; import eu.hbp.mip.utils.CustomResourceLoader; import io.swagger.annotations.Api; import org.springframework.beans.factory.annotation.Autowired; @@ -27,9 +28,12 @@ import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; @Api(value = "/pathologies") public class PathologiesApi { + @Autowired + private UserInfo userInfo; + @RequestMapping(name = "/pathologies", method = RequestMethod.GET) public String getPathologies() { - UserActionLogging.LogAction("load the pathologies", ""); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "load the pathologies", ""); return loadPathologies(); } diff --git a/src/main/java/eu/hbp/mip/controllers/SecurityApi.java b/src/main/java/eu/hbp/mip/controllers/SecurityApi.java index 0f93c437ea8477000e1881815cce984eca36f3f8..ee24f17d97573ffe2a416c6cc4cba766a94e4cbd 100644 --- a/src/main/java/eu/hbp/mip/controllers/SecurityApi.java +++ b/src/main/java/eu/hbp/mip/controllers/SecurityApi.java @@ -46,7 +46,7 @@ public class SecurityApi { public Object user(Principal principal, HttpServletResponse response) { ObjectMapper mapper = new ObjectMapper(); - UserActionLogging.LogAction("get user from /user",""); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "get user from /user",""); try { String userJSON = mapper.writeValueAsString(userInfo.getUser()); Cookie cookie = new Cookie("user", URLEncoder.encode(userJSON, "UTF-8")); @@ -78,7 +78,7 @@ public class SecurityApi { userRepository.save(user); } - UserActionLogging.LogAction("user agreeNDA",""); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "user agreeNDA",""); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @@ -113,7 +113,7 @@ public class SecurityApi { JsonObject object = new JsonObject(); object.addProperty("authorization", stringEncoded); object.addProperty("context", galaxyContext); - UserActionLogging.LogAction("get galaxy information",""); + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "get galaxy information",""); return ResponseEntity.ok(gson.toJson(object)); } diff --git a/src/main/java/eu/hbp/mip/controllers/StatsApi.java b/src/main/java/eu/hbp/mip/controllers/StatsApi.java index a92adecde01cb383ce4c677b2476b27afa862437..56d25679321043aec77613e0d028c0332ef49604 100644 --- a/src/main/java/eu/hbp/mip/controllers/StatsApi.java +++ b/src/main/java/eu/hbp/mip/controllers/StatsApi.java @@ -3,16 +3,15 @@ */ package eu.hbp.mip.controllers; -import eu.hbp.mip.utils.UserActionLogging; + import eu.hbp.mip.model.GeneralStats; +import eu.hbp.mip.model.UserInfo; import eu.hbp.mip.repositories.ArticleRepository; import eu.hbp.mip.repositories.UserRepository; +import eu.hbp.mip.utils.UserActionLogging; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -24,19 +23,20 @@ import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; @RequestMapping(value = "/stats", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/stats", description = "the stats API") public class StatsApi { - - @Autowired private UserRepository userRepository; + @Autowired + private UserInfo userInfo; + @Autowired private ArticleRepository articleRepository; @ApiOperation(value = "Get general statistics", response = GeneralStats.class) @RequestMapping(method = RequestMethod.GET) - public ResponseEntity<GeneralStats> getGeneralStatistics() { - UserActionLogging.LogAction("Get statistics (count on users, articles and variables)",""); + public ResponseEntity<GeneralStats> getGeneralStatistics() { + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Get statistics (count on users, articles and variables)", ""); GeneralStats stats = new GeneralStats(); diff --git a/src/main/java/eu/hbp/mip/controllers/UsersApi.java b/src/main/java/eu/hbp/mip/controllers/UsersApi.java index ed3104eb807ab844c25f20df69fac2c200ed0bf2..0620c34e444315dc6c472c304539f9c6b5d8d28d 100644 --- a/src/main/java/eu/hbp/mip/controllers/UsersApi.java +++ b/src/main/java/eu/hbp/mip/controllers/UsersApi.java @@ -4,12 +4,13 @@ package eu.hbp.mip.controllers; -import eu.hbp.mip.utils.UserActionLogging; -import io.swagger.annotations.*; import eu.hbp.mip.model.User; +import eu.hbp.mip.model.UserInfo; import eu.hbp.mip.repositories.UserRepository; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import eu.hbp.mip.utils.UserActionLogging; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; @@ -27,12 +28,15 @@ public class UsersApi { @Autowired private UserRepository userRepository; + @Autowired + private UserInfo userInfo; + @ApiOperation(value = "Get a user", response = User.class) @RequestMapping(value = "/{username}", method = RequestMethod.GET) public ResponseEntity<User> getAUser( @ApiParam(value = "username", required = true) @PathVariable("username") String username - ) { - UserActionLogging.LogAction("Get a user",""); + ) { + UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Get a user", ""); return ResponseEntity.ok(userRepository.findOne(username)); } diff --git a/src/main/java/eu/hbp/mip/utils/UserActionLogging.java b/src/main/java/eu/hbp/mip/utils/UserActionLogging.java index c4d7305b9a5924af29a41c9c4836004f21292f17..a0ec02277d0249c92577a3fad044de506ab7b039 100644 --- a/src/main/java/eu/hbp/mip/utils/UserActionLogging.java +++ b/src/main/java/eu/hbp/mip/utils/UserActionLogging.java @@ -1,32 +1,22 @@ package eu.hbp.mip.utils; -import eu.hbp.mip.model.UserInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.context.SecurityContextHolder; public class UserActionLogging { private static final Logger LOGGER = LoggerFactory.getLogger(UserActionLogging.class); - public static void LogAction(String actionName, String actionIdInfo) - { - LOGGER.info( "Called endpoint: " + actionName - + " info: " + actionIdInfo); - } - - public static void LogUserAction(String userName, String actionName, String actionInfo) - { - LOGGER.info( " User : " + public static void LogUserAction(String userName, String actionName, String actionInfo) { + LOGGER.info(" User : " + userName + " called endpoint: " + actionName + " info: " + actionInfo); } - // Used from Threads because LogAction won't work. - public static void LogThreadAction(String actionName, String actionIdInfo) - { - LOGGER.info( "Thread -->" + actionName + " info: " + actionIdInfo); - } + // Usually, used from Threads because threads can't get userName. + // Also used when a user is not authorised yet + public static void LogAction(String actionName, String actionIdInfo) { + LOGGER.info("Action -->" + actionName + " info: " + actionIdInfo); + } } diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml index efd7a874adcd194ee0145465dca9c08c1f3f5c5d..d4a1e4765b7d25b98ccaf68141e28784a6ff09cb 100644 --- a/src/main/resources/logback.xml +++ b/src/main/resources/logback.xml @@ -1,6 +1,6 @@ <configuration> <appender name="FILE1" class="ch.qos.logback.core.FileAppender"> - <file>logs/log1.txt</file> + <file>logs/portal-backend.txt</file> <append>true</append> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %msg%n</pattern>