1 package org
.argeo
.osgi
.useradmin
;
3 import static org
.argeo
.util
.naming
.LdapAttrs
.objectClass
;
4 import static org
.argeo
.util
.naming
.LdapObjs
.inetOrgPerson
;
7 import java
.io
.FileOutputStream
;
8 import java
.io
.IOException
;
9 import java
.io
.InputStream
;
10 import java
.io
.OutputStream
;
12 import java
.net
.URISyntaxException
;
13 import java
.util
.ArrayList
;
14 import java
.util
.Collections
;
15 import java
.util
.Dictionary
;
16 import java
.util
.HashSet
;
17 import java
.util
.Hashtable
;
18 import java
.util
.List
;
19 import java
.util
.Objects
;
21 import java
.util
.SortedMap
;
22 import java
.util
.TreeMap
;
24 import javax
.naming
.NameNotFoundException
;
25 import javax
.naming
.NamingEnumeration
;
26 import javax
.naming
.directory
.Attributes
;
27 import javax
.naming
.ldap
.LdapName
;
29 import org
.argeo
.util
.naming
.LdapObjs
;
30 import org
.argeo
.util
.naming
.LdifParser
;
31 import org
.argeo
.util
.naming
.LdifWriter
;
32 import org
.osgi
.framework
.Filter
;
33 import org
.osgi
.service
.useradmin
.Role
;
34 import org
.osgi
.service
.useradmin
.User
;
36 /** A user admin based on a LDIF files. */
37 public class LdifUserAdmin
extends AbstractUserDirectory
{
38 private SortedMap
<LdapName
, DirectoryUser
> users
= new TreeMap
<>();
39 private SortedMap
<LdapName
, DirectoryGroup
> groups
= new TreeMap
<>();
41 private SortedMap
<LdapName
, LdifHierarchyUnit
> hierarchy
= new TreeMap
<>();
42 private List
<HierarchyUnit
> rootHierarchyUnits
= new ArrayList
<>();
44 public LdifUserAdmin(String uri
, String baseDn
) {
45 this(fromUri(uri
, baseDn
), false);
48 public LdifUserAdmin(Dictionary
<String
, ?
> properties
) {
49 this(properties
, false);
52 protected LdifUserAdmin(Dictionary
<String
, ?
> properties
, boolean scoped
) {
53 super(null, properties
, scoped
);
56 public LdifUserAdmin(URI uri
, Dictionary
<String
, ?
> properties
) {
57 super(uri
, properties
, false);
61 protected AbstractUserDirectory
scope(User user
) {
62 Dictionary
<String
, Object
> credentials
= user
.getCredentials();
63 String username
= (String
) credentials
.get(SHARED_STATE_USERNAME
);
65 username
= user
.getName();
66 Object pwdCred
= credentials
.get(SHARED_STATE_PASSWORD
);
67 byte[] pwd
= (byte[]) pwdCred
;
69 char[] password
= DigestUtils
.bytesToChars(pwd
);
70 User directoryUser
= (User
) getRole(username
);
71 if (!directoryUser
.hasCredential(null, password
))
72 throw new UserDirectoryException("Invalid credentials");
74 throw new UserDirectoryException("Password is required");
76 Dictionary
<String
, Object
> properties
= cloneProperties();
77 properties
.put(UserAdminConf
.readOnly
.name(), "true");
78 LdifUserAdmin scopedUserAdmin
= new LdifUserAdmin(properties
, true);
79 scopedUserAdmin
.groups
= Collections
.unmodifiableSortedMap(groups
);
80 scopedUserAdmin
.users
= Collections
.unmodifiableSortedMap(users
);
81 return scopedUserAdmin
;
84 private static Dictionary
<String
, Object
> fromUri(String uri
, String baseDn
) {
85 Hashtable
<String
, Object
> res
= new Hashtable
<String
, Object
>();
86 res
.put(UserAdminConf
.uri
.name(), uri
);
87 res
.put(UserAdminConf
.baseDn
.name(), baseDn
);
94 URI u
= new URI(getUri());
95 if (u
.getScheme().equals("file")) {
96 File file
= new File(u
);
100 load(u
.toURL().openStream());
101 } catch (Exception e
) {
102 throw new UserDirectoryException("Cannot open URL " + getUri(), e
);
107 if (getUri() == null)
108 throw new UserDirectoryException("Cannot save LDIF user admin: no URI is set");
110 throw new UserDirectoryException("Cannot save LDIF user admin: " + getUri() + " is read-only");
111 try (FileOutputStream out
= new FileOutputStream(new File(new URI(getUri())))) {
113 } catch (IOException
| URISyntaxException e
) {
114 throw new UserDirectoryException("Cannot save user admin to " + getUri(), e
);
118 public void save(OutputStream out
) throws IOException
{
120 LdifWriter ldifWriter
= new LdifWriter(out
);
121 for (LdapName name
: hierarchy
.keySet())
122 ldifWriter
.writeEntry(name
, hierarchy
.get(name
).getAttributes());
123 for (LdapName name
: groups
.keySet())
124 ldifWriter
.writeEntry(name
, groups
.get(name
).getAttributes());
125 for (LdapName name
: users
.keySet())
126 ldifWriter
.writeEntry(name
, users
.get(name
).getAttributes());
132 protected void load(InputStream in
) {
138 LdifParser ldifParser
= new LdifParser();
139 SortedMap
<LdapName
, Attributes
> allEntries
= ldifParser
.read(in
);
140 for (LdapName key
: allEntries
.keySet()) {
141 Attributes attributes
= allEntries
.get(key
);
142 // check for inconsistency
143 Set
<String
> lowerCase
= new HashSet
<String
>();
144 NamingEnumeration
<String
> ids
= attributes
.getIDs();
145 while (ids
.hasMoreElements()) {
146 String id
= ids
.nextElement().toLowerCase();
147 if (lowerCase
.contains(id
))
148 throw new UserDirectoryException(key
+ " has duplicate id " + id
);
152 // analyse object classes
153 NamingEnumeration
<?
> objectClasses
= attributes
.get(objectClass
.name()).getAll();
154 // System.out.println(key);
155 objectClasses
: while (objectClasses
.hasMore()) {
156 String objectClass
= objectClasses
.next().toString();
157 // System.out.println(" " + objectClass);
158 if (objectClass
.toLowerCase().equals(inetOrgPerson
.name().toLowerCase())) {
159 users
.put(key
, newUser(key
, attributes
));
161 } else if (objectClass
.toLowerCase().equals(getGroupObjectClass().toLowerCase())) {
162 groups
.put(key
, newGroup(key
, attributes
));
164 // } else if (objectClass.equalsIgnoreCase(LdapObjs.organization.name())) {
165 // // we only consider organizations which are not groups
166 // hierarchy.put(key, new LdifHierarchyUnit(this, key, HierarchyUnit.ORGANIZATION, attributes));
167 // break objectClasses;
168 } else if (objectClass
.equalsIgnoreCase(LdapObjs
.organizationalUnit
.name())) {
169 // String name = key.getRdn(key.size() - 1).toString();
170 // if (getUserBase().equalsIgnoreCase(name) || getGroupBase().equalsIgnoreCase(name))
171 // break objectClasses; // skip
172 // TODO skip if it does not contain groups or users
173 hierarchy
.put(key
, new LdifHierarchyUnit(this, key
, attributes
));
180 hierachyUnits
: for (LdapName dn
: hierarchy
.keySet()) {
181 LdifHierarchyUnit unit
= hierarchy
.get(dn
);
182 LdapName parentDn
= (LdapName
) dn
.getPrefix(dn
.size() - 1);
183 LdifHierarchyUnit parent
= hierarchy
.get(parentDn
);
184 if (parent
== null) {
185 rootHierarchyUnits
.add(unit
);
187 continue hierachyUnits
;
189 parent
.children
.add(unit
);
190 unit
.parent
= parent
;
192 } catch (Exception e
) {
193 throw new UserDirectoryException("Cannot load user admin service from LDIF", e
);
197 public void destroy() {
198 if (users
== null || groups
== null)
199 throw new UserDirectoryException("User directory " + getBaseDn() + " is already destroyed");
209 protected DirectoryUser
daoGetRole(LdapName key
) throws NameNotFoundException
{
210 if (groups
.containsKey(key
))
211 return groups
.get(key
);
212 if (users
.containsKey(key
))
213 return users
.get(key
);
214 throw new NameNotFoundException(key
+ " not persisted");
218 protected Boolean
daoHasRole(LdapName dn
) {
219 return users
.containsKey(dn
) || groups
.containsKey(dn
);
223 protected List
<DirectoryUser
> doGetRoles(LdapName searchBase
, Filter f
, boolean deep
) {
224 Objects
.requireNonNull(searchBase
);
225 ArrayList
<DirectoryUser
> res
= new ArrayList
<DirectoryUser
>();
226 if (f
== null && deep
&& getBaseDn().equals(searchBase
)) {
227 res
.addAll(users
.values());
228 res
.addAll(groups
.values());
230 filterRoles(users
, searchBase
, f
, deep
, res
);
231 filterRoles(groups
, searchBase
, f
, deep
, res
);
236 private void filterRoles(SortedMap
<LdapName
, ?
extends DirectoryUser
> map
, LdapName searchBase
, Filter f
,
237 boolean deep
, List
<DirectoryUser
> res
) {
238 // TODO reduce map with search base ?
239 roles
: for (DirectoryUser user
: map
.values()) {
240 LdapName dn
= user
.getDn();
241 if (dn
.startsWith(searchBase
)) {
242 if (!deep
&& dn
.size() != (searchBase
.size() + 1))
246 else if (f
.match(user
.getProperties()))
254 protected List
<LdapName
> getDirectGroups(LdapName dn
) {
255 List
<LdapName
> directGroups
= new ArrayList
<LdapName
>();
256 for (LdapName name
: groups
.keySet()) {
257 DirectoryGroup group
= groups
.get(name
);
258 if (group
.getMemberNames().contains(dn
))
259 directGroups
.add(group
.getDn());
265 protected void prepare(UserDirectoryWorkingCopy wc
) {
267 for (LdapName dn
: wc
.getDeletedUsers().keySet()) {
268 if (users
.containsKey(dn
))
270 else if (groups
.containsKey(dn
))
273 throw new UserDirectoryException("User to delete not found " + dn
);
276 for (LdapName dn
: wc
.getNewUsers().keySet()) {
277 DirectoryUser user
= wc
.getNewUsers().get(dn
);
278 if (users
.containsKey(dn
) || groups
.containsKey(dn
))
279 throw new UserDirectoryException("User to create found " + dn
);
280 else if (Role
.USER
== user
.getType())
282 else if (Role
.GROUP
== user
.getType())
283 groups
.put(dn
, (DirectoryGroup
) user
);
285 throw new UserDirectoryException("Unsupported role type " + user
.getType() + " for new user " + dn
);
288 for (LdapName dn
: wc
.getModifiedUsers().keySet()) {
289 Attributes modifiedAttrs
= wc
.getModifiedUsers().get(dn
);
291 if (users
.containsKey(dn
))
292 user
= users
.get(dn
);
293 else if (groups
.containsKey(dn
))
294 user
= groups
.get(dn
);
296 throw new UserDirectoryException("User to modify no found " + dn
);
297 user
.publishAttributes(modifiedAttrs
);
302 protected void commit(UserDirectoryWorkingCopy wc
) {
307 protected void rollback(UserDirectoryWorkingCopy wc
) {
316 // public int getHierarchyChildCount() {
317 // return rootHierarchyUnits.size();
321 // public HierarchyUnit getHierarchyChild(int i) {
322 // return rootHierarchyUnits.get(i);
326 public HierarchyUnit
getHierarchyUnit(String path
) {
327 LdapName dn
= pathToName(path
);
328 return hierarchy
.get(dn
);
332 public Iterable
<HierarchyUnit
> getDirectHierarchyUnits(boolean functionalOnly
) {
333 if (functionalOnly
) {
334 List
<HierarchyUnit
> res
= new ArrayList
<>();
335 for (HierarchyUnit hu
: rootHierarchyUnits
) {
336 if (hu
.isFunctional())
342 return rootHierarchyUnits
;
347 public HierarchyUnit
getHierarchyUnit(Role role
) {
348 LdapName dn
= LdapNameUtils
.toLdapName(role
.getName());
349 LdapName huDn
= LdapNameUtils
.getParent(dn
);
350 HierarchyUnit hierarchyUnit
= hierarchy
.get(huDn
);
351 if (hierarchyUnit
== null)
352 throw new IllegalStateException("No hierarchy unit found for " + role
);
353 return hierarchyUnit
;