74 lines
2.9 KiB
Java
74 lines
2.9 KiB
Java
package eu.dnetlib.repo.manager.service.security;
|
|
|
|
import com.google.gson.JsonArray;
|
|
import com.google.gson.JsonElement;
|
|
import org.apache.log4j.Logger;
|
|
import org.springframework.security.core.GrantedAuthority;
|
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
|
|
|
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 = Logger.getLogger(AuthoritiesMapper.class);
|
|
private static final String ENTITLEMENT_REGEX = "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) {
|
|
List<String> roles = new ArrayList<>();
|
|
if (entitlements != null) {
|
|
for (JsonElement obj : entitlements) {
|
|
Matcher matcher = Pattern.compile(ENTITLEMENT_REGEX).matcher(obj.getAsString());
|
|
if (matcher.find()) {
|
|
StringBuilder sb = new StringBuilder();
|
|
if (matcher.group(1) != null && matcher.group(1).length() > 0) {
|
|
sb.append(matcher.group(1));
|
|
}
|
|
if (matcher.group(2).length() > 0) {
|
|
sb.append(":");
|
|
sb.append(matcher.group(2));
|
|
}
|
|
String role = sb.toString().replace("+", " ");
|
|
roles.add(URLDecoder.decode(role));
|
|
}
|
|
}
|
|
}
|
|
return roles;
|
|
}
|
|
|
|
private static void entityRoles(JsonArray entitlements, Set<GrantedAuthority> authorities) {
|
|
if (entitlements != null) {
|
|
for (JsonElement obj : entitlements) {
|
|
Matcher matcher = Pattern.compile(ENTITLEMENT_REGEX).matcher(obj.getAsString());
|
|
if (matcher.find()) {
|
|
StringBuilder sb = new StringBuilder();
|
|
if (matcher.group(1) != null && matcher.group(1).length() > 0) {
|
|
sb.append(matcher.group(1).replace("+-+", "_").replaceAll("[+.]", "_").toUpperCase());
|
|
}
|
|
if (matcher.group(2).length() > 0) {
|
|
sb.append("_");
|
|
if (matcher.group(2).equals("admins")) {
|
|
sb.append("MANAGER");
|
|
} else {
|
|
sb.append(matcher.group(2).toUpperCase());
|
|
}
|
|
}
|
|
authorities.add(new SimpleGrantedAuthority(sb.toString()));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|