Project

General

Profile

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
}
(2-2/6)