Project

General

Profile

« Previous | Next » 

Revision 61363

1. refactoring and changes of rest api

View differences:

modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/AaiRegistryService.java
3 3
import com.google.gson.JsonArray;
4 4
import com.google.gson.JsonObject;
5 5
import eu.dnetlib.repo.manager.domain.dto.Role;
6
import eu.dnetlib.repo.manager.domain.dto.User;
6 7

  
7 8
import java.util.List;
8 9
import java.util.Map;
......
247 248
     * @return
248 249
     */
249 250
    Map<Integer, String> getCouNames(List<Integer> couIds);
251

  
252
    // TODO: add description
253
    List<User> getUsers(Integer couId);
250 254
}
modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/RegistryCalls.java
4 4
import com.google.gson.JsonElement;
5 5
import com.google.gson.JsonObject;
6 6
import eu.dnetlib.repo.manager.domain.dto.Role;
7
import eu.dnetlib.repo.manager.domain.dto.User;
7 8
import eu.dnetlib.repo.manager.service.aai.registry.utils.RegistryUtils;
8 9
import eu.dnetlib.repo.manager.utils.HttpUtils;
9 10
import org.apache.log4j.Logger;
......
271 272
    }
272 273

  
273 274
    @Override
275
    public List<User> getUsers(Integer couId) {
276
        List<User> users = new ArrayList<>();
277
        JsonArray infos = getUserEmailByCouId(couId, false);
278

  
279
        infos.forEach(info -> {
280
            User user = new User();
281
            user.setEmail(info.getAsJsonObject().get("email").getAsString());
282

  
283
            users.add(user);
284
        });
285
        return users;
286
    }
287

  
288
    @Override
