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