Skip to content

Commit

Permalink
HELLODATA-1881 - fix annotations
Browse files Browse the repository at this point in the history
  • Loading branch information
Slawomir Wieczorek committed Jan 22, 2025
1 parent 76c5d25 commit 1b40cbd
Show file tree
Hide file tree
Showing 7 changed files with 59 additions and 72 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@
<modelmapper.version>3.1.1</modelmapper.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<rest-assured.version>5.2.0</rest-assured.version>
<spring-boot-starter-kubernetes.version>3.1.0</spring-boot-starter-kubernetes.version>
<spring-boot.version>3.2.4</spring-boot.version>
<spring-boot-admin-dependencies.version>3.2.3</spring-boot-admin-dependencies.version>
<spring-cloud.version>2023.0.0</spring-cloud.version>
<spring-boot-starter-kubernetes.version>3.1.2</spring-boot-starter-kubernetes.version>
<spring-boot.version>3.4.1</spring-boot.version>
<spring-boot-admin-dependencies.version>3.3.3</spring-boot-admin-dependencies.version>
<spring-cloud.version>2024.0.0</spring-cloud.version>
<spring-ws-test.version>4.0.2</spring-ws-test.version>
<springdoc.version>2.5.0</springdoc.version>
<testcontainers-keycloak.version>3.3.1</testcontainers-keycloak.version>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@
import ch.bedag.dap.hellodata.docs.entities.Role;
import ch.bedag.dap.hellodata.docs.service.ProjectDocService;
import ch.bedag.dap.hellodata.docs.service.SecurityService;
import jakarta.validation.constraints.NotNull;
import lombok.extern.log4j.Log4j2;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
Expand Down Expand Up @@ -66,7 +66,7 @@ public void onApplicationEvent(@NotNull ContextRefreshedEvent event) {

List<Privilege> adminPrivileges = Arrays.asList(readPrivilege, writePrivilege);
securityService.createRoleIfNotFound(Role.ADMIN_ROLE_KEY, "ROLE_ADMIN", adminPrivileges);
securityService.createRoleIfNotFound("TEST", "ROLE_USER", Arrays.asList(readPrivilege));
securityService.createRoleIfNotFound("TEST", "ROLE_USER", Collections.singletonList(readPrivilege));
securityService.createOrUpdateAdminUser();
Set<String> availableDataDomainKeys = projectDocService.getAvailableDataDomainKeys();
securityService.createProjectRoles(Collections.singletonList(readPrivilege), availableDataDomainKeys);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,12 @@
import ch.badag.dap.hellodata.commons.basemodel.BaseEntity;
import jakarta.persistence.Entity;
import jakarta.persistence.ManyToMany;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.util.Collection;
import lombok.Getter;
import lombok.Setter;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;

@Entity
@Getter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,13 @@
package ch.bedag.dap.hellodata.docs.entities;

import ch.badag.dap.hellodata.commons.basemodel.BaseEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.util.Collection;
import lombok.Getter;
import lombok.Setter;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;

@Entity
@Getter
Expand All @@ -62,7 +58,7 @@ public class Role extends BaseEntity {

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "roles_privileges", joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "privilege_id", referencedColumnName = "id"))
inverseJoinColumns = @JoinColumn(name = "privilege_id", referencedColumnName = "id"))
private Collection<Privilege> privileges;

public Role(String key, String name, boolean enabled) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,14 @@
package ch.bedag.dap.hellodata.docs.entities;

import ch.badag.dap.hellodata.commons.basemodel.BaseEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.util.Collection;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;

