]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.util/src/org/argeo/osgi/useradmin/LdifUserAdmin.java
Introduce directory kinds.
[lgpl/argeo-commons.git] / org.argeo.util / src / org / argeo / osgi / useradmin / LdifUserAdmin.java
1 package org.argeo.osgi.useradmin;
2
3 import static org.argeo.util.naming.LdapAttrs.objectClass;
4 import static org.argeo.util.naming.LdapObjs.inetOrgPerson;
5
6 import java.io.File;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.io.OutputStream;
11 import java.net.URI;
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;
20 import java.util.Set;
21 import java.util.SortedMap;
22 import java.util.TreeMap;
23
24 import javax.naming.NameNotFoundException;
25 import javax.naming.NamingEnumeration;
26 import javax.naming.directory.Attributes;
27 import javax.naming.ldap.LdapName;
28
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;
35
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<>();
40
41 private SortedMap<LdapName, LdifHierarchyUnit> hierarchy = new TreeMap<>();
42 private List<HierarchyUnit> rootHierarchyUnits = new ArrayList<>();
43
44 public LdifUserAdmin(String uri, String baseDn) {
45 this(fromUri(uri, baseDn), false);
46 }
47
48 public LdifUserAdmin(Dictionary<String, ?> properties) {
49 this(properties, false);
50 }
51
52 protected LdifUserAdmin(Dictionary<String, ?> properties, boolean scoped) {
53 super(null, properties, scoped);
54 }
55
56 public LdifUserAdmin(URI uri, Dictionary<String, ?> properties) {
57 super(uri, properties, false);
58 }
59
60 @Override
61 protected AbstractUserDirectory scope(User user) {
62 Dictionary<String, Object> credentials = user.getCredentials();
63 String username = (String) credentials.get(SHARED_STATE_USERNAME);
64 if (username == null)
65 username = user.getName();
66 Object pwdCred = credentials.get(SHARED_STATE_PASSWORD);
67 byte[] pwd = (byte[]) pwdCred;
68 if (pwd != null) {
69 char[] password = DigestUtils.bytesToChars(pwd);
70 User directoryUser = (User) getRole(username);
71 if (!directoryUser.hasCredential(null, password))
72 throw new UserDirectoryException("Invalid credentials");
73 } else {
74 throw new UserDirectoryException("Password is required");
75 }
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;
82 }
83
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);
88 return res;
89 }
90
91 public void init() {
92
93 try {
94 URI u = new URI(getUri());
95 if (u.getScheme().equals("file")) {
96 File file = new File(u);
97 if (!file.exists())
98 return;
99 }
100 load(u.toURL().openStream());
101 } catch (Exception e) {
102 throw new UserDirectoryException("Cannot open URL " + getUri(), e);
103 }
104 }
105
106 public void save() {
107 if (getUri() == null)
108 throw new UserDirectoryException("Cannot save LDIF user admin: no URI is set");
109 if (isReadOnly())
110 throw new UserDirectoryException("Cannot save LDIF user admin: " + getUri() + " is read-only");
111 try (FileOutputStream out = new FileOutputStream(new File(new URI(getUri())))) {
112 save(out);
113 } catch (IOException | URISyntaxException e) {
114 throw new UserDirectoryException("Cannot save user admin to " + getUri(), e);
115 }
116 }
117
118 public void save(OutputStream out) throws IOException {
119 try {
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());
127 } finally {
128 out.close();
129 }
130 }
131
132 protected void load(InputStream in) {
133 try {
134 users.clear();
135 groups.clear();
136 hierarchy.clear();
137
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);
149 lowerCase.add(id);
150 }
151
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));
160 break objectClasses;
161 } else if (objectClass.toLowerCase().equals(getGroupObjectClass().toLowerCase())) {
162 groups.put(key, newGroup(key, attributes));
163 break objectClasses;
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));
174 break objectClasses;
175 }
176 }
177 }
178
179 // link hierarchy
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);
186 unit.parent = null;
187 continue hierachyUnits;
188 }
189 parent.children.add(unit);
190 unit.parent = parent;
191 }
192 } catch (Exception e) {
193 throw new UserDirectoryException("Cannot load user admin service from LDIF", e);
194 }
195 }
196
197 public void destroy() {
198 if (users == null || groups == null)
199 throw new UserDirectoryException("User directory " + getBaseDn() + " is already destroyed");
200 users = null;
201 groups = null;
202 }
203
204 /*
205 * USER ADMIN
206 */
207
208 @Override
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");
215 }
216
217 @Override
218 protected Boolean daoHasRole(LdapName dn) {
219 return users.containsKey(dn) || groups.containsKey(dn);
220 }
221
222 @Override
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());
229 } else {
230 filterRoles(users, searchBase, f, deep, res);
231 filterRoles(groups, searchBase, f, deep, res);
232 }
233 return res;
234 }
235
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))
243 continue roles;
244 if (f == null)
245 res.add(user);
246 else if (f.match(user.getProperties()))
247 res.add(user);
248 }
249 }
250
251 }
252
253 @Override
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());
260 }
261 return directGroups;
262 }
263
264 @Override
265 protected void prepare(UserDirectoryWorkingCopy wc) {
266 // delete
267 for (LdapName dn : wc.getDeletedUsers().keySet()) {
268 if (users.containsKey(dn))
269 users.remove(dn);
270 else if (groups.containsKey(dn))
271 groups.remove(dn);
272 else
273 throw new UserDirectoryException("User to delete not found " + dn);
274 }
275 // add
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())
281 users.put(dn, user);
282 else if (Role.GROUP == user.getType())
283 groups.put(dn, (DirectoryGroup) user);
284 else
285 throw new UserDirectoryException("Unsupported role type " + user.getType() + " for new user " + dn);
286 }
287 // modify
288 for (LdapName dn : wc.getModifiedUsers().keySet()) {
289 Attributes modifiedAttrs = wc.getModifiedUsers().get(dn);
290 DirectoryUser user;
291 if (users.containsKey(dn))
292 user = users.get(dn);
293 else if (groups.containsKey(dn))
294 user = groups.get(dn);
295 else
296 throw new UserDirectoryException("User to modify no found " + dn);
297 user.publishAttributes(modifiedAttrs);
298 }
299 }
300
301 @Override
302 protected void commit(UserDirectoryWorkingCopy wc) {
303 save();
304 }
305
306 @Override
307 protected void rollback(UserDirectoryWorkingCopy wc) {
308 init();
309 }
310
311 /*
312 * HIERARCHY
313 */
314
315 // @Override
316 // public int getHierarchyChildCount() {
317 // return rootHierarchyUnits.size();
318 // }
319 //
320 // @Override
321 // public HierarchyUnit getHierarchyChild(int i) {
322 // return rootHierarchyUnits.get(i);
323 // }
324
325 @Override
326 public HierarchyUnit getHierarchyUnit(String path) {
327 LdapName dn = pathToName(path);
328 return hierarchy.get(dn);
329 }
330
331 @Override
332 public Iterable<HierarchyUnit> getRootHierarchyUnits(boolean functionalOnly) {
333 if (functionalOnly) {
334 List<HierarchyUnit> res = new ArrayList<>();
335 for (HierarchyUnit hu : rootHierarchyUnits) {
336 if (hu.isFunctional())
337 res.add(hu);
338 }
339 return res;
340
341 } else {
342 return rootHierarchyUnits;
343 }
344 }
345
346 @Override
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;
354 }
355
356 }