Project

General

Profile

1
package eu.dnetlib.organizations.controller;
2

    
3
import org.apache.commons.lang3.EnumUtils;
4
import org.apache.commons.lang3.StringUtils;
5
import org.springframework.security.core.Authentication;
6
import org.springframework.security.core.GrantedAuthority;
7

    
8
public class UserInfo {
9

    
10
	private String name;
11
	private UserRole role;
12

    
13
	public UserInfo() {
14
		this.name = "anonymous";
15
		this.role = UserRole.NOT_AUTHORIZED;
16
	}
17

    
18
	public UserInfo(final String name, final UserRole role) {
19
		this.name = name;
20
		this.role = role;
21
	}
22

    
23
	public String getName() {
24
		return name;
25
	}
26

    
27
	public void setName(final String name) {
28
		this.name = name;
29
	}
30

    
31
	public UserRole getRole() {
32
		return role;
33
	}
34

    
35
	public void setRole(final UserRole role) {
36
		this.role = role;
37
	}
38

    
39
	public static UserInfo generate(final Authentication authentication) {
40
		return new UserInfo(authentication.getName(), findRole(authentication));
41
	}
42

    
43
	public static UserRole findRole(final Authentication authentication) {
44
		return authentication.getAuthorities()
45
				.stream()
46
				.map(GrantedAuthority::getAuthority)
47
				.map(s -> StringUtils.substringAfter(s, "ROLE_"))
48
				.filter(s -> EnumUtils.isValidEnum(UserRole.class, s))
49
				.map(UserRole::valueOf)
50
				.findFirst()
51
				.orElseGet(() -> UserRole.NOT_AUTHORIZED);
52
	}
53

    
54
	public static boolean isSuperAdmin(final Authentication authentication) {
55
		for (final GrantedAuthority aut : authentication.getAuthorities()) {
56
			if (aut.getAuthority().equals("ROLE_" + UserRole.ADMIN)) { return true; }
57
		}
58
		return false;
59
	}
60

    
61
	public static boolean isNationalAdmin(final Authentication authentication) {
62
		for (final GrantedAuthority aut : authentication.getAuthorities()) {
63
			if (aut.getAuthority().equals("ROLE_" + UserRole.NATIONAL_ADMIN)) { return true; }
64
		}
65
		return false;
66
	}
67

    
68
	public static boolean isSimpleUser(final Authentication authentication) {
69
		for (final GrantedAuthority aut : authentication.getAuthorities()) {
70
			if (aut.getAuthority().equals("ROLE_" + UserRole.USER)) { return true; }
71
		}
72
		return false;
73
	}
74

    
75
	public static boolean isPending(final Authentication authentication) {
76
		for (final GrantedAuthority aut : authentication.getAuthorities()) {
77
			if (aut.getAuthority().equals("ROLE_" + UserRole.PENDING)) { return true; }
78
		}
79
		return false;
80
	}
81

    
82
	public static boolean isNotAuthorized(final Authentication authentication) {
83
		for (final GrantedAuthority aut : authentication.getAuthorities()) {
84
			if (aut.getAuthority().equals("ROLE_" + UserRole.NOT_AUTHORIZED)) { return true; }
85
		}
86
		return false;
87
	}
88

    
89
}
(4-4/6)