View Javadoc
1   package org.argeo.osgi.useradmin;
2   
3   import java.util.Arrays;
4   import java.util.Collections;
5   import java.util.Dictionary;
6   import java.util.List;
7   
8   import org.argeo.naming.LdapAttrs;
9   import org.osgi.service.useradmin.Authorization;
10  import org.osgi.service.useradmin.Role;
11  import org.osgi.service.useradmin.User;
12  
13  /** Basic authorization. */
14  class LdifAuthorization implements Authorization {
15  	private final String name;
16  	private final String displayName;
17  	private final List<String> allRoles;
18  
19  	public LdifAuthorization(User user, List<Role> allRoles) {
20  		if (user == null) {
21  			this.name = null;
22  			this.displayName = "anonymous";
23  		} else {
24  			this.name = user.getName();
25  			this.displayName = extractDisplayName(user);
26  		}
27  		// roles
28  		String[] roles = new String[allRoles.size()];
29  		for (int i = 0; i < allRoles.size(); i++) {
30  			roles[i] = allRoles.get(i).getName();
31  		}
32  		this.allRoles = Collections.unmodifiableList(Arrays.asList(roles));
33  	}
34  
35  	@Override
36  	public String getName() {
37  		return name;
38  	}
39  
40  	@Override
41  	public boolean hasRole(String name) {
42  		return allRoles.contains(name);
43  	}
44  
45  	@Override
46  	public String[] getRoles() {
47  		return allRoles.toArray(new String[allRoles.size()]);
48  	}
49  
50  	@Override
51  	public int hashCode() {
52  		if (name == null)
53  			return super.hashCode();
54  		return name.hashCode();
55  	}
56  
57  	@Override
58  	public boolean equals(Object obj) {
59  		if (!(obj instanceof Authorization))
60  			return false;
61  		Authorization that = (Authorization) obj;
62  		if (name == null)
63  			return that.getName() == null;
64  		return name.equals(that.getName());
65  	}
66  
67  	@Override
68  	public String toString() {
69  		return displayName;
70  	}
71  
72  	final static String extractDisplayName(User user) {
73  		Dictionary<String, Object> props = user.getProperties();
74  		Object displayName = props.get(LdapAttrs.displayName);
75  		if (displayName == null)
76  			displayName = props.get(LdapAttrs.cn);
77  		if (displayName == null)
78  			displayName = props.get(LdapAttrs.uid);
79  		if (displayName == null)
80  			displayName = user.getName();
81  		if (displayName == null)
82  			throw new UserDirectoryException("Cannot set display name for " + user);
83  		return displayName.toString();
84  	}
85  }