@Entity(name = "dbt_user")
@Getter
Expand Down Expand Up @@ -69,7 +65,7 @@ public class User extends BaseEntity {

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
private Collection<Role> roles;

public User() {//NOSONAR
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@
import ch.bedag.dap.hellodata.docs.entities.User;
import ch.bedag.dap.hellodata.docs.service.SecurityService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.jetbrains.annotations.NotNull;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
Expand All @@ -60,6 +60,14 @@ private static String getRequestParameterPath(@NotNull HttpServletRequest reques
return "";
}

private static String getProjectName(HttpServletRequest request) {
String[] parts = request.getRequestURI().split("/", 4);
if (request.getContextPath().isEmpty()) {
return parts.length > 1 ? parts[1] : "";
}
return parts.length > 2 ? parts[2] : "";
}

@Override
public AuthorizationDecision check(Supplier<Authentication> authenticationSupplier, RequestAuthorizationContext context) {
HttpServletRequest request = context.getRequest();
Expand All @@ -76,7 +84,7 @@ public AuthorizationDecision check(Supplier<Authentication> authenticationSuppli
String preferredUsername = user.getUserName();
String email = user.getEmail();
log.info("Received Principal with username {} and email {}. Requesting Uri: {}", preferredUsername, email,
request.getRequestURI());
request.getRequestURI());
if (requestedEndpoint(request, GET_PROJECTS_DOCS_BY_PATH_URI)) {
String requestParameterPath = getRequestParameterPath(request);
String requestedProject = getRequestedProject(requestParameterPath);
Expand All @@ -95,6 +103,16 @@ public AuthorizationDecision check(Supplier<Authentication> authenticationSuppli
return new AuthorizationDecision(false);
}

public boolean isUserAuthorizedOnProject(User user, String projectName) {
if (user.getRoles().stream().anyMatch(r -> r.getKey().equals(Role.ADMIN_ROLE_KEY))) {
return true;
}
return user.getRoles()
.stream()
.filter(Role::isEnabled)
.anyMatch(r -> r.getKey().equalsIgnoreCase(projectName) && r.getPrivileges().stream().anyMatch(p -> p.getName().equals(Privilege.READ_PRIVILEGE)));
}

private boolean requestedEndpoint(@NotNull HttpServletRequest request, String endpointPath) {
Path endpointPathWithContextPath = Paths.get(request.getContextPath(), endpointPath);
Path requestedUriPath = Paths.get(request.getRequestURI().toLowerCase());
Expand All @@ -104,14 +122,6 @@ private boolean requestedEndpoint(@NotNull HttpServletRequest request, String en
return requestedUriPath.startsWith(endpointPathWithContextPath);
}

private static String getProjectName(HttpServletRequest request) {
String[] parts = request.getRequestURI().split("/", 4);
if (request.getContextPath().isEmpty()) {
return parts.length > 1 ? parts[1] : "";
}
return parts.length > 2 ? parts[2] : "";
}

@NotNull
private AuthorizationDecision authorizeRequestedProject(User user, String projectName) {
if (ObjectUtils.isEmpty(projectName)) {
Expand All @@ -121,16 +131,6 @@ private AuthorizationDecision authorizeRequestedProject(User user, String projec
return new AuthorizationDecision(isAuthorized);
}

public boolean isUserAuthorizedOnProject(User user, String projectName) {
if (user.getRoles().stream().anyMatch(r -> r.getKey().equals(Role.ADMIN_ROLE_KEY))) {
return true;
}
return user.getRoles()
.stream()
.filter(Role::isEnabled)
.anyMatch(r -> r.getKey().equalsIgnoreCase(projectName) && r.getPrivileges().stream().anyMatch(p -> p.getName().equals(Privilege.READ_PRIVILEGE)));
}

private String getRequestedProject(@NotNull String path) {
log.info("Request path: " + path);
String[] split = path.split("/");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,12 @@
import ch.bedag.dap.hellodata.docs.repository.RoleRepository;
import ch.bedag.dap.hellodata.docs.repository.UserRepository;
import ch.bedag.dap.hellodata.docs.security.exception.NotAuthorizedException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import lombok.extern.log4j.Log4j2;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Log4j2
@Service
public class SecurityService {
Expand Down Expand Up @@ -95,14 +91,6 @@ public void createOrUpdateAdminUser() {
userRepository.save(adminUser);
}

@NotNull
private List<Role> getAdminRoles() {
Role adminRole = roleRepository.findByKeyIgnoreCase(Role.ADMIN_ROLE_KEY);
List<Role> roleList = new ArrayList<>();
roleList.add(adminRole);
return roleList;
}

/**
* If there is a ProjectDoc with the name of the value of Role.ADMIN_KEY no new role will get created.
* Do we need to change this?
Expand Down Expand Up @@ -136,13 +124,6 @@ public void updateRoles(Set<String> contextKeys) {
log.debug("Roles didn't change. Nothing to do.");
}

@NotNull
private List<Role> getAllRolesMinusAdminRole() {
List<Role> currentRoles = getAllRoles();
currentRoles.removeIf(r -> r.getKey().equals(Role.ADMIN_ROLE_KEY));
return currentRoles;
}

@Transactional
public Role createRoleIfNotFound(String key, String name, Collection<Privilege> privileges) {
Role role = roleRepository.findByKeyIgnoreCase(key);
Expand Down Expand Up @@ -176,9 +157,9 @@ public List<ProjectDoc> getProjectDocsFilteredByUser(User user, List<ProjectDoc>
log.debug("User {} requested a list of all project-docs.", user.getUserName());
Collection<Role> userRoles = user.getRoles();
return allProjectsDocs.stream()
.filter(projectDoc -> canAccessProject(userRoles, projectDoc.contextKey()))
.sorted((a, b) -> a.contextKey().compareToIgnoreCase(b.contextKey()))
.toList();
.filter(projectDoc -> canAccessProject(userRoles, projectDoc.contextKey()))
.sorted((a, b) -> a.contextKey().compareToIgnoreCase(b.contextKey()))
.toList();
}

public void validateUserIsAllowedOnProjectDoc(User loggedInUser, String projectName) {
Expand All @@ -190,8 +171,8 @@ public void validateUserIsAllowedOnProjectDoc(User loggedInUser, String projectN

public boolean canAccessProject(Collection<Role> userRoles, String dataDomainKey) {
return userRoles.stream()
.anyMatch(ur -> ur.getKey().equals(Role.ADMIN_ROLE_KEY) || (ur.isEnabled() && ur.getKey().equalsIgnoreCase(dataDomainKey) &&
ur.getPrivileges().stream().anyMatch(p -> p.getName().equals(Privilege.READ_PRIVILEGE))));
.anyMatch(ur -> ur.getKey().equals(Role.ADMIN_ROLE_KEY) || (ur.isEnabled() && ur.getKey().equalsIgnoreCase(dataDomainKey) &&
ur.getPrivileges().stream().anyMatch(p -> p.getName().equals(Privilege.READ_PRIVILEGE))));
}

/**
Expand All @@ -205,4 +186,17 @@ public void validateIsAllowedToAccessPath(User loggedInUser, String path) {
}
validateUserIsAllowedOnProjectDoc(loggedInUser, requestedProjectDoc.name());
}

private List<Role> getAdminRoles() {
Role adminRole = roleRepository.findByKeyIgnoreCase(Role.ADMIN_ROLE_KEY);
List<Role> roleList = new ArrayList<>();
roleList.add(adminRole);
return roleList;
}

private List<Role> getAllRolesMinusAdminRole() {
List<Role> currentRoles = getAllRoles();
currentRoles.removeIf(r -> r.getKey().equals(Role.ADMIN_ROLE_KEY));
return currentRoles;
}
}

0 comments on commit 1b40cbd

Please sign in to comment.