From 3a79a62cfbb2a4c4fde4f50fb81c54584c26ffc0 Mon Sep 17 00:00:00 2001 From: "Lam, Doris T (319E)" Date: Mon, 2 Aug 2021 14:10:42 -0700 Subject: [PATCH 1/5] try generating token with permissions info included --- example/example.gradle | 4 +- .../example/config/ExampleSecurityConfig.java | 2 + .../mms/example/config/LoggingFilter.java | 46 +++++ .../mms/example/controllers/MMS5Auth.java | 180 ++++++++++++++++++ .../BranchGroupPermRepository.java | 2 + .../rdb/repositories/BranchRepository.java | 3 + .../BranchUserPermRepository.java | 3 + .../ProjectGroupPermRepository.java | 2 + .../rdb/repositories/ProjectRepository.java | 1 + .../ProjectUserPermRepository.java | 2 + 10 files changed, 244 insertions(+), 1 deletion(-) create mode 100644 example/src/main/java/org/openmbee/mms/example/config/LoggingFilter.java create mode 100644 example/src/main/java/org/openmbee/mms/example/controllers/MMS5Auth.java diff --git a/example/example.gradle b/example/example.gradle index 87b646db8..e85b25479 100644 --- a/example/example.gradle +++ b/example/example.gradle @@ -26,11 +26,13 @@ dependencies { project(':search'), project(':storage'), project(':groups'), + project(':rdb'), 'org.springframework.boot:spring-boot-starter-web', 'org.postgresql:postgresql:42.2.5', //'mysql:mysql-connector-java:8.0.17', 'org.springdoc:springdoc-openapi-ui:1.3.1', - 'org.springdoc:springdoc-openapi-security:1.3.1' + 'org.springdoc:springdoc-openapi-security:1.3.1', + 'io.jsonwebtoken:jjwt-api:0.10.5' ) testImplementation( diff --git a/example/src/main/java/org/openmbee/mms/example/config/ExampleSecurityConfig.java b/example/src/main/java/org/openmbee/mms/example/config/ExampleSecurityConfig.java index c0cd41795..08b7989c9 100644 --- a/example/src/main/java/org/openmbee/mms/example/config/ExampleSecurityConfig.java +++ b/example/src/main/java/org/openmbee/mms/example/config/ExampleSecurityConfig.java @@ -12,6 +12,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.access.ExceptionTranslationFilter; +import org.springframework.security.web.authentication.AnonymousAuthenticationFilter; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; @@ -40,6 +41,7 @@ public void configure(HttpSecurity http) throws Exception { http.csrf().disable().authorizeRequests().anyRequest().permitAll().and().httpBasic(); http.headers().cacheControl(); http.addFilterAfter(corsFilter(), ExceptionTranslationFilter.class); + http.addFilterAfter(new LoggingFilter(), AnonymousAuthenticationFilter.class); authSecurityConfig.setAuthConfig(http); } diff --git a/example/src/main/java/org/openmbee/mms/example/config/LoggingFilter.java b/example/src/main/java/org/openmbee/mms/example/config/LoggingFilter.java new file mode 100644 index 000000000..c7b3c6103 --- /dev/null +++ b/example/src/main/java/org/openmbee/mms/example/config/LoggingFilter.java @@ -0,0 +1,46 @@ +package org.openmbee.mms.example.config; + +import java.io.IOException; +import java.util.UUID; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +public class LoggingFilter implements Filter { + private final Logger LOGGER = LoggerFactory.getLogger(LoggingFilter.class); + + @Override + public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) + throws IOException, ServletException { + String corr = UUID.randomUUID().toString(); + long time = System.currentTimeMillis(); + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + String user = "anonymousUser"; + if (auth != null) { + user = auth.getName(); + } + HttpServletRequest r = (HttpServletRequest) req; + String query = r.getQueryString(); + query = query == null ? "" : ("?" + query); + LOGGER.info("req - {} - {} - {} - {}", user, r.getMethod(), r.getRequestURI() + query, corr); + + chain.doFilter(req, resp); + + time = System.currentTimeMillis() - time; + HttpServletResponse res = (HttpServletResponse)resp; + auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth != null) { + user = auth.getName(); + } + LOGGER.info("res - {} - {} - {} - {} - {} - {}ms ", user, r.getMethod(), r.getRequestURI() + query, corr, res.getStatus(), time); + } +} + diff --git a/example/src/main/java/org/openmbee/mms/example/controllers/MMS5Auth.java b/example/src/main/java/org/openmbee/mms/example/controllers/MMS5Auth.java new file mode 100644 index 000000000..66f4e09fb --- /dev/null +++ b/example/src/main/java/org/openmbee/mms/example/controllers/MMS5Auth.java @@ -0,0 +1,180 @@ +package org.openmbee.mms.example.controllers; + +import io.swagger.v3.oas.annotations.security.SecurityRequirements; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.crypto.SecretKey; +import org.openmbee.mms.authenticator.security.JwtAuthenticationRequest; +import org.openmbee.mms.authenticator.security.JwtAuthenticationResponse; +import org.openmbee.mms.data.domains.global.Branch; +import org.openmbee.mms.data.domains.global.BranchGroupPerm; +import org.openmbee.mms.data.domains.global.BranchUserPerm; +import org.openmbee.mms.data.domains.global.Project; +import org.openmbee.mms.data.domains.global.ProjectGroupPerm; +import org.openmbee.mms.data.domains.global.ProjectUserPerm; +import org.openmbee.mms.rdb.repositories.BranchGroupPermRepository; +import org.openmbee.mms.rdb.repositories.BranchRepository; +import org.openmbee.mms.rdb.repositories.BranchUserPermRepository; +import org.openmbee.mms.rdb.repositories.ProjectGroupPermRepository; +import org.openmbee.mms.rdb.repositories.ProjectRepository; +import org.openmbee.mms.rdb.repositories.ProjectUserPermRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.MediaType; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.jsonwebtoken.security.Keys; +import io.jsonwebtoken.Jwts; + +@RestController +@RequestMapping("/mms5auth") +public class MMS5Auth { + private AuthenticationManager authenticationManager; + private ProjectUserPermRepository projectUserPerms; + private ProjectGroupPermRepository projectGroupPerms; + private BranchUserPermRepository branchUserPerms; + private BranchGroupPermRepository branchGroupPerms; + private ProjectRepository projectRepo; + private BranchRepository branchRepo; + + @Value("${jwt.secret}") + private String secret; + + @Value("${jwt.expiration}") + private Long expiration; + + @Autowired + public MMS5Auth(AuthenticationManager authenticationManager, + ProjectGroupPermRepository projectGroupPerms, + ProjectUserPermRepository projectUserPerms, + BranchUserPermRepository branchUserPerms, + BranchGroupPermRepository branchGroupPerms, + ProjectRepository projectRepo, + BranchRepository branchRepo) { + this.authenticationManager = authenticationManager; + this.projectUserPerms = projectUserPerms; + this.projectGroupPerms = projectGroupPerms; + this.branchUserPerms = branchUserPerms; + this.branchGroupPerms = branchGroupPerms; + this.projectRepo = projectRepo; + this.branchRepo = branchRepo; + + } + + @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) + @SecurityRequirements(value = {}) + @Transactional(readOnly = true) + public JwtAuthenticationResponse createAuthenticationToken( + @RequestBody JwtAuthenticationRequest authenticationRequest) { + final Authentication authentication = authenticationManager.authenticate( + new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), + authenticationRequest.getPassword())); + + SecurityContextHolder.getContext().setAuthentication(authentication); + + final UserDetails userDetails = (UserDetails) authentication.getPrincipal(); + Collection groups = authentication.getAuthorities(); + + Map o = new HashMap<>(); + Map perms = new HashMap<>(); + o.put("permissions", perms); + o.put("sub", userDetails.getUsername()); + + Map> projectPerms = new HashMap<>(); + for (ProjectUserPerm perm: projectUserPerms.findAllByUser_Username(userDetails.getUsername())) { + String projectId = perm.getProject().getProjectId(); + String role = perm.getRole().getName(); + updateProjectPerm(projectPerms, projectId, role); + Map> branchPerms = new HashMap<>(); + for (BranchUserPerm perm2: branchUserPerms.findAllByUser_UsernameAndBranch_Project_ProjectId(userDetails.getUsername(), projectId)) { + updateProjectPerm(branchPerms, perm2.getBranch().getBranchId(), perm2.getRole().getName()); + } + projectPerms.get(projectId).put("branches", branchPerms); + } + for (GrantedAuthority group: groups) { + for (ProjectGroupPerm perm: projectGroupPerms.findAllByGroup_Name(group.getAuthority())) { + String projectId = perm.getProject().getProjectId(); + String role = perm.getRole().getName(); + updateProjectPerm(projectPerms, projectId, role); + if (!(projectPerms.get(projectId)).containsKey("branches")){ + (projectPerms.get(projectId)).put("branches", new HashMap>()); + } + Map> branchPerms = (Map>) (projectPerms.get(projectId)).get("branches"); + for (BranchGroupPerm perm2: branchGroupPerms.findAllByGroup_NameAndBranch_Project_ProjectId(group.getAuthority(), projectId)) { + updateProjectPerm(branchPerms, perm2.getBranch().getBranchId(), perm2.getRole().getName()); + } + } + } + for (Map projectPerm: projectPerms.values()) { + projectPerm.put("branches", ((Map)projectPerm.get("branches")).values()); + } + perms.put("projects", projectPerms.values()); + final String token = generateToken(o); + return new JwtAuthenticationResponse(token); + } + + @GetMapping + @SecurityRequirements(value = {}) + @Transactional(readOnly = true) + public JwtAuthenticationResponse createAnonAuthenticationToken() { + String username = "anonymous"; + Map o = new HashMap<>(); + Map perms = new HashMap<>(); + o.put("permissions", perms); + o.put("sub", username); + List publicProjects = projectRepo.findAllByIsPublicTrue(); + Map> projectPerms = new HashMap<>(); + for (Project project: publicProjects) { + updateProjectPerm(projectPerms, project.getProjectId(), "READER"); + Map> branchPerms = new HashMap<>(); + for (Branch branch: branchRepo.findAllByProject_ProjectId(project.getProjectId())) { + updateProjectPerm(branchPerms, branch.getBranchId(), "READER"); + } + projectPerms.get(project.getProjectId()).put("branches", branchPerms); + } + for (Map projectPerm: projectPerms.values()) { + projectPerm.put("branches", ((Map)projectPerm.get("branches")).values()); + } + perms.put("projects", projectPerms.values()); + final String token = generateToken(o); + return new JwtAuthenticationResponse(token); + } + + private void updateProjectPerm(Map> projectPerms, String projectId, String role) { + if (!projectPerms.containsKey(projectId)) { + projectPerms.put(projectId, new HashMap<>()); + } + Map projectPerm = projectPerms.get(projectId); + projectPerm.put("id", projectId); + String existingRole = (String) projectPerm.get("role"); + role = existingRole == null || existingRole.equals("READER") || role.equals("ADMIN") ? role : existingRole; + projectPerm.put("role", role); + } + + private String generateToken(Map claims) { + return Jwts.builder().setClaims(claims).setExpiration(generateExpirationDate()) + .signWith(getSecretKey()) + .compact(); + } + + private SecretKey getSecretKey() { + return Keys.hmacShaKeyFor(secret.getBytes()); + } + private Date generateExpirationDate() { + return new Date(System.currentTimeMillis() + expiration * 1000); + } +} diff --git a/rdb/src/main/java/org/openmbee/mms/rdb/repositories/BranchGroupPermRepository.java b/rdb/src/main/java/org/openmbee/mms/rdb/repositories/BranchGroupPermRepository.java index b0129ab81..0b09a0227 100644 --- a/rdb/src/main/java/org/openmbee/mms/rdb/repositories/BranchGroupPermRepository.java +++ b/rdb/src/main/java/org/openmbee/mms/rdb/repositories/BranchGroupPermRepository.java @@ -20,6 +20,8 @@ public interface BranchGroupPermRepository extends JpaRepository findByBranchAndGroupAndInheritedIsFalse(Branch b, Group g); + List findAllByGroup_NameAndBranch_Project_ProjectId(String group, String projectId); + boolean existsByBranchAndGroup_NameInAndRoleIn(Branch b, Set groups, Set roles); void deleteByBranchAndGroup_NameInAndInheritedIsFalse(Branch b, Set groups); diff --git a/rdb/src/main/java/org/openmbee/mms/rdb/repositories/BranchRepository.java b/rdb/src/main/java/org/openmbee/mms/rdb/repositories/BranchRepository.java index 44bb6e9a8..65345c1a7 100644 --- a/rdb/src/main/java/org/openmbee/mms/rdb/repositories/BranchRepository.java +++ b/rdb/src/main/java/org/openmbee/mms/rdb/repositories/BranchRepository.java @@ -1,5 +1,6 @@ package org.openmbee.mms.rdb.repositories; +import java.util.List; import java.util.Optional; import org.openmbee.mms.data.domains.global.Branch; import org.springframework.data.jpa.repository.JpaRepository; @@ -10,4 +11,6 @@ public interface BranchRepository extends JpaRepository { Optional findByProject_ProjectIdAndBranchId(String projectId, String branchId); + List findAllByProject_ProjectId(String projectId); + } diff --git a/rdb/src/main/java/org/openmbee/mms/rdb/repositories/BranchUserPermRepository.java b/rdb/src/main/java/org/openmbee/mms/rdb/repositories/BranchUserPermRepository.java index 76a8b33d0..df101debb 100644 --- a/rdb/src/main/java/org/openmbee/mms/rdb/repositories/BranchUserPermRepository.java +++ b/rdb/src/main/java/org/openmbee/mms/rdb/repositories/BranchUserPermRepository.java @@ -1,5 +1,6 @@ package org.openmbee.mms.rdb.repositories; +import java.util.List; import java.util.Optional; import java.util.Set; @@ -19,6 +20,8 @@ public interface BranchUserPermRepository extends JpaRepository findByBranchAndUserAndInheritedIsFalse(Branch b, User u); + List findAllByUser_UsernameAndBranch_Project_ProjectId(String user, String projectId); + boolean existsByBranchAndUser_UsernameAndRoleIn(Branch b, String user, Set roles); void deleteByBranchAndUser_UsernameInAndInheritedIsFalse(Branch b, Set users); diff --git a/rdb/src/main/java/org/openmbee/mms/rdb/repositories/ProjectGroupPermRepository.java b/rdb/src/main/java/org/openmbee/mms/rdb/repositories/ProjectGroupPermRepository.java index d8f9f8b97..36c971989 100644 --- a/rdb/src/main/java/org/openmbee/mms/rdb/repositories/ProjectGroupPermRepository.java +++ b/rdb/src/main/java/org/openmbee/mms/rdb/repositories/ProjectGroupPermRepository.java @@ -24,6 +24,8 @@ public interface ProjectGroupPermRepository extends JpaRepository findAllByProjectAndRole_Name(Project proj, String r); + List findAllByGroup_Name(String group); + boolean existsByProjectAndGroup_NameInAndRoleIn(Project proj, Set groups, Set roles); void deleteByProjectAndGroup_NameInAndInheritedIsFalse(Project proj, Set groups); diff --git a/rdb/src/main/java/org/openmbee/mms/rdb/repositories/ProjectRepository.java b/rdb/src/main/java/org/openmbee/mms/rdb/repositories/ProjectRepository.java index be7b12cfc..c5bf01dd2 100644 --- a/rdb/src/main/java/org/openmbee/mms/rdb/repositories/ProjectRepository.java +++ b/rdb/src/main/java/org/openmbee/mms/rdb/repositories/ProjectRepository.java @@ -17,4 +17,5 @@ public interface ProjectRepository extends JpaRepository { List findAllByOrganizationOrganizationId(String id); + List findAllByIsPublicTrue(); } diff --git a/rdb/src/main/java/org/openmbee/mms/rdb/repositories/ProjectUserPermRepository.java b/rdb/src/main/java/org/openmbee/mms/rdb/repositories/ProjectUserPermRepository.java index 216395e7e..da6976213 100644 --- a/rdb/src/main/java/org/openmbee/mms/rdb/repositories/ProjectUserPermRepository.java +++ b/rdb/src/main/java/org/openmbee/mms/rdb/repositories/ProjectUserPermRepository.java @@ -24,6 +24,8 @@ public interface ProjectUserPermRepository extends JpaRepository findAllByProjectAndRole_Name(Project proj, String r); + List findAllByUser_Username(String user); + boolean existsByProjectAndUser_UsernameAndRoleIn(Project proj, String user, Set roles); void deleteByProjectAndUser_UsernameInAndInheritedIsFalse(Project proj, Set users); From 3084e3dd7924ba11cb5c94bdfddba72aeb227bd1 Mon Sep 17 00:00:00 2001 From: "Lam, Doris T (319E)" Date: Tue, 3 Aug 2021 10:42:54 -0700 Subject: [PATCH 2/5] added more queries for org perms --- .../openmbee/mms/rdb/repositories/OrgGroupPermRepository.java | 2 ++ .../openmbee/mms/rdb/repositories/OrgUserPermRepository.java | 2 ++ 2 files changed, 4 insertions(+) diff --git a/rdb/src/main/java/org/openmbee/mms/rdb/repositories/OrgGroupPermRepository.java b/rdb/src/main/java/org/openmbee/mms/rdb/repositories/OrgGroupPermRepository.java index e5975a67d..c352b00f6 100644 --- a/rdb/src/main/java/org/openmbee/mms/rdb/repositories/OrgGroupPermRepository.java +++ b/rdb/src/main/java/org/openmbee/mms/rdb/repositories/OrgGroupPermRepository.java @@ -22,6 +22,8 @@ public interface OrgGroupPermRepository extends JpaRepository findAllByOrganizationAndRole_Name(Organization org, String r); + List findAllByGroup_Name(String group); + boolean existsByOrganizationAndGroup_NameInAndRoleIn(Organization org, Set user, Set roles); void deleteByOrganizationAndGroup_NameIn(Organization org, Set groups); diff --git a/rdb/src/main/java/org/openmbee/mms/rdb/repositories/OrgUserPermRepository.java b/rdb/src/main/java/org/openmbee/mms/rdb/repositories/OrgUserPermRepository.java index ee2690ad3..ee1af231e 100644 --- a/rdb/src/main/java/org/openmbee/mms/rdb/repositories/OrgUserPermRepository.java +++ b/rdb/src/main/java/org/openmbee/mms/rdb/repositories/OrgUserPermRepository.java @@ -22,6 +22,8 @@ public interface OrgUserPermRepository extends JpaRepository List findAllByOrganizationAndRole_Name(Organization org, String r); + List findAllByUser_Username(String username); + boolean existsByOrganizationAndUser_UsernameAndRoleIn(Organization org, String user, Set roles); void deleteByOrganizationAndUser_UsernameIn(Organization org, Set users); From 30db2375af0a97892ccf29442bca7ae25262ed55 Mon Sep 17 00:00:00 2001 From: "Lam, Doris T (319E)" Date: Tue, 3 Aug 2021 10:48:24 -0700 Subject: [PATCH 3/5] find public orgs --- .../openmbee/mms/rdb/repositories/OrganizationRepository.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/rdb/src/main/java/org/openmbee/mms/rdb/repositories/OrganizationRepository.java b/rdb/src/main/java/org/openmbee/mms/rdb/repositories/OrganizationRepository.java index c5d2d716d..60f491ad1 100644 --- a/rdb/src/main/java/org/openmbee/mms/rdb/repositories/OrganizationRepository.java +++ b/rdb/src/main/java/org/openmbee/mms/rdb/repositories/OrganizationRepository.java @@ -1,5 +1,6 @@ package org.openmbee.mms.rdb.repositories; +import java.util.List; import java.util.Optional; import org.openmbee.mms.data.domains.global.Organization; import org.springframework.data.jpa.repository.JpaRepository; @@ -12,4 +13,6 @@ public interface OrganizationRepository extends JpaRepository findByOrganizationName(String name); + List findAllByIsPublicTrue(); + } From ab9d8f78477187c5c6ab26765b0ae7b14261889c Mon Sep 17 00:00:00 2001 From: "Lam, Doris T (319E)" Date: Tue, 3 Aug 2021 10:52:41 -0700 Subject: [PATCH 4/5] remove example tests --- .../example/config/ExampleSecurityConfig.java | 2 - .../mms/example/config/LoggingFilter.java | 46 ----- .../mms/example/controllers/MMS5Auth.java | 180 ------------------ 3 files changed, 228 deletions(-) delete mode 100644 example/src/main/java/org/openmbee/mms/example/config/LoggingFilter.java delete mode 100644 example/src/main/java/org/openmbee/mms/example/controllers/MMS5Auth.java diff --git a/example/src/main/java/org/openmbee/mms/example/config/ExampleSecurityConfig.java b/example/src/main/java/org/openmbee/mms/example/config/ExampleSecurityConfig.java index 08b7989c9..c0cd41795 100644 --- a/example/src/main/java/org/openmbee/mms/example/config/ExampleSecurityConfig.java +++ b/example/src/main/java/org/openmbee/mms/example/config/ExampleSecurityConfig.java @@ -12,7 +12,6 @@ import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.access.ExceptionTranslationFilter; -import org.springframework.security.web.authentication.AnonymousAuthenticationFilter; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; @@ -41,7 +40,6 @@ public void configure(HttpSecurity http) throws Exception { http.csrf().disable().authorizeRequests().anyRequest().permitAll().and().httpBasic(); http.headers().cacheControl(); http.addFilterAfter(corsFilter(), ExceptionTranslationFilter.class); - http.addFilterAfter(new LoggingFilter(), AnonymousAuthenticationFilter.class); authSecurityConfig.setAuthConfig(http); } diff --git a/example/src/main/java/org/openmbee/mms/example/config/LoggingFilter.java b/example/src/main/java/org/openmbee/mms/example/config/LoggingFilter.java deleted file mode 100644 index c7b3c6103..000000000 --- a/example/src/main/java/org/openmbee/mms/example/config/LoggingFilter.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.openmbee.mms.example.config; - -import java.io.IOException; -import java.util.UUID; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; - -public class LoggingFilter implements Filter { - private final Logger LOGGER = LoggerFactory.getLogger(LoggingFilter.class); - - @Override - public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) - throws IOException, ServletException { - String corr = UUID.randomUUID().toString(); - long time = System.currentTimeMillis(); - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - String user = "anonymousUser"; - if (auth != null) { - user = auth.getName(); - } - HttpServletRequest r = (HttpServletRequest) req; - String query = r.getQueryString(); - query = query == null ? "" : ("?" + query); - LOGGER.info("req - {} - {} - {} - {}", user, r.getMethod(), r.getRequestURI() + query, corr); - - chain.doFilter(req, resp); - - time = System.currentTimeMillis() - time; - HttpServletResponse res = (HttpServletResponse)resp; - auth = SecurityContextHolder.getContext().getAuthentication(); - if (auth != null) { - user = auth.getName(); - } - LOGGER.info("res - {} - {} - {} - {} - {} - {}ms ", user, r.getMethod(), r.getRequestURI() + query, corr, res.getStatus(), time); - } -} - diff --git a/example/src/main/java/org/openmbee/mms/example/controllers/MMS5Auth.java b/example/src/main/java/org/openmbee/mms/example/controllers/MMS5Auth.java deleted file mode 100644 index 66f4e09fb..000000000 --- a/example/src/main/java/org/openmbee/mms/example/controllers/MMS5Auth.java +++ /dev/null @@ -1,180 +0,0 @@ -package org.openmbee.mms.example.controllers; - -import io.swagger.v3.oas.annotations.security.SecurityRequirements; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.crypto.SecretKey; -import org.openmbee.mms.authenticator.security.JwtAuthenticationRequest; -import org.openmbee.mms.authenticator.security.JwtAuthenticationResponse; -import org.openmbee.mms.data.domains.global.Branch; -import org.openmbee.mms.data.domains.global.BranchGroupPerm; -import org.openmbee.mms.data.domains.global.BranchUserPerm; -import org.openmbee.mms.data.domains.global.Project; -import org.openmbee.mms.data.domains.global.ProjectGroupPerm; -import org.openmbee.mms.data.domains.global.ProjectUserPerm; -import org.openmbee.mms.rdb.repositories.BranchGroupPermRepository; -import org.openmbee.mms.rdb.repositories.BranchRepository; -import org.openmbee.mms.rdb.repositories.BranchUserPermRepository; -import org.openmbee.mms.rdb.repositories.ProjectGroupPermRepository; -import org.openmbee.mms.rdb.repositories.ProjectRepository; -import org.openmbee.mms.rdb.repositories.ProjectUserPermRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.MediaType; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import io.jsonwebtoken.security.Keys; -import io.jsonwebtoken.Jwts; - -@RestController -@RequestMapping("/mms5auth") -public class MMS5Auth { - private AuthenticationManager authenticationManager; - private ProjectUserPermRepository projectUserPerms; - private ProjectGroupPermRepository projectGroupPerms; - private BranchUserPermRepository branchUserPerms; - private BranchGroupPermRepository branchGroupPerms; - private ProjectRepository projectRepo; - private BranchRepository branchRepo; - - @Value("${jwt.secret}") - private String secret; - - @Value("${jwt.expiration}") - private Long expiration; - - @Autowired - public MMS5Auth(AuthenticationManager authenticationManager, - ProjectGroupPermRepository projectGroupPerms, - ProjectUserPermRepository projectUserPerms, - BranchUserPermRepository branchUserPerms, - BranchGroupPermRepository branchGroupPerms, - ProjectRepository projectRepo, - BranchRepository branchRepo) { - this.authenticationManager = authenticationManager; - this.projectUserPerms = projectUserPerms; - this.projectGroupPerms = projectGroupPerms; - this.branchUserPerms = branchUserPerms; - this.branchGroupPerms = branchGroupPerms; - this.projectRepo = projectRepo; - this.branchRepo = branchRepo; - - } - - @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) - @SecurityRequirements(value = {}) - @Transactional(readOnly = true) - public JwtAuthenticationResponse createAuthenticationToken( - @RequestBody JwtAuthenticationRequest authenticationRequest) { - final Authentication authentication = authenticationManager.authenticate( - new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), - authenticationRequest.getPassword())); - - SecurityContextHolder.getContext().setAuthentication(authentication); - - final UserDetails userDetails = (UserDetails) authentication.getPrincipal(); - Collection groups = authentication.getAuthorities(); - - Map o = new HashMap<>(); - Map perms = new HashMap<>(); - o.put("permissions", perms); - o.put("sub", userDetails.getUsername()); - - Map> projectPerms = new HashMap<>(); - for (ProjectUserPerm perm: projectUserPerms.findAllByUser_Username(userDetails.getUsername())) { - String projectId = perm.getProject().getProjectId(); - String role = perm.getRole().getName(); - updateProjectPerm(projectPerms, projectId, role); - Map> branchPerms = new HashMap<>(); - for (BranchUserPerm perm2: branchUserPerms.findAllByUser_UsernameAndBranch_Project_ProjectId(userDetails.getUsername(), projectId)) { - updateProjectPerm(branchPerms, perm2.getBranch().getBranchId(), perm2.getRole().getName()); - } - projectPerms.get(projectId).put("branches", branchPerms); - } - for (GrantedAuthority group: groups) { - for (ProjectGroupPerm perm: projectGroupPerms.findAllByGroup_Name(group.getAuthority())) { - String projectId = perm.getProject().getProjectId(); - String role = perm.getRole().getName(); - updateProjectPerm(projectPerms, projectId, role); - if (!(projectPerms.get(projectId)).containsKey("branches")){ - (projectPerms.get(projectId)).put("branches", new HashMap>()); - } - Map> branchPerms = (Map>) (projectPerms.get(projectId)).get("branches"); - for (BranchGroupPerm perm2: branchGroupPerms.findAllByGroup_NameAndBranch_Project_ProjectId(group.getAuthority(), projectId)) { - updateProjectPerm(branchPerms, perm2.getBranch().getBranchId(), perm2.getRole().getName()); - } - } - } - for (Map projectPerm: projectPerms.values()) { - projectPerm.put("branches", ((Map)projectPerm.get("branches")).values()); - } - perms.put("projects", projectPerms.values()); - final String token = generateToken(o); - return new JwtAuthenticationResponse(token); - } - - @GetMapping - @SecurityRequirements(value = {}) - @Transactional(readOnly = true) - public JwtAuthenticationResponse createAnonAuthenticationToken() { - String username = "anonymous"; - Map o = new HashMap<>(); - Map perms = new HashMap<>(); - o.put("permissions", perms); - o.put("sub", username); - List publicProjects = projectRepo.findAllByIsPublicTrue(); - Map> projectPerms = new HashMap<>(); - for (Project project: publicProjects) { - updateProjectPerm(projectPerms, project.getProjectId(), "READER"); - Map> branchPerms = new HashMap<>(); - for (Branch branch: branchRepo.findAllByProject_ProjectId(project.getProjectId())) { - updateProjectPerm(branchPerms, branch.getBranchId(), "READER"); - } - projectPerms.get(project.getProjectId()).put("branches", branchPerms); - } - for (Map projectPerm: projectPerms.values()) { - projectPerm.put("branches", ((Map)projectPerm.get("branches")).values()); - } - perms.put("projects", projectPerms.values()); - final String token = generateToken(o); - return new JwtAuthenticationResponse(token); - } - - private void updateProjectPerm(Map> projectPerms, String projectId, String role) { - if (!projectPerms.containsKey(projectId)) { - projectPerms.put(projectId, new HashMap<>()); - } - Map projectPerm = projectPerms.get(projectId); - projectPerm.put("id", projectId); - String existingRole = (String) projectPerm.get("role"); - role = existingRole == null || existingRole.equals("READER") || role.equals("ADMIN") ? role : existingRole; - projectPerm.put("role", role); - } - - private String generateToken(Map claims) { - return Jwts.builder().setClaims(claims).setExpiration(generateExpirationDate()) - .signWith(getSecretKey()) - .compact(); - } - - private SecretKey getSecretKey() { - return Keys.hmacShaKeyFor(secret.getBytes()); - } - private Date generateExpirationDate() { - return new Date(System.currentTimeMillis() + expiration * 1000); - } -} From 1cb0a5ccb8ae4fb655baabe64c5d285dfdb01ba4 Mon Sep 17 00:00:00 2001 From: "Lam, Doris T (319E)" Date: Tue, 3 Aug 2021 10:53:57 -0700 Subject: [PATCH 5/5] revert --- example/example.gradle | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/example/example.gradle b/example/example.gradle index e85b25479..87b646db8 100644 --- a/example/example.gradle +++ b/example/example.gradle @@ -26,13 +26,11 @@ dependencies { project(':search'), project(':storage'), project(':groups'), - project(':rdb'), 'org.springframework.boot:spring-boot-starter-web', 'org.postgresql:postgresql:42.2.5', //'mysql:mysql-connector-java:8.0.17', 'org.springdoc:springdoc-openapi-ui:1.3.1', - 'org.springdoc:springdoc-openapi-security:1.3.1', - 'io.jsonwebtoken:jjwt-api:0.10.5' + 'org.springdoc:springdoc-openapi-security:1.3.1' ) testImplementation(