uoa-repository-manager-service/src/main/java/eu/dnetlib/repo/manager/service/security/AuthoritiesMapper.java

81 lines
3.1 KiB
Java

package eu.dnetlib.repo.manager.service.security;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.nimbusds.jose.util.StandardCharset;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AuthoritiesMapper {
private static final Logger logger = LoggerFactory.getLogger(AuthoritiesMapper.class);
private static final Pattern ENTITLEMENT_REGEX = Pattern.compile("urn:geant:openaire[.]eu:group:([^:]*):?(.*)?:role=member#aai[.]openaire[.]eu");
private AuthoritiesMapper() {
}
public static Collection<GrantedAuthority> map(JsonArray entitlements) {
HashSet<GrantedAuthority> authorities = new HashSet<>();
entityRoles(entitlements, authorities);
return authorities;
}
public static List<String> entitlementRoles(JsonArray entitlements) throws UnsupportedEncodingException {
List<String> roles = new ArrayList<>();
if (entitlements != null) {
for (JsonElement obj : entitlements) {
Matcher matcher = ENTITLEMENT_REGEX.matcher(obj.getAsString());
if (matcher.find()) {
StringBuilder sb = new StringBuilder();
String group1 = matcher.group(1);
if (group1 != null && group1.length() > 0) {
sb.append(group1);
}
String group2 = matcher.group(2);
if (group2.length() > 0) {
sb.append(":");
sb.append(group2);
}
String role = sb.toString().replace("+", " ");
roles.add(URLDecoder.decode(role, StandardCharset.UTF_8.name()));
}
}
}
return roles;
}
private static void entityRoles(JsonArray entitlements, Set<GrantedAuthority> authorities) {
if (entitlements != null) {
for (JsonElement obj : entitlements) {
Matcher matcher = ENTITLEMENT_REGEX.matcher(obj.getAsString());
if (matcher.find()) {
StringBuilder sb = new StringBuilder();
String group1 = matcher.group(1);
if (group1 != null && group1.length() > 0) {
sb.append(group1.replace("+-+", "_").replaceAll("[+.]", "_").toUpperCase());
}
String group2 = matcher.group(2);
if (group2.length() > 0) {
sb.append("_");
if (group2.equals("admins")) {
sb.append("MANAGER");
} else {
sb.append(group2.toUpperCase());
}
}
authorities.add(new SimpleGrantedAuthority(sb.toString()));
}
}
}
}
}