274 289
    public JsonArray getUserNamesByCouId(Integer couId, boolean admin) {
275 290
        Map<String, String> params = new HashMap<>();
276 291
        params.put("couid", couId.toString());
modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/service/RepositoryServiceImpl.java
13 13
import eu.dnetlib.repo.manager.domain.dto.Role;
14 14
import eu.dnetlib.repo.manager.exception.ResourceNotFoundException;
15 15
import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService;
16
import eu.dnetlib.repo.manager.service.security.AaiUserRoleService;
16
import eu.dnetlib.repo.manager.service.security.RoleMappingService;
17 17
import eu.dnetlib.repo.manager.service.security.AuthoritiesUpdater;
18 18
import eu.dnetlib.repo.manager.utils.Converter;
19 19
import gr.uoa.di.driver.enabling.vocabulary.VocabularyLoader;
......
30 30
import org.springframework.http.*;
31 31
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
32 32
import org.springframework.security.core.Authentication;
33
import org.springframework.security.core.authority.SimpleGrantedAuthority;
34 33
import org.springframework.security.core.context.SecurityContextHolder;
35 34
import org.springframework.stereotype.Service;
36 35
import org.springframework.web.client.HttpClientErrorException;
......
51 50

  
52 51
    private static final Logger LOGGER = Logger.getLogger(RepositoryServiceImpl.class);
53 52

  
54
    private final AaiUserRoleService aaiUserRoleService;
53
    private final RoleMappingService roleMappingService;
55 54
    private final AaiRegistryService registryCalls;
56 55
    private final AuthoritiesUpdater authoritiesUpdater;
57 56
    private final RestTemplate restTemplate;
......
85 84
    private HttpHeaders httpHeaders;
86 85

  
87 86
    @Autowired
88
    public RepositoryServiceImpl(AaiUserRoleService aaiUserRoleService,
87
    public RepositoryServiceImpl(RoleMappingService roleMappingService,
89 88
                                 AaiRegistryService registryCalls,
90 89
                                 AuthoritiesUpdater authoritiesUpdater,
91
                                 VocabularyLoader vocabularyLoader, EmailUtils emailUtils,
90
                                 VocabularyLoader vocabularyLoader,
92 91
                                 RestTemplate restTemplate,
92
                                 @Lazy EmailUtils emailUtils,
93 93
                                 @Lazy ValidatorService validatorService,
94 94
                                 @Lazy PiWikService piWikService) {
95
        this.aaiUserRoleService = aaiUserRoleService;
95
        this.roleMappingService = roleMappingService;
96 96
        this.registryCalls = registryCalls;
97 97
        this.authoritiesUpdater = authoritiesUpdater;
98 98
        this.vocabularyLoader = vocabularyLoader;
......
514 514

  
515 515
        // TODO: move the following code elsewhere (creation and assignment of role to user) ??
516 516
        // Create new role
517
        String newRoleName = aaiUserRoleService.getRoleIdByRepoId(repository.getId());
517
        String newRoleName = roleMappingService.getRoleIdByRepoId(repository.getId());
518 518
        Role newRole = new Role(newRoleName, repository.getOfficialName());
519 519
        Integer couId = null;
520 520
        try {
......
537 537
                registryCalls.assignMemberRole(coPersonId, couId, role);
538 538

  
539 539
                // Add role to current user authorities
540
                authoritiesUpdater.addRole(aaiUserRoleService.convertRepoIdToAuthority(repository.getId()));
540
                authoritiesUpdater.addRole(roleMappingService.convertRepoIdToAuthority(repository.getId()));
541 541
            } catch (Exception e) {
542 542
                LOGGER.debug("Exception on assign role to user during add repository", e);
543 543
                throw e;
......
686 686
        this.updateCompliance(repoId, repositoryInterface.getId(), repositoryInterface.getCompliance());
687 687
        this.updateValidationSet(repoId, repositoryInterface.getId(), repositoryInterface.getAccessSet());
688 688

  
689
        Repository e = this.getRepositoryById(repoId);
690
        emailUtils.sendAdminUpdateInterfaceEmail(e, comment, repositoryInterface, SecurityContextHolder.getContext().getAuthentication());
691
        emailUtils.sendUserUpdateInterfaceEmail(e, comment, repositoryInterface, SecurityContextHolder.getContext().getAuthentication());
689
        Repository repository = this.getRepositoryById(repoId);
690
        try {
691
            emailUtils.sendAdminUpdateInterfaceEmail(repository, comment, repositoryInterface, SecurityContextHolder.getContext().getAuthentication());
692
            emailUtils.sendUserUpdateInterfaceEmail(repository, comment, repositoryInterface, SecurityContextHolder.getContext().getAuthentication());
693
        } catch (Exception e) {
694
            LOGGER.warn("Could not send emails", e);
695
        }
696

  
692 697
        submitInterfaceValidation(getRepositoryById(repoId), registeredBy, repositoryInterface, true);
693 698

  
694 699
        return repositoryInterface;
modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/service/security/AaiUserRoleService.java
1
package eu.dnetlib.repo.manager.service.security;
2

  
3
import org.springframework.security.core.authority.SimpleGrantedAuthority;
4

  
5
public interface AaiUserRoleService {
6

  
7
    /**
8
     * @param fullName
9
     * @param prefix
10
     * @return
11
     */
12
    String getRepoNameWithoutType(String fullName, String prefix);
13

  
14
    /**
15
     * @param repoId Repository Id
16
     * @return Converts {@param repoId} to a role Id.
17
     */
18
    String getRoleIdByRepoId(String repoId);
19

  
20
    /**
21
     * @param repoId Repository Id
22
     * @return
23
     */
24
    String convertRepoIdToAuthorityId(String repoId);
25

  
26
    /**
27
     * @param repoId Repository Id
28
     * @return Converts {@param repoId} to {@link String} role id url encoded ($ -> %24)
29
     * // TODO: remove role encoding and perform url decoding when mapping authorities. (Must be performed in all OpenAIRE projects because of Redis)
30
     */
31
    String convertRepoIdToEncodedAuthorityId(String repoId);
32

  
33
    /**
34
     * @param repoId Repository Id
35
     * @return Converts {@param repoId} to {@link SimpleGrantedAuthority} with the role url encoded ($ -> %24)
36
     * // TODO: remove role encoding and perform url decoding when mapping authorities. (Must be performed in all OpenAIRE projects because of Redis)
37
     */
38
    SimpleGrantedAuthority convertRepoIdToAuthority(String repoId);
39

  
40
    /**
41
     * @param repoId Repository Id to check.
42
     * @return Checks if a user is a member of a repository or not.
43
     */
44
    boolean isMemberOf(String repoId);
45

  
46
}
modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/service/security/AaiUserRoleServiceImpl.java
1
package eu.dnetlib.repo.manager.service.security;
2

  
3
import org.apache.log4j.Logger;
4
import org.springframework.beans.factory.annotation.Value;
5
import org.springframework.security.core.authority.SimpleGrantedAuthority;
6
import org.springframework.security.core.context.SecurityContextHolder;
7
import org.springframework.stereotype.Service;
8

  
9
import java.net.URLEncoder;
10

  
11
@Service("aaiUserRoleService")
12
public class AaiUserRoleServiceImpl implements AaiUserRoleService {
13

  
14
    private static final Logger logger = Logger.getLogger(AaiUserRoleServiceImpl.class);
15

  
16
    @Value("${registry.production:true}")
17
    private boolean production;
18

  
19

  
20
    private String createRepoRoleName(String prefix, String repoId) {
21
        return prefix + "." + repoId.replace(":", "$");
22
    }
23

  
24
    @Override
25
    public String getRepoNameWithoutType(String fullName, String prefix) {
26
        if (fullName != null && prefix != null && fullName.startsWith(prefix)) {
27
            return fullName.substring(prefix.length());
28
        }
29
        return null;
30
    }
31

  
32
    @Override
33
    public String getRoleIdByRepoId(String repoId) {
34
        String roleId = "";
35
        String prefix = production ? null : "beta." + "datasource";
36
        if (repoId != null) {
37
            roleId = createRepoRoleName(prefix, repoId);
38
            return roleId;
39
        } else {
40
            return null;
41
        }
42

  
43
    }
44

  
45
    @Override
46
    public String convertRepoIdToAuthorityId(String repoId) {
47
        StringBuilder roleBuilder = new StringBuilder();
48
        String role = "";
49
        if (repoId != null) {
50
            roleBuilder.append(production ? "" : "beta.");
51
            roleBuilder.append("datasource.");
52
            roleBuilder.append(repoId.replace(":", "$"));
53
            role = roleBuilder.toString().replace(".", "_").toUpperCase();
54
        }
55
        return role;
56
    }
57

  
58
    @Override
59
    public String convertRepoIdToEncodedAuthorityId(String repoId) {
60
        return URLEncoder.encode(convertRepoIdToAuthorityId(repoId));
61
    }
62

  
63
    @Override
64
    public SimpleGrantedAuthority convertRepoIdToAuthority(String repoId) {
65
        String role = convertRepoIdToEncodedAuthorityId(repoId);
66
        return new SimpleGrantedAuthority(role);
67
    }
68

  
69

  
70
    @Override
71
    public boolean isMemberOf(String repoId) {
72
        String repoRole = convertRepoIdToEncodedAuthorityId(repoId);
73
        return SecurityContextHolder.getContext().getAuthentication().getAuthorities()
74
                .parallelStream().anyMatch(authority -> authority.toString().equals(repoRole));
75
    }
76
}
modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/service/security/AuthorizationService.java
1 1
package eu.dnetlib.repo.manager.service.security;
2 2

  
3
import eu.dnetlib.repo.manager.domain.dto.User;
4
import eu.dnetlib.repo.manager.exception.ResourceNotFoundException;
5

  
6
import java.util.List;
7

  
3 8
public interface AuthorizationService {
4 9

  
5 10
    /**
6
     *
7 11
     * @param type
8 12
     * @param id
9 13
     * @return
10 14
     */
11
    String member(String type, String id);
15
    String member(String type, String id); //TODO: use or delete
16

  
17
    /**
18
     * @param id Resource Id to check.
19
     * @return Checks if a user is a member of a resource.
20
     */
21
    boolean isMemberOf(String id);
22

  
23

  
24
    /**
25
     * Returns a list of admins of the resource.
26
     *
27
     * @param repoId
28
     * @return
29
     */
30
    List<User> getAdminsOfRepo(String repoId);
31

  
32
    /**
33
     * Add a user as admin to a resource.
34
     *
35
     * @param id    Resource id
36
     * @param email User email
37
     * @return
38
     * @throws ResourceNotFoundException
39
     */
40
    boolean addAdmin(String id, String email) throws ResourceNotFoundException;
41

  
42
    /**
43
     * Remove user from resource admins.
44
     *
45
     * @param id    Resource id
46
     * @param email User email
47
     * @return
48
     * @throws ResourceNotFoundException
49
     */
50
    boolean removeAdmin(String id, String email) throws ResourceNotFoundException;
12 51
}
modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/service/security/AuthorizationServiceImpl.java
1 1
package eu.dnetlib.repo.manager.service.security;
2 2

  
3
import org.springframework.stereotype.Component;
3
import com.google.gson.JsonArray;
4
import com.google.gson.JsonElement;
5
import eu.dnetlib.repo.manager.domain.dto.User;
6
import eu.dnetlib.repo.manager.exception.ResourceNotFoundException;
7
import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService;
8
import org.springframework.beans.factory.annotation.Autowired;
9
import org.springframework.security.core.context.SecurityContextHolder;
10
import org.springframework.stereotype.Service;
4 11

  
5
@Component("AuthorizationService")
12
import java.util.ArrayList;
13
import java.util.List;
14

  
15
@Service("authorizationService")
6 16
public class AuthorizationServiceImpl implements AuthorizationService {
7 17

  
8 18
    public final String ROLE_ADMIN = "ROLE_ADMIN";
9 19
    public final String ROLE_PROVIDE_ADMIN = "ROLE_PROVIDE_ADMIN";
10 20
    public final String ROLE_USER = "ROLE_USER";
11 21

  
22
    private final RoleMappingService roleMappingService;
23
    private final AaiRegistryService aaiRegistryService;
24
    private final AuthoritiesUpdater authoritiesUpdater;
25

  
26
    @Autowired
27
    AuthorizationServiceImpl(RoleMappingService roleMappingService, AaiRegistryService aaiRegistryService,
28
                             AuthoritiesUpdater authoritiesUpdater) {
29
        this.roleMappingService = roleMappingService;
30
        this.aaiRegistryService = aaiRegistryService;
31
        this.authoritiesUpdater = authoritiesUpdater;
32
    }
33

  
12 34
    private String mapType(String type) {
13 35
        if (type.equals("datasource")) {
14 36
            type = "datasource";
......
19 41
    /**
20 42
     * Type = DATASOURCE
21 43
     */
44
    @Override
22 45
    public String member(String type, String id) {
23 46
        return mapType(type).toUpperCase() + "_" + id.toUpperCase();
24 47
    }
25 48

  
49
    @Override
50
    public boolean isMemberOf(String repoId) {
51
        String repoRole = roleMappingService.convertRepoIdToEncodedAuthorityId(repoId);
52
        return SecurityContextHolder.getContext().getAuthentication().getAuthorities()
53
                .parallelStream().anyMatch(authority -> authority.toString().equals(repoRole));
54
    }
55

  
56
    @Override
57
    public List<User> getAdminsOfRepo(String repoId) {
58
        List<String> userList = new ArrayList<>();
59

  
60
        // find couId by role name
61
        String role = roleMappingService.getRoleIdByRepoId(repoId);
62
        Integer couId = aaiRegistryService.getCouId(role);
63
        if (couId != null) {
64
            JsonArray users = aaiRegistryService.getUsersByCouId(couId);
65
            for (JsonElement jsonElement : users) {
66
                userList.add(jsonElement.toString());
67
            }
68
        }
69
        return aaiRegistryService.getUsers(couId);
70
    }
71

  
72

  
73
    @Override
74
    public boolean addAdmin(String id, String email) throws ResourceNotFoundException {
75
        Integer coPersonId = aaiRegistryService.getCoPersonIdByEmail(email);
76
        if (coPersonId != null) {
77
            String role = roleMappingService.getRoleIdByRepoId(id);
78
            Integer couId = aaiRegistryService.getCouId(role);
79
            if (couId != null) {
80
                Integer roleId = aaiRegistryService.getRoleId(coPersonId, couId);
81
                aaiRegistryService.assignMemberRole(coPersonId, couId, roleId);
82

  
83
                // Add role to user current authorities
84
                authoritiesUpdater.addRole(email, roleMappingService.convertRepoIdToAuthority(id));
85

  
86
                return true;
87
            } else {
88
                throw new ResourceNotFoundException("Cannot find CouId for role: " + role);
89
            }
90
        } else {
91
            throw new ResourceNotFoundException("Cannot find coPersonId for user with email: " + email);
92
        }
93
    }
94

  
95
    @Override
96
    public boolean removeAdmin(String id, String email) throws ResourceNotFoundException {
97
        Integer coPersonId = aaiRegistryService.getCoPersonIdByEmail(email);
98
        if (coPersonId != null) {
99
            String role = roleMappingService.getRoleIdByRepoId(id);
100
            Integer couId = aaiRegistryService.getCouId(role);
101
            Integer roleId = null;
102
            if (couId != null) {
103
                roleId = aaiRegistryService.getRoleId(coPersonId, couId);
104
            }
105
            if (couId != null && roleId != null) {
106
                aaiRegistryService.removeMemberRole(coPersonId, couId, roleId);
107

  
108
                // Remove role from user current authorities
109
                authoritiesUpdater.removeRole(email, roleMappingService.convertRepoIdToAuthority(id));
110

  
111
                return true;
112
            } else {
113
                throw new ResourceNotFoundException("Cannot find CouId for role: " + role);
114
            }
115
        } else {
116
            throw new ResourceNotFoundException("Cannot find coPersonId for user with email: " + email);
117
        }
118
    }
119

  
26 120
}
modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/service/security/AuthoritiesMapper.java
6 6
import org.springframework.security.core.GrantedAuthority;
7 7
import org.springframework.security.core.authority.SimpleGrantedAuthority;
8 8

  
9
import java.net.URLDecoder;
9 10
import java.util.*;
10 11
import java.util.regex.Matcher;
11 12
import java.util.regex.Pattern;
......
13 14
public class AuthoritiesMapper {
14 15

  
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";
16 18

  
17 19
    private AuthoritiesMapper() {
18 20
    }
19 21

  
20
    public static Collection<? extends GrantedAuthority> map(JsonArray entitlements) {
21
        HashSet<SimpleGrantedAuthority> authorities = new HashSet<>();
22
        //entitlements.add("urn:geant:openaire.eu:group:datasource.opendoar____$$3469:role=member#aai.openaire.eu");
22
    public static Collection<GrantedAuthority> map(JsonArray entitlements) {
23
        HashSet<GrantedAuthority> authorities = new HashSet<>();
23 24
        provideRoles(entitlements, authorities);
24 25
        entityRoles(entitlements, authorities);
25 26
        return authorities;
26 27
    }
27 28

  
28
    private static void entityRoles(JsonArray entitlements, Set<SimpleGrantedAuthority> authorities) {
29
        String regex = "urn:geant:openaire[.]eu:group:([^:]*):?(.*)?:role=member#aai[.]openaire[.]eu";
30
        for (JsonElement obj : entitlements) {
31
            Matcher matcher = Pattern.compile(regex).matcher(obj.getAsString());
32
            if (matcher.find()) {
33
                StringBuilder sb = new StringBuilder();
34
                if (matcher.group(1) != null && matcher.group(1).length() > 0) {
35
                    sb.append(matcher.group(1).replace("+-+", "_").replaceAll("[+.]", "_").toUpperCase());
29
    public static List<String> entitlementRoles(JsonArray entitlements) {
30
        List<String> roles = new ArrayList<>();
31
        if (entitlements != null) {
32
            for (JsonElement obj : entitlements) {
33
                Matcher matcher = Pattern.compile(ENTITLEMENT_REGEX).matcher(obj.getAsString());
34
                if (matcher.find()) {
35
                    StringBuilder sb = new StringBuilder();
36
                    if (matcher.group(1) != null && matcher.group(1).length() > 0) {
37
                        sb.append(matcher.group(1));
38
                    }
39
                    if (matcher.group(2).length() > 0) {
40
                        sb.append(":");
41
                        sb.append(matcher.group(2));
42
                    }
43
                    String role = sb.toString().replace("+", " ");
44
                    roles.add(URLDecoder.decode(role));
36 45
                }
37
                if (matcher.group(2).length() > 0) {
38
                    sb.append("_");
39
                    if (matcher.group(2).equals("admins")) {
40
                        sb.append("MANAGER");
41
                    } else {
42
                        sb.append(matcher.group(2).toUpperCase());
46
            }
47
        }
48
        return roles;
49
    }
50

  
51
    private static void entityRoles(JsonArray entitlements, Set<GrantedAuthority> authorities) {
52
        if (entitlements != null) {
53
            for (JsonElement obj : entitlements) {
54
                Matcher matcher = Pattern.compile(ENTITLEMENT_REGEX).matcher(obj.getAsString());
55
                if (matcher.find()) {
56
                    StringBuilder sb = new StringBuilder();
57
                    if (matcher.group(1) != null && matcher.group(1).length() > 0) {
58
                        sb.append(matcher.group(1).replace("+-+", "_").replaceAll("[+.]", "_").toUpperCase());
43 59
                    }
60
                    if (matcher.group(2).length() > 0) {
61
                        sb.append("_");
62
                        if (matcher.group(2).equals("admins")) {
63
                            sb.append("MANAGER");
64
                        } else {
65
                            sb.append(matcher.group(2).toUpperCase());
66
                        }
67
                    }
68
                    authorities.add(new SimpleGrantedAuthority(sb.toString()));
44 69
                }
45
                authorities.add(new SimpleGrantedAuthority(sb.toString()));
46 70
            }
47 71
        }
48 72
    }
49 73

  
50 74
    // TODO: remove when ROLE_ADMIN and ROLE_PROVIDE_ADMIN are removed from project
51
    private static void provideRoles(JsonArray entitlements, Set<SimpleGrantedAuthority> authorities) {
75
    private static void provideRoles(JsonArray entitlements, Set<GrantedAuthority> authorities) {
52 76
        Map<String, String> userRoles = new HashMap() {{
53 77
            put("urn:geant:openaire.eu:group:Super+Administrator:role=member#aai.openaire.eu", "ROLE_ADMIN");
54 78
            put("urn:geant:openaire.eu:group:Content+Provider+Dashboard+Administrator:role=member#aai.openaire.eu", "ROLE_PROVIDE_ADMIN");
modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/service/security/AuthoritiesUpdater.java
26 26
    @Autowired
27 27
    FindByIndexNameSessionRepository sessions;
28 28

  
29
    public void update(String id, Collection<? extends GrantedAuthority> authorities) {
29
    public void update(String email, Collection<? extends GrantedAuthority> authorities) {
30 30
        if (sessions != null) {
31 31
            Map<String, ExpiringSession> map = sessions.
32
                    findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, id);
33
            logger.debug(map.values().toArray().length);
34
            for (ExpiringSession session : map.values()) {
35
                logger.debug(session.getId());
36
                if (!session.isExpired()) {
37
                    SecurityContext securityContext = session.getAttribute(SPRING_SECURITY_CONTEXT_KEY);
38
                    Authentication authentication = securityContext.getAuthentication();
39
                    if (authentication instanceof OIDCAuthenticationToken) {
40
                        OIDCAuthenticationToken authOIDC = (OIDCAuthenticationToken) authentication;
41
                        logger.debug(authorities);
42
                        securityContext.setAuthentication(new OIDCAuthenticationToken(authOIDC.getSub(), authOIDC.getIssuer(),
43
                                authOIDC.getUserInfo(), authorities, authOIDC.getIdToken(),
44
                                authOIDC.getAccessTokenValue(), authOIDC.getRefreshTokenValue()));
45
                        logger.debug("Update authorities");
46
                        session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, securityContext);
47
                        sessions.save(session);
32
                    findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, email);
33
            if (map != null) {
34
                logger.debug(map.values().toArray().length);
35
                for (ExpiringSession session : map.values()) {
36
                    logger.debug(session.getId());
37
                    if (!session.isExpired()) {
38
                        SecurityContext securityContext = session.getAttribute(SPRING_SECURITY_CONTEXT_KEY);
39
                        Authentication authentication = securityContext.getAuthentication();
40
                        if (authentication instanceof OIDCAuthenticationToken) {
41
                            OIDCAuthenticationToken authOIDC = (OIDCAuthenticationToken) authentication;
42
                            logger.debug(authorities);
43
                            securityContext.setAuthentication(new OIDCAuthenticationToken(authOIDC.getSub(), authOIDC.getIssuer(),
44
                                    authOIDC.getUserInfo(), authorities, authOIDC.getIdToken(),
45
                                    authOIDC.getAccessTokenValue(), authOIDC.getRefreshTokenValue()));
46
                            logger.debug("Update authorities");
47
                            session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, securityContext);
48
                            sessions.save(session);
49
                        }
48 50
                    }
49 51
                }
50 52
            }
51 53
        }
52 54
    }
53 55

  
54
    public void update(String id, Update update) {
56
    public void update(String email, Update update) {
55 57
        Collection<? extends GrantedAuthority> authorities = update.authorities(SecurityContextHolder.getContext().getAuthentication().getAuthorities());
56
        this.update(id, authorities);
58
        this.update(email, authorities);
57 59
    }
58 60

  
61
    public void addRole(String email, GrantedAuthority role) {
62
        this.update(email, old -> {
63
            HashSet<GrantedAuthority> authorities = new HashSet<>(old);
64
            authorities.add(role);
65
            return authorities;
66
        });
67
    }
68

  
59 69
    public void addRole(GrantedAuthority role) {
60 70
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
61 71
        if (auth instanceof OIDCAuthenticationToken) {
62 72
            OIDCAuthenticationToken oidcAuth = (OIDCAuthenticationToken) auth;
63
            this.update(oidcAuth.getUserInfo().getEmail(), old -> {
64
                HashSet<GrantedAuthority> authorities = new HashSet<>(old);
65
                authorities.add(role);
66
                return authorities;
67
            });
73
            this.addRole(oidcAuth.getUserInfo().getEmail(), role);
68 74
        } else {
69 75
            throw new UnauthorizedClientException("User auth is not instance of OIDCAuthenticationToken");
70 76
        }
71 77
    }
72 78

  
79
    public void removeRole(String email, GrantedAuthority role) {
80
        this.update(email, old -> {
81
            HashSet<GrantedAuthority> authorities = new HashSet<>(old);
82
            authorities.remove(role);
83
            return authorities;
84
        });
85
    }
86

  
73 87
    public void removeRole(GrantedAuthority role) {
74 88
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
75 89
        if (auth instanceof OIDCAuthenticationToken) {
76 90
            OIDCAuthenticationToken oidcAuth = (OIDCAuthenticationToken) auth;
77
            this.update(oidcAuth.getUserInfo().getEmail(), old -> {
78
                HashSet<GrantedAuthority> authorities = new HashSet<>(old);
79
                authorities.remove(role);
80
                return authorities;
81
            });
82
        } else {
83
            throw new UnauthorizedClientException("User auth is not instance of OIDCAuthenticationToken");
91
            this.removeRole(oidcAuth.getUserInfo().getEmail(), role);
84 92
        }
85 93
    }
86 94

  
modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/service/security/AaiRoleMappingService.java
1
package eu.dnetlib.repo.manager.service.security;
2

  
3
import org.apache.log4j.Logger;
4
import org.springframework.beans.factory.annotation.Value;
5
import org.springframework.security.core.GrantedAuthority;
6
import org.springframework.security.core.authority.SimpleGrantedAuthority;
7
import org.springframework.stereotype.Service;
8

  
9
import java.net.URLEncoder;
10

  
11
@Service("roleMappingService")
12
public class AaiRoleMappingService implements RoleMappingService {
13

  
14
    private static final Logger logger = Logger.getLogger(AaiRoleMappingService.class);
15

  
16
    @Value("${registry.production:true}")
17
    private boolean production;
18

  
19

  
20
    private String createRepoRoleName(String prefix, String repoId) {
21
        return prefix + "." + repoId.replace(":", "$");
22
    }
23

  
24
    @Override
25
    public String getRepoNameWithoutType(String fullName, String prefix) {
26
        if (fullName != null && prefix != null && fullName.startsWith(prefix)) {
27
            return fullName.substring(prefix.length());
28
        }
29
        return null;
30
    }
31

  
32
    @Override
33
    public String getRepoIdByRoleId(String roleId) {
34
        return roleId.replaceFirst(".*datasource\\.", "").replace("$", ":");
35
    }
36

  
37
    @Override
38
    public String getRoleIdByRepoId(String repoId) {
39
        String roleId = "";
40
        String prefix = production ? null : "beta." + "datasource";
41
        if (repoId != null) {
42
            roleId = createRepoRoleName(prefix, repoId);
43
            return roleId;
44
        } else {
45
            return null;
46
        }
47

  
48
    }
49

  
50
    @Override
51
    public String convertAuthorityIdToRepoId(String authorityId) {
52
        String repo = "";
53
        if (authorityId != null) {
54
            repo = authorityId
55
                    .replaceFirst(".*datasource\\.", "")
56
                    .replace("$", ":")
57
                    .toLowerCase();
58
        }
59
        return repo;
60
    }
61

  
62
    @Override
63
    public String convertAuthorityToRepoId(GrantedAuthority authority) {
64
        return convertAuthorityIdToRepoId(authority.toString());
65
    }
66

  
67
    @Override
68
    public String convertRepoIdToAuthorityId(String repoId) {
69
        StringBuilder roleBuilder = new StringBuilder();
70
        String role = "";
71
        if (repoId != null) {
72
            roleBuilder.append(production ? "" : "beta.");
73
            roleBuilder.append("datasource.");
74
            roleBuilder.append(repoId.replace(":", "$"));
75
            role = roleBuilder.toString().replace(".", "_").toUpperCase();
76
        }
77
        return role;
78
    }
79

  
80
    @Override
81
    public String convertRepoIdToEncodedAuthorityId(String repoId) {
82
        return URLEncoder.encode(convertRepoIdToAuthorityId(repoId));
83
    }
84

  
85
    @Override
86
    public SimpleGrantedAuthority convertRepoIdToAuthority(String repoId) {
87
        String role = convertRepoIdToEncodedAuthorityId(repoId);
88
        return new SimpleGrantedAuthority(role);
89
    }
90
}
modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/service/security/RoleMappingService.java
1
package eu.dnetlib.repo.manager.service.security;
2

  
3
import org.springframework.security.core.GrantedAuthority;
4
import org.springframework.security.core.authority.SimpleGrantedAuthority;
5

  
6
public interface RoleMappingService {
7

  
8
    /**
9
     * @param fullName
10
     * @param prefix
11
     * @return
12
     */
13
    String getRepoNameWithoutType(String fullName, String prefix);
14

  
15
    /**
16
     * @param roleId Role Id
17
     * @return Converts {@param roleId} to a repo Id.
18
     */
19
    String getRepoIdByRoleId(String roleId);
20

  
21
    /**
22
     * @param repoId Repository Id
23
     * @return Converts {@param repoId} to a role Id.
24
     */
25
    String getRoleIdByRepoId(String repoId);
26

  
27
    /**
28
     * @param authorityId Authority Id
29
     * @return Converts {@param authorityId} to repo Id.
30
     */
31
    String convertAuthorityIdToRepoId(String authorityId);
32

  
33
    /**
34
     * @param authority Granted authority
35
     * @return Converts {@param authority} to repo Id.
36
     */
37
    String convertAuthorityToRepoId(GrantedAuthority authority);
38

  
39
    /**
40
     * @param repoId Repository Id
41
     * @return
42
     */
43
    String convertRepoIdToAuthorityId(String repoId);
44

  
45
    /**
46
     * @param repoId Repository Id
47
     * @return Converts {@param repoId} to {@link String} role id url encoded ($ -> %24)
48
     * // TODO: remove role encoding and perform url decoding when mapping authorities. (Must be performed in all OpenAIRE projects because of Redis)
49
     */
50
    String convertRepoIdToEncodedAuthorityId(String repoId);
51

  
52
    /**
53
     * @param repoId Repository Id
54
     * @return Converts {@param repoId} to {@link SimpleGrantedAuthority} with the role url encoded ($ -> %24)
55
     * // TODO: remove role encoding and perform url decoding when mapping authorities. (Must be performed in all OpenAIRE projects because of Redis)
56
     */
57
    SimpleGrantedAuthority convertRepoIdToAuthority(String repoId);
58

  
59
}
modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/service/EmailUtilsImpl.java
33 33
    private boolean override = false, logonly = false;
34 34
    private String overrideEmail = null, from = null;
35 35

  
36
    @Autowired
37
    private MailLibrary mailLibrary;
36
    private final MailLibrary mailLibrary;
37
    private final CascadingPropertyLoader pLoader;
38
    private final RepositoryService repositoryService;
38 39

  
39
    @Autowired
40
    private CascadingPropertyLoader pLoader;
41

  
42 40
    @Value("${services.repo-manager.baseUrl}")
43 41
    private String baseUrl;
44 42

  
......
55 53
    private String valBaseUrl;
56 54

  
57 55
    @Autowired
58
    private RepositoryService repositoryService;
56
    EmailUtilsImpl(MailLibrary mailLibrary, CascadingPropertyLoader pLoader,
57
                   RepositoryService repositoryService) {
58
        this.mailLibrary = mailLibrary;
59
        this.pLoader = pLoader;
60
        this.repositoryService = repositoryService;
61
    }
59 62

  
60 63

  
61 64
    @PostConstruct
modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/utils/HttpUtils.java
36 36
        headers.setContentType(MediaType.APPLICATION_JSON);
37 37
        HttpEntity<String> request = new HttpEntity<>(body.toString(), headers);
38 38
        ResponseEntity<String> responseEntity = restTemplate.exchange(issuer + path, HttpMethod.POST, request, String.class);
39
        if (responseEntity.getBody() != null) {
40
            return new JsonParser().parse(responseEntity.getBody());
41
        } else {
42
            return null;
43
        }
39
        return getResponseEntityAsJsonElement(responseEntity);
44 40
    }
45 41

  
46 42
    public JsonElement put(String path, JsonObject body) {
......
49 45
        headers.setContentType(MediaType.APPLICATION_JSON);
50 46
        HttpEntity<String> request = new HttpEntity<>(body.toString(), headers);
51 47
        ResponseEntity<String> responseEntity = restTemplate.exchange(issuer + path, HttpMethod.PUT, request, String.class);
52
        if (responseEntity.getBody() != null) {
53
            return new JsonParser().parse(responseEntity.getBody());
54
        } else {
55
            return null;
56
        }
48
        return getResponseEntityAsJsonElement(responseEntity);
57 49
    }
58 50

  
59 51
    public JsonElement get(String path, Map<String, String> params) {
......
61 53
        String url = issuer + path + ((params != null) ? createParams(params) : null);
62 54
        ResponseEntity<String> responseEntity = restTemplate.exchange
63 55
                (url, HttpMethod.GET, new HttpEntity<>(createHeaders(user, password)), String.class);
64
        if (responseEntity.getBody() != null) {
65
            return new JsonParser().parse(responseEntity.getBody());
66
        } else {
67
            return null;
68
        }
56
        return getResponseEntityAsJsonElement(responseEntity);
69 57
    }
70 58

  
71 59
    public JsonElement delete(String path) {
......
73 61
        String url = issuer + path;
74 62
        ResponseEntity<String> responseEntity = restTemplate.exchange
75 63
                (url, HttpMethod.DELETE, new HttpEntity<>(createHeaders(user, password)), String.class);
76
        if (responseEntity.getBody() != null) {
77
            return new JsonParser().parse(responseEntity.getBody());
78
        } else {
79
            return null;
80
        }
64
        return getResponseEntityAsJsonElement(responseEntity);
81 65
    }
82 66

  
83 67

  
......
103 87
            set("Authorization", authHeader);
104 88
        }};
105 89
    }
90

  
91
    private JsonElement getResponseEntityAsJsonElement(ResponseEntity<String> responseEntity) {
92
        if (responseEntity != null && responseEntity.getBody() != null) {
93
            logger.info(responseEntity.getBody());
94
            try {
95
                return new JsonParser().parse(responseEntity.getBody());
96
            } catch (Exception e) {
97
                logger.warn("Could not parse response body", e);
98
            }
99
        }
100
        return null;
101
    }
106 102
}
modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/config/FrontEndLinkURIAuthenticationSuccessHandler.java
84 84
        accessToken.setPath("/");
85 85

  
86 86

  
87
        Cookie openAIREUser = new Cookie("openAIREUser", new Gson().toJson(userInfo));
87
        Cookie openAIREUser = new Cookie("openAIREUser", URLEncoder.encode(new Gson().toJson(userInfo), "UTF-8"));
88 88
        openAIREUser.setMaxAge(accessToken.getMaxAge());
89 89
        openAIREUser.setPath("/");
90 90
        if (aai_mode.equalsIgnoreCase("production") || aai_mode.equalsIgnoreCase("beta"))
modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/config/OpenAIREAuthoritiesMapper.java
6 6
import org.apache.log4j.Logger;
7 7
import org.mitre.openid.connect.client.OIDCAuthoritiesMapper;
8 8
import org.mitre.openid.connect.model.UserInfo;
9
import org.springframework.beans.factory.annotation.Value;
9 10
import org.springframework.context.annotation.ComponentScan;
10 11
import org.springframework.security.core.GrantedAuthority;
12
import org.springframework.security.core.authority.SimpleGrantedAuthority;
11 13
import org.springframework.stereotype.Component;
12 14

  
15
import java.util.ArrayList;
13 16
import java.util.Collection;
17
import java.util.List;
14 18

  
15 19
@ComponentScan
16 20
@Component
17 21
public class OpenAIREAuthoritiesMapper implements OIDCAuthoritiesMapper {
18 22

  
19 23
    private static final Logger logger = Logger.getLogger(OpenAIREAuthoritiesMapper.class);
24

  
25
    @Value("${services.repo-manager.adminEmail}")
26
    String adminEmail;
27

  
20 28
    @Override
21 29
    public Collection<? extends GrantedAuthority> mapAuthorities(JWT jwtToken, UserInfo userInfo) {
22
        logger.info("entitlements" + userInfo.getSource().getAsJsonArray("edu_person_entitlements").size());
23
        JsonArray entitlements = userInfo.getSource().getAsJsonArray("edu_person_entitlements");
24
        return AuthoritiesMapper.map(entitlements);
30
        JsonArray entitlements = null;
31
        List<GrantedAuthority> authorities = new ArrayList<>();
32
        if (userInfo != null && userInfo.getSource() != null) {
33
            if (userInfo.getSource().getAsJsonArray("edu_person_entitlements") != null) {
34
                entitlements = userInfo.getSource().getAsJsonArray("edu_person_entitlements");
35
            } else if (userInfo.getSource().getAsJsonArray("eduperson_entitlement") != null) {
36
                entitlements = userInfo.getSource().getAsJsonArray("eduperson_entitlement");
37
            } else {
38
                authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
39
                logger.error("Could not read user 'edu_person_entitlements' && 'eduperson_entitlement'\nAdding default role 'ROLE_USER' to user: " + userInfo.toString());
40
            }
41
            logger.debug("user info: " + userInfo + "\nentitlements: " + entitlements);
42

  
43
            // FIXME: delete this if statement
44
            if (userInfo.getEmail() != null && userInfo.getEmail().equals(adminEmail)) {
45
                authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
46
            }
47

  
48
            authorities.addAll(AuthoritiesMapper.map(entitlements));
49
        }
50
        return authorities;
25 51
    }
26 52
}
27 53

  
modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/controllers/AaiUserRoleController.java
1
package eu.dnetlib.repo.manager.controllers;
2

  
3
import com.google.gson.JsonArray;
4
import com.google.gson.JsonElement;
5
import eu.dnetlib.repo.manager.domain.dto.Role;
6
import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService;
7
import eu.dnetlib.repo.manager.service.security.AaiUserRoleService;
8
import eu.dnetlib.repo.manager.service.security.AuthoritiesUpdater;
9
import eu.dnetlib.repo.manager.utils.JsonUtils;
10
import io.swagger.annotations.Api;
11
import io.swagger.annotations.ApiOperation;
12
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
13
import org.springframework.beans.factory.annotation.Autowired;
14
import org.springframework.http.HttpStatus;
15
import org.springframework.http.ResponseEntity;
16
import org.springframework.security.access.prepost.PreAuthorize;
17
import org.springframework.security.core.context.SecurityContextHolder;
18
import org.springframework.web.bind.annotation.*;
19

  
20
import javax.ws.rs.core.MediaType;
21
import javax.ws.rs.core.Response;
22
import java.util.ArrayList;
23
import java.util.List;
24

  
25
@RestController
26
@RequestMapping(value = "/aai-user-management")
27
@Api(description = "AAI User Management", value = "aai-user-management")
28
public class AaiUserRoleController {
29

  
30
    private final AaiRegistryService aaiRegistryService;
31
    private final AuthoritiesUpdater authoritiesUpdater;
32
    private final AaiUserRoleService aaiUserRoleService;
33

  
34
    @Autowired
35
    AaiUserRoleController(AaiRegistryService aaiRegistryService,
36
                          AuthoritiesUpdater authoritiesUpdater,
37
                          AaiUserRoleService aaiUserRoleService) {
38
        this.aaiRegistryService = aaiRegistryService;
39
        this.authoritiesUpdater = authoritiesUpdater;
40
        this.aaiUserRoleService = aaiUserRoleService;
41
    }
42

  
43
    private String sendEmail() {
44
        OIDCAuthenticationToken authenticationToken = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
45
        return authenticationToken.getUserInfo().getEmail();
46
    }
47

  
48
    /**
49
     * Get the role with the given name and description.
50
     **/
51
    @RequestMapping(method = RequestMethod.GET, path = "/role/id/get")
52
//    @PreAuthorize("hasAnyAuthority('ROLE_USER', 'ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN')")
53
    public Response getRole(@RequestParam(value = "type", defaultValue = "datasource") String type, @RequestParam("id") String id) {
54
        int roleId = aaiRegistryService.getCouId(type, id);
55
        return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role id is: " + roleId).toString()).type(MediaType.APPLICATION_JSON).build();
56
    }
57

  
58
    /**
59
     * Create a new role with the given name and description.
60
     **/
61
    @RequestMapping(method = RequestMethod.POST, path = "/createRole")
62
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
63
    public Response createRole(@RequestBody Role role) {
64
        aaiRegistryService.createRole(role);
65
        return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been created").toString()).type(MediaType.APPLICATION_JSON).build();
66
    }
67

  
68
    /**
69
     * Subscribe to a type(Community, etc.) with id(ee, egi, etc.)
70
     */
71
    @ApiOperation(value = "subscribe")
72
    @RequestMapping(method = RequestMethod.POST, path = "/subscribe/{type}/{id}")
73
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN')")
74
    public Response subscribe(@PathVariable("type") String type, @PathVariable("id") String id) {
75
        Integer coPersonId = aaiRegistryService.getCoPersonIdByIdentifier();
76
        if (coPersonId == null) {
77
            coPersonId = aaiRegistryService.getCoPersonIdByEmail();
78
        }
79
        Integer couId = aaiRegistryService.getCouId(type, id);
80
        if (couId != null) {
81
            Integer role = aaiRegistryService.getRoleId(coPersonId, couId);
82
            aaiRegistryService.assignMemberRole(coPersonId, couId, role);
83

  
84
            // Add role to current user authorities
85
            authoritiesUpdater.addRole(aaiUserRoleService.convertRepoIdToAuthority(id));
86

  
87
            return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build();
88
        } else {
89
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(JsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
90
        }
91
    }
92

  
93

  
94
    /**
95
     * Remove the member role from user with email for a type(Community, etc.) with id(ee, egi, etc.)
96
     */
97
    @ApiOperation(value = "Remove role from member")
98
    @RequestMapping(method = RequestMethod.DELETE, path = "/{type}/{id}/member/{email}")
99
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN')") // FIXME: ??
100
    public Response removeMemberRole(@PathVariable("type") String type, @PathVariable("id") String
101
            id, @PathVariable("email") String email) {
102
        Integer coPersonId = aaiRegistryService.getCoPersonIdByEmail(email);
103
        if (coPersonId != null) {
104
            Integer couId = aaiRegistryService.getCouId(type, id);
105
            Integer role = null;
106
            if (couId != null) {
107
                role = aaiRegistryService.getRoleId(coPersonId, couId);
108
            }
109
            if (couId != null && role != null) {
110
                aaiRegistryService.removeMemberRole(coPersonId, couId, role);
111

  
112
                // Remove role from current user authorities
113
                authoritiesUpdater.removeRole(aaiUserRoleService.convertRepoIdToAuthority(id));
114

  
115
                return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been removed").toString()).type(MediaType.APPLICATION_JSON).build();
116
            } else {
117
                return Response.status(HttpStatus.NOT_FOUND.value()).entity(JsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
118
            }
119
        } else {
120
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(JsonUtils.createResponse("User has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
121
        }
122
    }
123

  
124

  
125
    /**
126
     * Subscribe to role-repo by his email
127
     */
128
    @RequestMapping(method = RequestMethod.POST, path = "/subscribe/repo-role/{id}")
129
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN') or @aaiUserRoleService.isMemberOf(#id)")
130
    public Response subscribeRoleByEmail(@PathVariable("id") String id, @RequestParam("email") String email) {
131
        Integer coPersonId = aaiRegistryService.getCoPersonIdByEmail(email);
132
        if (coPersonId != null) {
133
            Integer couId = aaiRegistryService.getCouId("datasource", id);
134
            if (couId != null) {
135
                Integer role = aaiRegistryService.getRoleId(coPersonId, couId);
136
                aaiRegistryService.assignMemberRole(coPersonId, couId, role);
137

  
138
                // Add role to current user authorities
139
                authoritiesUpdater.addRole(aaiUserRoleService.convertRepoIdToAuthority(id));
140

  
141
                return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build();
142
            } else {
143
                return Response.status(HttpStatus.NOT_FOUND.value()).entity(JsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
144
            }
145
        } else {
146
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(JsonUtils.createResponse("User with this email has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
147
        }
148

  
149

  
150
    }
151

  
152

  
153
    /**
154
     * Get all the users that have the role that is associated with repoId
155
     */
156
    @RequestMapping(method = RequestMethod.GET, path = "/repo/{id}/all-users")
157
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN')") // FIXME: ??
158
    public ResponseEntity<List<String>> getAllUsersOfARepo(@PathVariable("id") String id) {
159

  
160
        List<String> userList = new ArrayList<>();
161

  
162
        // find couId by role name
163
        Integer couId = aaiRegistryService.getCouId("datasource", id);
164
        if (couId != null) {
165
            JsonArray users = aaiRegistryService.getUsersByCouId(couId);
166
            for (JsonElement jsonElement : users) {
167
                userList.add(jsonElement.toString());
168
            }
169
            return ResponseEntity.ok(userList);
170
        }
171

  
172
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
173
    }
174
    /////////////////////////////////////////////////////////////////////////////////////////////
175
    /////////////////////////////////////////////////////////////////////////////////////////////
176

  
177
    @RequestMapping(method = RequestMethod.GET, path = "/users/couid/{id}")
178
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN')")
179
    public ResponseEntity<String> getUsersByCouId(@PathVariable("id") Integer id) {
180
//        calls.getUserByCoId()
181
        return ResponseEntity.ok(aaiRegistryService.getUsersByCouId(id).toString());
182
    }
183

  
184

  
185
    @RequestMapping(method = RequestMethod.GET, path = "/user/roles")
186
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN') or hasRole('ROLE_USER') and authentication.userInfo.email==#email")
187
    public ResponseEntity<List<String>> getRolesByEmail(@RequestParam("email") String email) {
188
        int coPersonId = aaiRegistryService.getCoPersonIdByEmail(email);
189
        List<String> list = new ArrayList<>();
190
        for (JsonElement element : aaiRegistryService.getRoles(coPersonId)) {
191
            list.add(element.toString());
192
        }
193
        return ResponseEntity.ok(list);
194
    }
195

  
196
}
modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/controllers/RepositoryController.java
3 3
import eu.dnetlib.domain.data.Repository;
4 4
import eu.dnetlib.domain.data.RepositoryInterface;
5 5
import eu.dnetlib.repo.manager.domain.*;
6
import eu.dnetlib.repo.manager.domain.dto.User;
6 7
import eu.dnetlib.repo.manager.exception.ResourceNotFoundException;
7 8
import eu.dnetlib.repo.manager.service.RepositoryServiceImpl;
9
import eu.dnetlib.repo.manager.service.security.AuthorizationService;
10
import eu.dnetlib.repo.manager.utils.JsonUtils;
8 11
import io.swagger.annotations.Api;
9 12
import org.apache.log4j.Logger;
10 13
import org.json.JSONException;
11 14
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
12 15
import org.springframework.beans.factory.annotation.Autowired;
16
import org.springframework.http.HttpStatus;
13 17
import org.springframework.http.MediaType;
18
import org.springframework.http.ResponseEntity;
14 19
import org.springframework.security.access.prepost.PostAuthorize;
15 20
import org.springframework.security.access.prepost.PreAuthorize;
16 21
import org.springframework.security.core.Authentication;
17 22
import org.springframework.security.core.context.SecurityContextHolder;
18 23
import org.springframework.web.bind.annotation.*;
19 24

  
25
import javax.ws.rs.core.Response;
20 26
import java.io.IOException;
21 27
import java.util.List;
22 28
import java.util.Map;
......
28 34

  
29 35
    private static final Logger logger = Logger.getLogger(RepositoryController.class);
30 36

  
37
    private final RepositoryServiceImpl repositoryService; //TODO: why not RepositoryService??
38
    private final AuthorizationService authorizationService;
39

  
31 40
    @Autowired
32
    private RepositoryServiceImpl repositoryService;
41
    RepositoryController(RepositoryServiceImpl repositoryService,
42
                         AuthorizationService authorizationService) {
43
        this.repositoryService = repositoryService;
44
        this.authorizationService = authorizationService;
45
    }
33 46

  
34 47

  
35 48
    @RequestMapping(value = "/getCountries", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
......
87 100
    @RequestMapping(value = "/getRepositoryById/{id}", method = RequestMethod.GET,
88 101
            produces = MediaType.APPLICATION_JSON_VALUE)
89 102
    @ResponseBody
90
    @PostAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN') or @aaiUserRoleService.isMemberOf(#id) or (returnObject.registeredBy=='null' and hasRole('ROLE_USER'))")
103
    @PostAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN') or @authorizationService.isMemberOf(#id) or (returnObject.registeredBy=='null' and hasRole('ROLE_USER'))")
91 104
    public Repository getRepositoryById(@PathVariable("id") String id) throws JSONException, ResourceNotFoundException {
92 105
        Repository repo = repositoryService.getRepositoryById(id);
93 106

  
......
124 137
    @RequestMapping(value = "/getRepositoryInterface/{id}", method = RequestMethod.GET,
125 138
            produces = MediaType.APPLICATION_JSON_VALUE)
126 139
    @ResponseBody
127
    @PostAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or @aaiUserRoleService.isMemberOf(#id) or (@repositoryService.getRepositoryById(#id).registeredBy=='null' and hasRole('ROLE_USER'))")
140
    @PostAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or @authorizationService.isMemberOf(#id) or (@repositoryService.getRepositoryById(#id).registeredBy=='null' and hasRole('ROLE_USER'))")
128 141
    public List<RepositoryInterface> getRepositoryInterface(@PathVariable("id") String id) throws JSONException {
129 142
        return repositoryService.getRepositoryInterface(id);
130 143
    }
......
132 145
    @RequestMapping(value = "/addRepository", method = RequestMethod.POST,
133 146
            consumes = MediaType.APPLICATION_JSON_VALUE)
134 147
    @ResponseBody
135
//    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or (hasRole(@aaiUserRoleService.convertRepoIdToRoleId(#repository.id)) or hasRole(@aaiUserRoleService.convertRepoIdToRoleId(returnObject.id)))")
148
//    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or (hasRole(@authorizationService.convertRepoIdToRoleId(#repository.id)) or hasRole(@authorizationService.convertRepoIdToRoleId(returnObject.id)))")
136 149
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or hasRole('ROLE_USER')")
137 150
    public Repository addRepository(@RequestParam("datatype") String datatype,
138 151
                                    @RequestBody Repository repository) throws Exception {
......
164 177
    @RequestMapping(value = "/updateRepository", method = RequestMethod.POST,
165 178
            consumes = MediaType.APPLICATION_JSON_VALUE)
166 179
    @ResponseBody
167
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or @aaiUserRoleService.isMemberOf(#repository.id)")
180
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or @authorizationService.isMemberOf(#repository.id)")
168 181
    public Repository updateRepository(@RequestBody Repository repository, Authentication authentication) throws Exception {
169 182
        return repositoryService.updateRepository(repository, authentication);
170 183
    }
171 184

  
172 185
    @RequestMapping(value = "/deleteInterface/", method = RequestMethod.DELETE)
173
    @PreAuthorize("@aaiUserRoleService.isMemberOf(#id)")
186
    @PreAuthorize("@authorizationService.isMemberOf(#id)")
174 187
    public void deleteRepositoryInterface(@RequestParam("id") String id,
175 188
                                          @RequestParam("registeredBy") String registeredBy) {
176 189
        repositoryService.deleteRepositoryInterface(id, registeredBy);
......
179 192
    @RequestMapping(value = "/addInterface", method = RequestMethod.POST,
180 193
            consumes = MediaType.APPLICATION_JSON_VALUE)
181 194
    @ResponseBody
182
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or @aaiUserRoleService.isMemberOf(#repoId)")
195
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or @authorizationService.isMemberOf(#repoId)")
183 196
    public RepositoryInterface addRepositoryInterface(@RequestParam("datatype") String datatype,
184 197
                                                      @RequestParam("repoId") String repoId,
185 198
                                                      @RequestParam("registeredBy") String registeredBy,
......
235 248
    @RequestMapping(value = "/updateRepositoryInterface", method = RequestMethod.POST,
236 249
            consumes = MediaType.APPLICATION_JSON_VALUE)
237 250
    @ResponseBody
238
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or @aaiUserRoleService.isMemberOf(#repoId)")
251
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or @authorizationService.isMemberOf(#repoId)")
239 252
    public RepositoryInterface updateRepositoryInterface(@RequestParam("repoId") String repoId,
240 253
                                                         @RequestParam("registeredBy") String registeredBy,
241 254
                                                         @RequestParam(value = "comment", required = false) String comment,
242 255
                                                         @RequestBody RepositoryInterface repositoryInterface) throws Exception {
243 256
        return repositoryService.updateRepositoryInterface(repoId, registeredBy, comment, repositoryInterface);
244 257
    }
258

  
259

  
260
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
261
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
262

  
263
    /**
264
     * Get all the admins of the repository
265
     */
266
    @RequestMapping(method = RequestMethod.GET, path = "{repoId}/admins")
267
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN') or @authorizationService.isMemberOf(#id)")
268
    public ResponseEntity<List<User>> getAdminsOfARepo(@PathVariable("repoId") String id) {
269
        return new ResponseEntity<>(authorizationService.getAdminsOfRepo(id), HttpStatus.OK);
270
    }
271

  
272
    /**
273
     * Subscribe to repo by email
274
     */
275
    @RequestMapping(method = RequestMethod.POST, path = "{repoId}/admins")
276
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN') or @authorizationService.isMemberOf(#id)")
277
    public Response subscribeByEmail(@PathVariable("repoId") String id, @RequestBody String email) throws ResourceNotFoundException {
278
        authorizationService.addAdmin(id, email);
279
        return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been assigned").toString()).type(javax.ws.rs.core.MediaType.APPLICATION_JSON).build();
280
    }
281

  
282
    /**
283
     * Unsubscribe from repo by email
284
     */
285
    @RequestMapping(method = RequestMethod.DELETE, path = "{repoId}/admins/{email}")
286
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN') or @authorizationService.isMemberOf(#id)")
287
    public Response unsubscribeByEmail(@PathVariable("id") String id, @RequestBody String email) throws ResourceNotFoundException {
288
        authorizationService.removeAdmin(id, email);
289
        return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been removed").toString()).type(javax.ws.rs.core.MediaType.APPLICATION_JSON).build();
290
    }
245 291
}
modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/controllers/UserRoleController.java
1
package eu.dnetlib.repo.manager.controllers;
2

  
3
import com.google.gson.JsonArray;
4
import com.google.gson.JsonElement;
5
import eu.dnetlib.repo.manager.domain.dto.Role;
6
import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService;
7
import eu.dnetlib.repo.manager.service.security.RoleMappingService;
8
import eu.dnetlib.repo.manager.service.security.AuthoritiesMapper;
9
import eu.dnetlib.repo.manager.service.security.AuthoritiesUpdater;
10
import eu.dnetlib.repo.manager.utils.JsonUtils;
11
import io.swagger.annotations.Api;
12
import io.swagger.annotations.ApiOperation;
13
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
14
import org.mitre.openid.connect.model.UserInfo;
15
import org.springframework.beans.factory.annotation.Autowired;
16
import org.springframework.http.HttpStatus;
17
import org.springframework.http.ResponseEntity;
18
import org.springframework.security.access.prepost.PreAuthorize;
19
import org.springframework.security.core.context.SecurityContextHolder;
20
import org.springframework.web.bind.annotation.*;
21

  
22
import javax.ws.rs.core.MediaType;
23
import javax.ws.rs.core.Response;
24
import java.util.ArrayList;
25
import java.util.Collection;
26
import java.util.List;
27

  
28
@RestController
29
@RequestMapping(value = "/role-management")
30
@Api(description = "Role Management", value = "role-management")
31
public class UserRoleController {
32

  
33
    private final AaiRegistryService aaiRegistryService;
34
    private final AuthoritiesUpdater authoritiesUpdater;
35
    private final RoleMappingService roleMappingService;
36

  
37
    @Autowired
38
    UserRoleController(AaiRegistryService aaiRegistryService,
39
                       AuthoritiesUpdater authoritiesUpdater,
40
                       RoleMappingService roleMappingService) {
41
        this.aaiRegistryService = aaiRegistryService;
42
        this.authoritiesUpdater = authoritiesUpdater;
43
        this.roleMappingService = roleMappingService;
44
    }
45

  
46
    /**
47
     * Get the role with the given id.
48
     **/
49
    @RequestMapping(method = RequestMethod.GET, path = "/role/{id}")
50
//    @PreAuthorize("hasAnyAuthority('ROLE_USER', 'ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN')")
51
    public Response getRole(@RequestParam(value = "type", defaultValue = "datasource") String type, @PathVariable("id") String id) {
52
        int roleId = aaiRegistryService.getCouId(type, id);
53
        return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role id is: " + roleId).toString()).type(MediaType.APPLICATION_JSON).build();
54
    }
55

  
56
    /**
57
     * Create a new role with the given name and description.
58
     **/
59
    @RequestMapping(method = RequestMethod.POST, path = "/role")
60
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
61
    public Response createRole(@RequestBody Role role) {
62
        aaiRegistryService.createRole(role);
63
        return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been created").toString()).type(MediaType.APPLICATION_JSON).build();
64
    }
65

  
66
    /**
67
     * Subscribe to a type(Community, etc.) with id(ee, egi, etc.)
68
     */
69
    @ApiOperation(value = "subscribe")
70
    @RequestMapping(method = RequestMethod.POST, path = "/subscribe/{type}/{id}")
71
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN')")
72
    public Response subscribe(@PathVariable("type") String type, @PathVariable("id") String id) {
73
        Integer coPersonId = aaiRegistryService.getCoPersonIdByIdentifier();
74
        if (coPersonId == null) {
75
            coPersonId = aaiRegistryService.getCoPersonIdByEmail();
76
        }
77
        Integer couId = aaiRegistryService.getCouId(type, id);
78
        if (couId != null) {
79
            Integer role = aaiRegistryService.getRoleId(coPersonId, couId);
80
            aaiRegistryService.assignMemberRole(coPersonId, couId, role);
81

  
82
            // Add role to current authorities
83
            authoritiesUpdater.addRole(roleMappingService.convertRepoIdToAuthority(id));
84

  
85
            return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build();
86
        } else {
87
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(JsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
88
        }
89
    }
90
    /////////////////////////////////////////////////////////////////////////////////////////////
91
    /////////////////////////////////////////////////////////////////////////////////////////////
92

  
93
    @RequestMapping(method = RequestMethod.GET, path = "/users/couid/{id}")
94
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN')")
95
    public ResponseEntity<String> getUsersByCouId(@PathVariable("id") Integer id) {
96
//        calls.getUserByCoId()
97
        return ResponseEntity.ok(aaiRegistryService.getUsersByCouId(id).toString());
98
    }
99

  
100

  
101
    @RequestMapping(method = RequestMethod.GET, path = "/users/{email}/roles")
102
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN') or hasRole('ROLE_USER') and authentication.userInfo.email==#email")
103
    public ResponseEntity<Collection<String>> getRolesByEmail(@PathVariable("email") String email) {
104
        int coPersonId = aaiRegistryService.getCoPersonIdByEmail(email);
105
        List<Integer> list = new ArrayList<>();
106
        // FIXME: getRoles returns all roles of user, requested and active
107
        for (JsonElement element : aaiRegistryService.getRoles(coPersonId)) {
108
            list.add(element.getAsJsonObject().get("CouId").getAsInt());
109
        }
110
        return ResponseEntity.ok(aaiRegistryService.getCouNames(list).values());
111
    }
112

  
113

  
114
    @RequestMapping(method = RequestMethod.GET, path = "/user/roles/my")
115
    @PreAuthorize("hasRole('ROLE_USER')")
116
    public ResponseEntity<Collection<String>> getRoleNames() {
117
        List<String> roles;
118
        JsonArray entitlements = null;
119
        UserInfo userInfo = ((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo();
120
        if (userInfo.getSource().getAsJsonArray("edu_person_entitlements") != null) {
121
            entitlements = userInfo.getSource().getAsJsonArray("edu_person_entitlements");
122
        } else if (userInfo.getSource().getAsJsonArray("eduperson_entitlement") != null) {
123
            entitlements = userInfo.getSource().getAsJsonArray("eduperson_entitlement");
124
        } else {
125
            return ResponseEntity.ok(null);
126
        }
127
        roles = AuthoritiesMapper.entitlementRoles(entitlements);
128
        return ResponseEntity.ok(roles);
129
    }
130

  
131
}
modules/uoa-repository-manager-service/branches/aai_roles_new/src/main/java/eu/dnetlib/repo/manager/controllers/PiWikController.java
42 42

  
43 43
    @RequestMapping(value = "/getPiwikSiteForRepo/{repositoryId}" , method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
44 44
    @ResponseBody
45
    @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN') or @aaiUserRoleService.isMemberOf(#repositoryId) or (@repositoryService.getRepositoryById(#repositoryId).registeredBy=='null' and hasRole('ROLE_USER'))")
45
    @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN') or @authorizationService.isMemberOf(#repositoryId) or (@repositoryService.getRepositoryById(#repositoryId).registeredBy=='null' and hasRole('ROLE_USER'))")
46 46
    public PiwikInfo getPiwikSiteForRepo(@PathVariable("repositoryId") String repositoryId) {
47 47
        return piWikService.getPiwikSiteForRepo(repositoryId);
48 48
    }
49 49

  
50 50
    @RequestMapping(value = "/savePiwikInfo" , method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
51
    @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN') or @aaiUserRoleService.isMemberOf(#piwikInfo.repositoryId) or (@repositoryService.getRepositoryById(#piwikInfo.repositoryId).registeredBy=='null' and hasRole('ROLE_USER'))")
51
    @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_PROVIDE_ADMIN') or @authorizationService.isMemberOf(#piwikInfo.repositoryId) or (@repositoryService.getRepositoryById(#piwikInfo.repositoryId).registeredBy=='null' and hasRole('ROLE_USER'))")
52 52
    public PiwikInfo savePiwikInfo(@RequestBody PiwikInfo piwikInfo) {
53 53
        return piWikService.savePiwikInfo(piwikInfo);
54 54
    }
......
157 157

  
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff