1 package org
.argeo
.util
.directory
.ldap
;
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
.NavigableMap
;
20 import java
.util
.Objects
;
22 import java
.util
.SortedMap
;
23 import java
.util
.TreeMap
;
25 import javax
.naming
.NameNotFoundException
;
26 import javax
.naming
.NamingEnumeration
;
27 import javax
.naming
.NamingException
;
28 import javax
.naming
.directory
.Attributes
;
29 import javax
.naming
.ldap
.LdapName
;
31 import org
.argeo
.util
.directory
.DirectoryConf
;
32 import org
.argeo
.util
.directory
.HierarchyUnit
;
33 import org
.argeo
.util
.naming
.LdapObjs
;
34 import org
.osgi
.framework
.Filter
;
35 import org
.osgi
.framework
.FrameworkUtil
;
36 import org
.osgi
.framework
.InvalidSyntaxException
;
37 import org
.osgi
.service
.useradmin
.Role
;
39 /** A user admin based on a LDIF files. */
40 public class LdifDao
extends AbstractLdapDirectoryDao
{
41 // private NavigableMap<LdapName, LdapEntry> users = new TreeMap<>();
42 // private NavigableMap<LdapName, LdapEntry> groups = new TreeMap<>();
43 private NavigableMap
<LdapName
, LdapEntry
> entries
= new TreeMap
<>();
45 private NavigableMap
<LdapName
, LdapHierarchyUnit
> hierarchy
= new TreeMap
<>();
46 // private List<HierarchyUnit> rootHierarchyUnits = new ArrayList<>();
48 // public LdifUserAdmin(String uri, String baseDn) {
49 // this(fromUri(uri, baseDn), false);
52 public LdifDao(AbstractLdapDirectory directory
) {
56 // protected LdifUserAdmin(Hashtable<String, ?> properties, boolean scoped) {
57 // super( properties, scoped);
60 // public LdifUserAdmin(URI uri, Dictionary<String, ?> properties) {
61 // super(uri, properties, false);
65 // protected AbstractUserDirectory scope(User user) {
66 // Dictionary<String, Object> credentials = user.getCredentials();
67 // String username = (String) credentials.get(SHARED_STATE_USERNAME);
68 // if (username == null)
69 // username = user.getName();
70 // Object pwdCred = credentials.get(SHARED_STATE_PASSWORD);
71 // byte[] pwd = (byte[]) pwdCred;
73 // char[] password = DirectoryDigestUtils.bytesToChars(pwd);
74 // User directoryUser = (User) getRole(username);
75 // if (!directoryUser.hasCredential(null, password))
76 // throw new IllegalStateException("Invalid credentials");
78 // throw new IllegalStateException("Password is required");
80 // Dictionary<String, Object> properties = cloneProperties();
81 // properties.put(DirectoryConf.readOnly.name(), "true");
82 // LdifUserAdmin scopedUserAdmin = new LdifUserAdmin(properties, true);
83 //// scopedUserAdmin.groups = Collections.unmodifiableNavigableMap(groups);
84 //// scopedUserAdmin.users = Collections.unmodifiableNavigableMap(users);
85 // scopedUserAdmin.entries = Collections.unmodifiableNavigableMap(entries);
86 // return scopedUserAdmin;
89 private static Dictionary
<String
, Object
> fromUri(String uri
, String baseDn
) {
90 Hashtable
<String
, Object
> res
= new Hashtable
<String
, Object
>();
91 res
.put(DirectoryConf
.uri
.name(), uri
);
92 res
.put(DirectoryConf
.baseDn
.name(), baseDn
);
99 URI u
= new URI(getDirectory().getUri());
100 if (u
.getScheme().equals("file")) {
101 File file
= new File(u
);
105 load(u
.toURL().openStream());
106 } catch (IOException
| URISyntaxException e
) {
107 throw new IllegalStateException("Cannot open URL " + getDirectory().getUri(), e
);
112 if (getDirectory().getUri() == null)
113 throw new IllegalStateException("Cannot save LDIF user admin: no URI is set");
114 if (getDirectory().isReadOnly())
115 throw new IllegalStateException(
116 "Cannot save LDIF user admin: " + getDirectory().getUri() + " is read-only");
117 try (FileOutputStream out
= new FileOutputStream(new File(new URI(getDirectory().getUri())))) {
119 } catch (IOException
| URISyntaxException e
) {
120 throw new IllegalStateException("Cannot save user admin to " + getDirectory().getUri(), e
);
124 public void save(OutputStream out
) throws IOException
{
126 LdifWriter ldifWriter
= new LdifWriter(out
);
127 for (LdapName name
: hierarchy
.keySet())
128 ldifWriter
.writeEntry(name
, hierarchy
.get(name
).getAttributes());
129 // for (LdapName name : groups.keySet())
130 // ldifWriter.writeEntry(name, groups.get(name).getAttributes());
131 // for (LdapName name : users.keySet())
132 // ldifWriter.writeEntry(name, users.get(name).getAttributes());
133 for (LdapName name
: entries
.keySet())
134 ldifWriter
.writeEntry(name
, entries
.get(name
).getAttributes());
140 public void load(InputStream in
) {
147 LdifParser ldifParser
= new LdifParser();
148 SortedMap
<LdapName
, Attributes
> allEntries
= ldifParser
.read(in
);
149 for (LdapName key
: allEntries
.keySet()) {
150 Attributes attributes
= allEntries
.get(key
);
151 // check for inconsistency
152 Set
<String
> lowerCase
= new HashSet
<String
>();
153 NamingEnumeration
<String
> ids
= attributes
.getIDs();
154 while (ids
.hasMoreElements()) {
155 String id
= ids
.nextElement().toLowerCase();
156 if (lowerCase
.contains(id
))
157 throw new IllegalStateException(key
+ " has duplicate id " + id
);
161 // analyse object classes
162 NamingEnumeration
<?
> objectClasses
= attributes
.get(objectClass
.name()).getAll();
163 // System.out.println(key);
164 objectClasses
: while (objectClasses
.hasMore()) {
165 String objectClass
= objectClasses
.next().toString();
166 // System.out.println(" " + objectClass);
167 if (objectClass
.toLowerCase().equals(inetOrgPerson
.name().toLowerCase())) {
168 entries
.put(key
, newUser(key
, attributes
));
170 } else if (objectClass
.toLowerCase().equals(getDirectory().getGroupObjectClass().toLowerCase())) {
171 entries
.put(key
, newGroup(key
, attributes
));
173 // } else if (objectClass.equalsIgnoreCase(LdapObjs.organization.name())) {
174 // // we only consider organizations which are not groups
175 // hierarchy.put(key, new LdifHierarchyUnit(this, key, HierarchyUnit.ORGANIZATION, attributes));
176 // break objectClasses;
177 } else if (objectClass
.equalsIgnoreCase(LdapObjs
.organizationalUnit
.name())) {
178 // String name = key.getRdn(key.size() - 1).toStrindirectoryDaog();
179 // if (getUserBase().equalsIgnoreCase(name) || getGroupBase().equalsIgnoreCase(name))
180 // break objectClasses; // skip
181 // TODO skip if it does not contain groups or users
182 hierarchy
.put(key
, new LdapHierarchyUnit(getDirectory(), key
, attributes
));
189 // hierachyUnits: for (LdapName dn : hierarchy.keySet()) {
190 // LdifHierarchyUnit unit = hierarchy.get(dn);
191 // LdapName parentDn = (LdapName) dn.getPrefix(dn.size() - 1);
192 // LdifHierarchyUnit parent = hierarchy.get(parentDn);
193 // if (parent == null) {
194 // rootHierarchyUnits.add(unit);
195 // unit.parent = null;
196 // continue hierachyUnits;
198 // parent.children.add(unit);
199 // unit.parent = parent;
201 } catch (NamingException
| IOException e
) {
202 throw new IllegalStateException("Cannot load user admin service from LDIF", e
);
206 public void destroy() {
207 // if (users == null || groups == null)
209 throw new IllegalStateException("User directory " + getDirectory().getBaseDn() + " is already destroyed");
220 public LdapEntry
doGetEntry(LdapName key
) throws NameNotFoundException
{
221 // if (groups.containsKey(key))
222 // return groups.get(key);
223 // if (users.containsKey(key))
224 // return users.get(key);
225 if (entries
.containsKey(key
))
226 return entries
.get(key
);
227 throw new NameNotFoundException(key
+ " not persisted");
231 public Boolean
entryExists(LdapName dn
) {
232 return entries
.containsKey(dn
);// || groups.containsKey(dn);
236 public List
<LdapEntry
> doGetEntries(LdapName searchBase
, String f
, boolean deep
) {
237 Objects
.requireNonNull(searchBase
);
238 ArrayList
<LdapEntry
> res
= new ArrayList
<>();
239 if (f
== null && deep
&& getDirectory().getBaseDn().equals(searchBase
)) {
240 // res.addAll(users.values());
241 // res.addAll(groups.values());
242 res
.addAll(entries
.values());
244 // filterRoles(users, searchBase, f, deep, res);
245 // filterRoles(groups, searchBase, f, deep, res);
246 filterRoles(entries
, searchBase
, f
, deep
, res
);
251 private void filterRoles(SortedMap
<LdapName
, ?
extends LdapEntry
> map
, LdapName searchBase
, String f
, boolean deep
,
252 List
<LdapEntry
> res
) {
253 // FIXME get rid of OSGi references
255 // TODO reduce map with search base ?
256 Filter filter
= f
!= null ? FrameworkUtil
.createFilter(f
) : null;
257 roles
: for (LdapEntry user
: map
.values()) {
258 LdapName dn
= user
.getDn();
259 if (dn
.startsWith(searchBase
)) {
260 if (!deep
&& dn
.size() != (searchBase
.size() + 1))
265 if (user
instanceof Role
) {
266 if (filter
.match(((Role
) user
).getProperties()))
272 } catch (InvalidSyntaxException e
) {
273 throw new IllegalArgumentException("Cannot create filter " + f
, e
);
279 public List
<LdapName
> getDirectGroups(LdapName dn
) {
280 List
<LdapName
> directGroups
= new ArrayList
<LdapName
>();
281 entries
: for (LdapName name
: entries
.keySet()) {
284 LdapEntry entry
= doGetEntry(name
);
285 if (AbstractLdapDirectory
.hasObjectClass(entry
.getAttributes(), getDirectory().getGroupObjectClass())) {
290 } catch (NameNotFoundException e
) {
291 throw new IllegalArgumentException("Group " + dn
+ " not found", e
);
293 if (group
.getReferences(getDirectory().getMemberAttributeId()).contains(dn
)) {
294 directGroups
.add(group
.getDn());
301 public void prepare(LdapEntryWorkingCopy wc
) {
303 for (LdapName dn
: wc
.getDeletedData().keySet()) {
304 if (entries
.containsKey(dn
))
306 // if (users.containsKey(dn))
308 // else if (groups.containsKey(dn))
309 // groups.remove(dn);
311 throw new IllegalStateException("User to delete not found " + dn
);
314 for (LdapName dn
: wc
.getNewData().keySet()) {
315 LdapEntry user
= (LdapEntry
) wc
.getNewData().get(dn
);
316 // if (users.containsKey(dn) || groups.containsKey(dn))
317 if (entries
.containsKey(dn
))
318 throw new IllegalStateException("User to create found " + dn
);
319 entries
.put(dn
, user
);
320 // else if (Role.USER == user.getType())
321 // users.put(dn, user);
322 // else if (Role.GROUP == user.getType())
323 // groups.put(dn, (DirectoryGroup) user);
325 // throw new IllegalStateException("Unsupported role type " + user.getType() + " for new user " + dn);
328 for (LdapName dn
: wc
.getModifiedData().keySet()) {
329 Attributes modifiedAttrs
= wc
.getModifiedData().get(dn
);
332 user
= doGetEntry(dn
);
333 } catch (NameNotFoundException e
) {
334 throw new IllegalStateException("User to modify no found " + dn
, e
);
337 throw new IllegalStateException("User to modify no found " + dn
);
338 user
.publishAttributes(modifiedAttrs
);
343 public void commit(LdapEntryWorkingCopy wc
) {
348 public void rollback(LdapEntryWorkingCopy wc
) {
357 // public int getHierarchyChildCount() {
358 // return rootHierarchyUnits.size();
362 // public HierarchyUnit getHierarchyChild(int i) {
363 // return rootHierarchyUnits.get(i);
366 public HierarchyUnit
doGetHierarchyUnit(LdapName dn
) {
367 return hierarchy
.get(dn
);
371 public Iterable
<HierarchyUnit
> doGetDirectHierarchyUnits(LdapName searchBase
, boolean functionalOnly
) {
372 List
<HierarchyUnit
> res
= new ArrayList
<>();
373 for (LdapName n
: hierarchy
.keySet()) {
374 if (n
.size() == searchBase
.size() + 1) {
375 if (n
.startsWith(searchBase
)) {
376 HierarchyUnit hu
= hierarchy
.get(n
);
377 if (functionalOnly
) {
378 if (hu
.isFunctional())
389 public void scope(LdifDao scoped
) {
390 scoped
.entries
= Collections
.unmodifiableNavigableMap(entries
);
394 // public Iterable<HierarchyUnit> getDirectHierarchyUnits(boolean functionalOnly) {
395 // if (functionalOnly) {
396 // List<HierarchyUnit> res = new ArrayList<>();
397 // for (HierarchyUnit hu : rootHierarchyUnits) {
398 // if (hu.isFunctional())
404 // return rootHierarchyUnits;