Improved role functionality

This commit is contained in:
Konstantinos Spyrou 2023-02-17 16:17:37 +02:00
parent 0f0163dc2d
commit b67e98976d
6 changed files with 85 additions and 106 deletions

View File

@ -67,8 +67,9 @@ public class AaiSecurityConfiguration extends WebSecurityConfigurerAdapter {
.anyRequest().authenticated() .anyRequest().authenticated()
.and() .and()
.logout().logoutUrl("/openid_logout") .logout().logoutUrl("/openid_logout")
.clearAuthentication(true)
.invalidateHttpSession(true) .invalidateHttpSession(true)
.deleteCookies("openAIRESession") .deleteCookies()
.logoutSuccessUrl(logoutSuccessUrl) .logoutSuccessUrl(logoutSuccessUrl)
.and() .and()
.addFilterBefore(openIdConnectAuthenticationFilter(), AbstractPreAuthenticatedProcessingFilter.class) .addFilterBefore(openIdConnectAuthenticationFilter(), AbstractPreAuthenticatedProcessingFilter.class)

View File

@ -28,6 +28,7 @@ import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*; import org.springframework.http.*;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
@ -38,6 +39,7 @@ import javax.annotation.PostConstruct;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
@Service("repositoryService") @Service("repositoryService")
public class RepositoryServiceImpl implements RepositoryService { public class RepositoryServiceImpl implements RepositoryService {
@ -284,14 +286,14 @@ public class RepositoryServiceImpl implements RepositoryService {
public List<Repository> getRepositoriesOfUser(String page, String size) { public List<Repository> getRepositoriesOfUser(String page, String size) {
logger.debug("Retrieving repositories of authenticated user : {}", logger.debug("Retrieving repositories of authenticated user : {}",
((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo().getEmail()); ((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo().getEmail());
Collection<String> repoIds = roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRoles()); Collection<String> repoIds = roleMappingService.getRepositoryIds(authorizationService.getUserRoles());
return getRepositories(new ArrayList<>(repoIds)); return getRepositories(new ArrayList<>(repoIds));
} }
@Override @Override
public List<Repository> getRepositoriesOfUser(String userEmail, String page, String size) { public List<Repository> getRepositoriesOfUser(String userEmail, String page, String size) {
logger.debug("Retrieving repositories of authenticated user : {}", userEmail); logger.debug("Retrieving repositories of authenticated user : {}", userEmail);
Collection<String> repoIds = roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRolesByEmail(userEmail)); Collection<String> repoIds = roleMappingService.getRepositoryIds(authorizationService.getUserRolesByEmail(userEmail));
return getRepositories(new ArrayList<>(repoIds)); return getRepositories(new ArrayList<>(repoIds));
} }
@ -304,12 +306,7 @@ public class RepositoryServiceImpl implements RepositoryService {
public List<RepositorySnippet> getRepositoriesSnippetsOfUser(String userEmail, String page, String size) { public List<RepositorySnippet> getRepositoriesSnippetsOfUser(String userEmail, String page, String size) {
int from = Integer.parseInt(page) * Integer.parseInt(size); int from = Integer.parseInt(page) * Integer.parseInt(size);
int to = from + Integer.parseInt(size); int to = from + Integer.parseInt(size);
List<String> repoIds = new ArrayList<>(); List<String> repoIds = getRepoIdsOfUser(userEmail);
if (userEmail != null && !"".equals(userEmail)) {
repoIds.addAll(roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRolesByEmail(userEmail)));
} else {
repoIds.addAll(roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRoles()));
}
if (repoIds.size() < from) { if (repoIds.size() < from) {
return Collections.emptyList(); return Collections.emptyList();
@ -534,8 +531,8 @@ public class RepositoryServiceImpl implements RepositoryService {
emailUtils.sendUserRegisterInterfaceEmail(repo, comment, repositoryInterface, desiredCompatibilityLevel, authentication); emailUtils.sendUserRegisterInterfaceEmail(repo, comment, repositoryInterface, desiredCompatibilityLevel, authentication);
String prevCompatibilityLevel = repositoryInterface.getCompatibility(); String prevCompatibilityLevel = repositoryInterface.getCompatibility();
if ( (desiredCompatibilityLevel != null) if ((desiredCompatibilityLevel != null)
&& ((prevCompatibilityLevel == null) || ! prevCompatibilityLevel.equals(desiredCompatibilityLevel))) { && ((prevCompatibilityLevel == null) || !prevCompatibilityLevel.equals(desiredCompatibilityLevel))) {
InterfaceComplianceRequest request = new InterfaceComplianceRequest(repoId, repositoryInterface.getId(), desiredCompatibilityLevel); InterfaceComplianceRequest request = new InterfaceComplianceRequest(repoId, repositoryInterface.getId(), desiredCompatibilityLevel);
interfaceComplianceService.create(request); interfaceComplianceService.create(request);
} }
@ -957,10 +954,27 @@ public class RepositoryServiceImpl implements RepositoryService {
return repositories; return repositories;
} }
private List<String> getRepoIdsOfUser(String userEmail) {
List<String> repoIds;
if (userEmail != null && !"".equals(userEmail)) {
repoIds = new ArrayList<>(roleMappingService.getRepositoryIds(authorizationService.getUserRolesByEmail(userEmail)));
} else {
Collection<?> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
repoIds = authorities
.stream()
.map(a -> roleMappingService.authorityToRepositoryId((GrantedAuthority) a))
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
return repoIds;
}
@Deprecated
private String getRepositoryType(String typology) { private String getRepositoryType(String typology) {
return invertedDataSourceClass.get(typology); return invertedDataSourceClass.get(typology);
} }
@Deprecated
private List<String> getRoleIdsFromUserRoles(String userEmail) { private List<String> getRoleIdsFromUserRoles(String userEmail) {
List<Integer> coPersonId = registryCalls.getCoPersonIdsByEmail(userEmail); List<Integer> coPersonId = registryCalls.getCoPersonIdsByEmail(userEmail);
JsonArray roles; JsonArray roles;

View File

@ -165,6 +165,7 @@ public class RegistryCalls implements AaiRegistryService {
@Override @Override
public JsonArray getRoles(Integer coPersonId) { public JsonArray getRoles(Integer coPersonId) {
Map<String, String> params = new HashMap<>(); Map<String, String> params = new HashMap<>();
params.put("coid", coid);
params.put("copersonid", coPersonId.toString()); params.put("copersonid", coPersonId.toString());
JsonElement response = httpUtils.get("co_person_roles.json", params); JsonElement response = httpUtils.get("co_person_roles.json", params);
return (response != null) ? response.getAsJsonObject().get("CoPersonRoles").getAsJsonArray() : new JsonArray(); return (response != null) ? response.getAsJsonObject().get("CoPersonRoles").getAsJsonArray() : new JsonArray();

View File

@ -7,6 +7,8 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.Collection; import java.util.Collection;
import java.util.Objects; import java.util.Objects;
@ -20,21 +22,8 @@ public class AaiRoleMappingService implements RoleMappingService {
@Value("${services.provide.aai.registry.production:true}") @Value("${services.provide.aai.registry.production:true}")
private boolean production; private boolean production;
private String createRepoRoleName(String prefix, String repoId) {
return prefix + "." + repoId.replace(":", "$");
}
@Override @Override
public String getRepoNameWithoutType(String fullName, String prefix) { public String getRepositoryId(String roleId) {
if (fullName != null && prefix != null && fullName.startsWith(prefix)) {
return fullName.substring(prefix.length());
}
return null;
}
@Override
public String getRepoIdByRoleId(String roleId) {
if (!roleActive(roleId)) { if (!roleActive(roleId)) {
return null; return null;
} }
@ -42,43 +31,46 @@ public class AaiRoleMappingService implements RoleMappingService {
} }
@Override @Override
public Collection<String> getRepoIdsByRoleIds(Collection<String> roleIds) { public Collection<String> getRepositoryIds(Collection<String> roleIds) {
return roleIds return roleIds
.stream() .stream()
//.filter(this::roleActive) // implicitly executed in the next statement .map(this::getRepositoryId)
.map(this::getRepoIdByRoleId)
.filter(Objects::nonNull) .filter(Objects::nonNull)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@Override @Override
public String getRoleIdByRepoId(String repoId) { public String getRole(String repoId) {
String roleId = ""; String role = null;
String prefix = (production ? "" : "beta.") + "datasource"; String prefix = (production ? "" : "beta.") + "datasource";
if (repoId != null) { if (repoId != null) {
roleId = createRepoRoleName(prefix, repoId); role = createRole(prefix, repoId);
return roleId;
} else {
return null;
} }
return role;
} }
@Override @Override
public Collection<String> getRoleIdsByRepoIds(Collection<String> repoIds) { public Collection<String> getRoles(Collection<String> repoIds) {
return repoIds return repoIds
.stream() .stream()
.map(this::getRoleIdByRepoId) .map(this::getRole)
.filter(Objects::nonNull) .filter(Objects::nonNull)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@Override @Override
public String convertAuthorityIdToRepoId(String authorityId) { public String authorityToRepositoryId(GrantedAuthority authority) {
String repo = ""; String repo = null;
if (authorityId != null && roleActive(authorityId)) { String auth = null;
repo = authorityId try {
.replaceFirst(".*datasource\\.", "") auth = URLDecoder.decode(authority.getAuthority(), "UTF-8").toLowerCase();
} catch (UnsupportedEncodingException e) {
logger.error("", e);
}
if (auth != null && roleActive(auth)) {
repo = auth
.replaceFirst(".*datasource\\_", "")
.replace("$", ":") .replace("$", ":")
.toLowerCase(); .toLowerCase();
} }
@ -86,12 +78,26 @@ public class AaiRoleMappingService implements RoleMappingService {
} }
@Override @Override
public String convertAuthorityToRepoId(GrantedAuthority authority) { public GrantedAuthority repositoryIdToAuthority(String repoId) {
return convertAuthorityIdToRepoId(authority.toString()); String role = null;
try {
role = URLEncoder.encode(convertRepoIdToAuthorityId(repoId), "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error("", e);
}
return new SimpleGrantedAuthority(role);
} }
@Override private String createRole(String prefix, String repoId) {
public String convertRepoIdToAuthorityId(String repoId) { return prefix + "." + repoId.replace(":", "$");
}
private boolean roleActive(String roleId) {
return (production && !roleId.toLowerCase().startsWith("beta"))
|| (!production && roleId.toLowerCase().startsWith("beta"));
}
private String convertRepoIdToAuthorityId(String repoId) {
StringBuilder roleBuilder = new StringBuilder(); StringBuilder roleBuilder = new StringBuilder();
String role = ""; String role = "";
if (repoId != null) { if (repoId != null) {
@ -102,20 +108,4 @@ public class AaiRoleMappingService implements RoleMappingService {
} }
return role; return role;
} }
@Override
public String convertRepoIdToEncodedAuthorityId(String repoId) {
return URLEncoder.encode(convertRepoIdToAuthorityId(repoId));
}
@Override
public SimpleGrantedAuthority convertRepoIdToAuthority(String repoId) {
String role = convertRepoIdToEncodedAuthorityId(repoId);
return new SimpleGrantedAuthority(role);
}
private boolean roleActive(String roleId) {
return (production && !roleId.toLowerCase().startsWith("beta."))
|| (!production && roleId.toLowerCase().startsWith("beta."));
}
} }

View File

@ -56,9 +56,9 @@ public class AuthorizationServiceImpl implements AuthorizationService {
@Override @Override
public boolean isMemberOf(String repoId) { public boolean isMemberOf(String repoId) {
String repoRole = roleMappingService.convertRepoIdToEncodedAuthorityId(repoId); String repoAuthority = roleMappingService.repositoryIdToAuthority(repoId).getAuthority();
return SecurityContextHolder.getContext().getAuthentication().getAuthorities() return SecurityContextHolder.getContext().getAuthentication().getAuthorities()
.stream().anyMatch(authority -> authority.toString().equals(repoRole)); .stream().anyMatch(authority -> authority.toString().equals(repoAuthority));
} }
@Override @Override
@ -74,7 +74,7 @@ public class AuthorizationServiceImpl implements AuthorizationService {
public List<User> getAdminsOfRepo(String repoId) { public List<User> getAdminsOfRepo(String repoId) {
// find couId by role name // find couId by role name
String role = roleMappingService.getRoleIdByRepoId(repoId); String role = roleMappingService.getRole(repoId);
Integer couId = aaiRegistryService.getCouId(role); Integer couId = aaiRegistryService.getCouId(role);
return aaiRegistryService.getUsers(couId); return aaiRegistryService.getUsers(couId);
} }
@ -82,7 +82,7 @@ public class AuthorizationServiceImpl implements AuthorizationService {
@Override @Override
public void addAdmin(String resourceId, String email) throws ResourceNotFoundException { public void addAdmin(String resourceId, String email) throws ResourceNotFoundException {
String role = roleMappingService.getRoleIdByRepoId(resourceId); String role = roleMappingService.getRole(resourceId);
Integer couId = aaiRegistryService.getCouId(role); Integer couId = aaiRegistryService.getCouId(role);
if (couId == null) { if (couId == null) {
throw new ResourceNotFoundException("Cannot find CouId for role: " + role); throw new ResourceNotFoundException("Cannot find CouId for role: " + role);
@ -94,14 +94,14 @@ public class AuthorizationServiceImpl implements AuthorizationService {
// Add role to user current authorities // Add role to user current authorities
for (String userId : aaiRegistryService.getUserIdentifiersByEmail(email)) { for (String userId : aaiRegistryService.getUserIdentifiersByEmail(email)) {
authoritiesUpdater.addRole(userId, roleMappingService.convertRepoIdToAuthority(resourceId)); authoritiesUpdater.addRole(userId, roleMappingService.repositoryIdToAuthority(resourceId));
} }
} }
} }
@Override @Override
public void removeAdmin(String resourceId, String email) throws ResourceNotFoundException { public void removeAdmin(String resourceId, String email) throws ResourceNotFoundException {
String role = roleMappingService.getRoleIdByRepoId(resourceId); String role = roleMappingService.getRole(resourceId);
Integer couId = aaiRegistryService.getCouId(role); Integer couId = aaiRegistryService.getCouId(role);
if (couId == null) { if (couId == null) {
throw new ResourceNotFoundException("Cannot find CouId for role: " + role); throw new ResourceNotFoundException("Cannot find CouId for role: " + role);
@ -115,7 +115,7 @@ public class AuthorizationServiceImpl implements AuthorizationService {
// Remove role from user current authorities // Remove role from user current authorities
for (String userId : aaiRegistryService.getUserIdentifiersByEmail(email)) { for (String userId : aaiRegistryService.getUserIdentifiersByEmail(email)) {
authoritiesUpdater.removeRole(userId, roleMappingService.convertRepoIdToAuthority(resourceId)); authoritiesUpdater.removeRole(userId, roleMappingService.repositoryIdToAuthority(resourceId));
} }
} else { } else {
logger.error("Cannot find RoleId for role: {}", role); logger.error("Cannot find RoleId for role: {}", role);
@ -126,7 +126,7 @@ public class AuthorizationServiceImpl implements AuthorizationService {
@Override @Override
public void createAndAssignRoleToAuthenticatedUser(String resourceId, String roleDescription) { public void createAndAssignRoleToAuthenticatedUser(String resourceId, String roleDescription) {
// Create new role // Create new role
String newRoleName = roleMappingService.getRoleIdByRepoId(resourceId); String newRoleName = roleMappingService.getRole(resourceId);
Role newRole = new Role(newRoleName, roleDescription); Role newRole = new Role(newRoleName, roleDescription);
Integer couId; Integer couId;
@ -148,7 +148,7 @@ public class AuthorizationServiceImpl implements AuthorizationService {
aaiRegistryService.assignMemberRole(coPersonId, couId); aaiRegistryService.assignMemberRole(coPersonId, couId);
// Add role to current user authorities // Add role to current user authorities
authoritiesUpdater.addRole(roleMappingService.convertRepoIdToAuthority(resourceId)); authoritiesUpdater.addRole(roleMappingService.repositoryIdToAuthority(resourceId));
} }
} }

View File

@ -7,68 +7,41 @@ import java.util.Collection;
public interface RoleMappingService { public interface RoleMappingService {
/**
* @param fullName
* @param prefix
* @return
*/
String getRepoNameWithoutType(String fullName, String prefix);
/** /**
* @param roleId Role Id * @param roleId Role Id
* @return Converts {@param roleId} to a repo Id. * @return Converts {@param roleId} to a repo Id.
*/ */
String getRepoIdByRoleId(String roleId); String getRepositoryId(String roleId);
/** /**
*
* @param roleIds Collection of roles * @param roleIds Collection of roles
* @return Converts {@param roleIds} to a repo Ids. * @return Converts {@param roleIds} to a repo Ids.
*/ */
Collection<String> getRepoIdsByRoleIds(Collection<String> roleIds); Collection<String> getRepositoryIds(Collection<String> roleIds);
/** /**
* @param repoId Repository Id * @param repoId Repository Id
* @return Converts {@param repoId} to a role Id. * @return Converts {@param repoId} to a role Id.
*/ */
String getRoleIdByRepoId(String repoId); String getRole(String repoId);
/** /**
* @param repoIds Collection of Repository Ids * @param repoIds Collection of Repository Ids
* @return Converts {@param repoIds} to role Ids. * @return Converts {@param repoIds} to role Ids.
*/ */
Collection<String> getRoleIdsByRepoIds(Collection<String> repoIds); Collection<String> getRoles(Collection<String> repoIds);
/** /**
* @param authorityId Authority Id * @param authority {@link GrantedAuthority}
* @return Converts {@param authorityId} to repo Id. * @return Converts {@param authority} to repository Id.
*/ */
String convertAuthorityIdToRepoId(String authorityId); String authorityToRepositoryId(GrantedAuthority authority);
/**
* @param authority Granted authority
* @return Converts {@param authority} to repo Id.
*/
String convertAuthorityToRepoId(GrantedAuthority authority);
/**
* @param repoId Repository Id
* @return
*/
String convertRepoIdToAuthorityId(String repoId);
/**
* @param repoId Repository Id
* @return Converts {@param repoId} to {@link String} role id url encoded ($ -> %24)
* // TODO: remove role encoding and perform url decoding when mapping authorities. (Must be performed in all OpenAIRE projects because of Redis)
*/
String convertRepoIdToEncodedAuthorityId(String repoId);
/** /**
* @param repoId Repository Id * @param repoId Repository Id
* @return Converts {@param repoId} to {@link SimpleGrantedAuthority} with the role url encoded ($ -> %24) * @return Converts {@param repoId} to {@link SimpleGrantedAuthority} with the role url encoded ($ -> %24)
* // TODO: remove role encoding and perform url decoding when mapping authorities. (Must be performed in all OpenAIRE projects because of Redis) * // TODO: remove role encoding and perform url decoding when mapping authorities. (Must be performed in all OpenAIRE projects because of Redis)
*/ */
SimpleGrantedAuthority convertRepoIdToAuthority(String repoId); GrantedAuthority repositoryIdToAuthority(String repoId);
} }