1
|
package eu.dnetlib.repo.manager.service.security;
|
2
|
|
3
|
import com.google.gson.JsonArray;
|
4
|
import com.google.gson.JsonElement;
|
5
|
import org.apache.log4j.Logger;
|
6
|
import org.springframework.security.core.GrantedAuthority;
|
7
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
8
|
|
9
|
import java.net.URLDecoder;
|
10
|
import java.util.*;
|
11
|
import java.util.regex.Matcher;
|
12
|
import java.util.regex.Pattern;
|
13
|
|
14
|
public class AuthoritiesMapper {
|
15
|
|
16
|
private static final Logger logger = Logger.getLogger(AuthoritiesMapper.class);
|
17
|
private static final String ENTITLEMENT_REGEX = "urn:geant:openaire[.]eu:group:([^:]*):?(.*)?:role=member#aai[.]openaire[.]eu";
|
18
|
|
19
|
private AuthoritiesMapper() {
|
20
|
}
|
21
|
|
22
|
public static Collection<GrantedAuthority> map(JsonArray entitlements) {
|
23
|
HashSet<GrantedAuthority> authorities = new HashSet<>();
|
24
|
entityRoles(entitlements, authorities);
|
25
|
return authorities;
|
26
|
}
|
27
|
|
28
|
public static List<String> entitlementRoles(JsonArray entitlements) {
|
29
|
List<String> roles = new ArrayList<>();
|
30
|
if (entitlements != null) {
|
31
|
for (JsonElement obj : entitlements) {
|
32
|
Matcher matcher = Pattern.compile(ENTITLEMENT_REGEX).matcher(obj.getAsString());
|
33
|
if (matcher.find()) {
|
34
|
StringBuilder sb = new StringBuilder();
|
35
|
if (matcher.group(1) != null && matcher.group(1).length() > 0) {
|
36
|
sb.append(matcher.group(1));
|
37
|
}
|
38
|
if (matcher.group(2).length() > 0) {
|
39
|
sb.append(":");
|
40
|
sb.append(matcher.group(2));
|
41
|
}
|
42
|
String role = sb.toString().replace("+", " ");
|
43
|
roles.add(URLDecoder.decode(role));
|
44
|
}
|
45
|
}
|
46
|
}
|
47
|
return roles;
|
48
|
}
|
49
|
|
50
|
private static void entityRoles(JsonArray entitlements, Set<GrantedAuthority> authorities) {
|
51
|
if (entitlements != null) {
|
52
|
for (JsonElement obj : entitlements) {
|
53
|
Matcher matcher = Pattern.compile(ENTITLEMENT_REGEX).matcher(obj.getAsString());
|
54
|
if (matcher.find()) {
|
55
|
StringBuilder sb = new StringBuilder();
|
56
|
if (matcher.group(1) != null && matcher.group(1).length() > 0) {
|
57
|
sb.append(matcher.group(1).replace("+-+", "_").replaceAll("[+.]", "_").toUpperCase());
|
58
|
}
|
59
|
if (matcher.group(2).length() > 0) {
|
60
|
sb.append("_");
|
61
|
if (matcher.group(2).equals("admins")) {
|
62
|
sb.append("MANAGER");
|
63
|
} else {
|
64
|
sb.append(matcher.group(2).toUpperCase());
|
65
|
}
|
66
|
}
|
67
|
authorities.add(new SimpleGrantedAuthority(sb.toString()));
|
68
|
}
|
69
|
}
|
70
|
}
|
71
|
}
|
72
|
|
73
|
}
|