1. use sub for session instead of email 2. minor refactoring

This commit is contained in:
Konstantinos Spyrou 2023-01-12 14:16:27 +02:00
parent d8eac0ac10
commit 830df7cb52
8 changed files with 30 additions and 34 deletions

View File

@ -26,7 +26,7 @@ public class FrontEndLinkURIAuthenticationSuccessHandler implements Authenticati
private static final Logger logger = LoggerFactory.getLogger(FrontEndLinkURIAuthenticationSuccessHandler.class); private static final Logger logger = LoggerFactory.getLogger(FrontEndLinkURIAuthenticationSuccessHandler.class);
public void init() { public void init() {
logger.debug("Front end uri : " + frontEndURI); logger.debug("Front end uri : {}", frontEndURI);
} }
@ -36,7 +36,7 @@ public class FrontEndLinkURIAuthenticationSuccessHandler implements Authenticati
@Override @Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
OIDCAuthenticationToken authOIDC = (OIDCAuthenticationToken) authentication; OIDCAuthenticationToken authOIDC = (OIDCAuthenticationToken) authentication;
request.getSession().setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, authOIDC.getUserInfo().getEmail()); request.getSession().setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, authOIDC.getUserInfo().getSub());
Cookie accessToken = new Cookie("AccessToken", authOIDC.getAccessTokenValue()); Cookie accessToken = new Cookie("AccessToken", authOIDC.getAccessTokenValue());
String regex = "^([A-Za-z0-9-_=]+)\\.([A-Za-z0-9-_=]+)\\.?([A-Za-z0-9-_.+=]*)$"; String regex = "^([A-Za-z0-9-_=]+)\\.([A-Za-z0-9-_=]+)\\.?([A-Za-z0-9-_.+=]*)$";

View File

@ -34,7 +34,7 @@ public class OpenAIREAuthoritiesMapper implements OIDCAuthoritiesMapper {
} else if (userInfo.getSource().getAsJsonArray("eduperson_entitlement") != null) { } else if (userInfo.getSource().getAsJsonArray("eduperson_entitlement") != null) {
entitlements = userInfo.getSource().getAsJsonArray("eduperson_entitlement"); entitlements = userInfo.getSource().getAsJsonArray("eduperson_entitlement");
} }
logger.debug("user info: " + userInfo + "\nentitlements: " + entitlements); logger.debug("user info: {}\nentitlements: {}", userInfo, entitlements);
// FIXME: delete this if statement when super administrators are set // FIXME: delete this if statement when super administrators are set
if (userInfo.getEmail() != null && userInfo.getEmail().equals(adminEmail)) { if (userInfo.getEmail() != null && userInfo.getEmail().equals(adminEmail)) {

View File

@ -52,7 +52,7 @@ public class RedisConfiguration {
serializer.setCookieName("openAIRESession"); serializer.setCookieName("openAIRESession");
serializer.setCookiePath("/"); serializer.setCookiePath("/");
serializer.setDomainName(domain); serializer.setDomainName(domain);
logger.info("Serializer : " + serializer); logger.info("Cookie Serializer : {}", serializer);
return serializer; return serializer;
} }

View File

@ -96,7 +96,7 @@ public class UserRoleController {
@RequestMapping(method = RequestMethod.GET, path = "/users/{email}/roles") @RequestMapping(method = RequestMethod.GET, path = "/users/{email}/roles")
@PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or hasAuthority('REGISTERED_USER') and authentication.userInfo.email==#email") @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or hasAuthority('REGISTERED_USER') and authentication.userInfo.email==#email")
public ResponseEntity<Collection<String>> getRolesByEmail(@PathVariable("email") String email) { public ResponseEntity<Collection<String>> getRolesByEmail(@PathVariable("email") String email) {
return ResponseEntity.ok(authorizationService.getUserRoles(email)); return ResponseEntity.ok(authorizationService.getUserRolesByEmail(email));
} }

View File

@ -1,10 +1,6 @@
package eu.dnetlib.repo.manager.service; package eu.dnetlib.repo.manager.service;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
import com.google.gson.JsonArray; import com.google.gson.JsonArray;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
@ -12,7 +8,6 @@ import eu.dnetlib.api.functionality.ValidatorServiceException;
import eu.dnetlib.domain.enabling.Vocabulary; import eu.dnetlib.domain.enabling.Vocabulary;
import eu.dnetlib.domain.functionality.validator.JobForValidation; import eu.dnetlib.domain.functionality.validator.JobForValidation;
import eu.dnetlib.repo.manager.domain.*; import eu.dnetlib.repo.manager.domain.*;
import eu.dnetlib.repo.manager.domain.broker.BrowseEntry;
import eu.dnetlib.repo.manager.domain.dto.Role; import eu.dnetlib.repo.manager.domain.dto.Role;
import eu.dnetlib.repo.manager.domain.dto.User; import eu.dnetlib.repo.manager.domain.dto.User;
import eu.dnetlib.repo.manager.exception.BrokerException; import eu.dnetlib.repo.manager.exception.BrokerException;
@ -331,8 +326,8 @@ public class RepositoryServiceImpl implements RepositoryService {
@Override @Override
public List<Repository> getRepositoriesOfUser(String page, String size) throws JSONException { public List<Repository> getRepositoriesOfUser(String page, String size) throws JSONException {
String userEmail = ((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo().getEmail(); logger.debug("Retrieving repositories of authenticated user : {}",
logger.debug("Retrieving repositories of authenticated user : " + userEmail); ((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo().getEmail());
Collection<String> repoIds = roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRoles()); Collection<String> repoIds = roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRoles());
return getRepositories(new ArrayList<>(repoIds)); return getRepositories(new ArrayList<>(repoIds));
} }
@ -340,7 +335,7 @@ public class RepositoryServiceImpl implements RepositoryService {
@Override @Override
public List<Repository> getRepositoriesOfUser(String userEmail, String page, String size) throws JSONException { public List<Repository> getRepositoriesOfUser(String userEmail, String page, String size) throws JSONException {
logger.debug("Retrieving repositories of authenticated user : " + userEmail); logger.debug("Retrieving repositories of authenticated user : " + userEmail);
Collection<String> repoIds = roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRoles(userEmail)); Collection<String> repoIds = roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRolesByEmail(userEmail));
return getRepositories(new ArrayList<>(repoIds)); return getRepositories(new ArrayList<>(repoIds));
} }
@ -355,7 +350,7 @@ public class RepositoryServiceImpl implements RepositoryService {
int to = from + Integer.parseInt(size); int to = from + Integer.parseInt(size);
List<String> repoIds = new ArrayList<>(); List<String> repoIds = new ArrayList<>();
if (userEmail != null && !"".equals(userEmail)) { if (userEmail != null && !"".equals(userEmail)) {
repoIds.addAll(roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRoles(userEmail))); repoIds.addAll(roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRolesByEmail(userEmail)));
} else { } else {
repoIds.addAll(roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRoles())); repoIds.addAll(roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRoles()));
} }

View File

@ -64,7 +64,7 @@ public class AuthoritiesUpdater extends HttpSessionSecurityContextRepository {
Authentication auth = SecurityContextHolder.getContext().getAuthentication(); Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth instanceof OIDCAuthenticationToken) { if (auth instanceof OIDCAuthenticationToken) {
OIDCAuthenticationToken oidcAuth = (OIDCAuthenticationToken) auth; OIDCAuthenticationToken oidcAuth = (OIDCAuthenticationToken) auth;
this.addRole(oidcAuth.getUserInfo().getEmail(), role); this.addRole(oidcAuth.getUserInfo().getSub(), role);
} else { } else {
throw new UnauthorizedClientException("User auth is not instance of OIDCAuthenticationToken"); throw new UnauthorizedClientException("User auth is not instance of OIDCAuthenticationToken");
} }
@ -82,7 +82,7 @@ public class AuthoritiesUpdater extends HttpSessionSecurityContextRepository {
Authentication auth = SecurityContextHolder.getContext().getAuthentication(); Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth instanceof OIDCAuthenticationToken) { if (auth instanceof OIDCAuthenticationToken) {
OIDCAuthenticationToken oidcAuth = (OIDCAuthenticationToken) auth; OIDCAuthenticationToken oidcAuth = (OIDCAuthenticationToken) auth;
this.removeRole(oidcAuth.getUserInfo().getEmail(), role); this.removeRole(oidcAuth.getUserInfo().getSub(), role);
} }
} }

View File

@ -38,22 +38,22 @@ public interface AuthorizationService {
/** /**
* Add a user as admin to a resource. * Add a user as admin to a resource.
* *
* @param id Resource id * @param resourceId Resource id
* @param email User email * @param email User email
* @return * @return
* @throws ResourceNotFoundException * @throws ResourceNotFoundException
*/ */
boolean addAdmin(String id, String email) throws ResourceNotFoundException; boolean addAdmin(String resourceId, String email) throws ResourceNotFoundException;
/** /**
* Remove user from resource admins. * Remove user from resource admins.
* *
* @param id Resource id * @param resourceId Resource id
* @param email User email * @param email User email
* @return * @return
* @throws ResourceNotFoundException * @throws ResourceNotFoundException
*/ */
boolean removeAdmin(String id, String email) throws ResourceNotFoundException; boolean removeAdmin(String resourceId, String email) throws ResourceNotFoundException;
/** /**
@ -69,6 +69,6 @@ public interface AuthorizationService {
* @param email * @param email
* @return * @return
*/ */
Collection<String> getUserRoles(String email); Collection<String> getUserRolesByEmail(String email);
} }

View File

@ -70,7 +70,6 @@ public class AuthorizationServiceImpl implements AuthorizationService {
@Override @Override
public List<User> getAdminsOfRepo(String repoId) { public List<User> getAdminsOfRepo(String repoId) {
List<String> userList = new ArrayList<>();
// find couId by role name // find couId by role name
String role = roleMappingService.getRoleIdByRepoId(repoId); String role = roleMappingService.getRoleIdByRepoId(repoId);
@ -80,17 +79,17 @@ public class AuthorizationServiceImpl implements AuthorizationService {
@Override @Override
public boolean addAdmin(String id, String email) throws ResourceNotFoundException { public boolean addAdmin(String resourceId, String email) throws ResourceNotFoundException {
Integer coPersonId = aaiRegistryService.getCoPersonIdByEmail(email); Integer coPersonId = aaiRegistryService.getCoPersonIdByEmail(email);
if (coPersonId != null) { if (coPersonId != null) {
String role = roleMappingService.getRoleIdByRepoId(id); String role = roleMappingService.getRoleIdByRepoId(resourceId);
Integer couId = aaiRegistryService.getCouId(role); Integer couId = aaiRegistryService.getCouId(role);
if (couId != null) { if (couId != null) {
Integer roleId = aaiRegistryService.getRoleId(coPersonId, couId); Integer roleId = aaiRegistryService.getRoleId(coPersonId, couId);
aaiRegistryService.assignMemberRole(coPersonId, couId, roleId); aaiRegistryService.assignMemberRole(coPersonId, couId, roleId);
// Add role to user current authorities // Add role to user current authorities
authoritiesUpdater.addRole(email, roleMappingService.convertRepoIdToAuthority(id)); authoritiesUpdater.addRole(email, roleMappingService.convertRepoIdToAuthority(resourceId));
return true; return true;
} else { } else {
@ -102,10 +101,10 @@ public class AuthorizationServiceImpl implements AuthorizationService {
} }
@Override @Override
public boolean removeAdmin(String id, String email) throws ResourceNotFoundException { public boolean removeAdmin(String resourceId, String email) throws ResourceNotFoundException {
Integer coPersonId = aaiRegistryService.getCoPersonIdByEmail(email); Integer coPersonId = aaiRegistryService.getCoPersonIdByEmail(email);
if (coPersonId != null) { if (coPersonId != null) {
String role = roleMappingService.getRoleIdByRepoId(id); String role = roleMappingService.getRoleIdByRepoId(resourceId);
Integer couId = aaiRegistryService.getCouId(role); Integer couId = aaiRegistryService.getCouId(role);
Integer roleId = null; Integer roleId = null;
if (couId != null) { if (couId != null) {
@ -115,7 +114,7 @@ public class AuthorizationServiceImpl implements AuthorizationService {
aaiRegistryService.removeMemberRole(coPersonId, couId, roleId); aaiRegistryService.removeMemberRole(coPersonId, couId, roleId);
// Remove role from user current authorities // Remove role from user current authorities
authoritiesUpdater.removeRole(email, roleMappingService.convertRepoIdToAuthority(id)); authoritiesUpdater.removeRole(email, roleMappingService.convertRepoIdToAuthority(resourceId));
return true; return true;
} else { } else {
@ -130,14 +129,16 @@ public class AuthorizationServiceImpl implements AuthorizationService {
public Collection<String> getUserRoles() { public Collection<String> getUserRoles() {
Collection<String> roles; Collection<String> roles;
UserInfo userInfo = ((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo(); UserInfo userInfo = ((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo();
roles = getUserRoles(userInfo.getEmail()); roles = getUserRolesByEmail(userInfo.getEmail());
logger.debug(String.format("User Roles: %s", String.join(",", roles))); if (logger.isDebugEnabled()) {
logger.debug("User Roles: {}", String.join(",", roles));
}
return roles; return roles;
} }
@Override @Override
public Collection<String> getUserRoles(String email) { public Collection<String> getUserRolesByEmail(String email) {
int coPersonId = aaiRegistryService.getCoPersonIdByEmail(email); int coPersonId = aaiRegistryService.getCoPersonIdByEmail(email);
List<Integer> list = new ArrayList<>(); List<Integer> list = new ArrayList<>();
for (JsonElement element : aaiRegistryService.getRolesWithStatus(coPersonId, AaiRegistryService.RoleStatus.ACTIVE)) { for (JsonElement element : aaiRegistryService.getRolesWithStatus(coPersonId, AaiRegistryService.RoleStatus.ACTIVE)) {