]> git.argeo.org Git - lgpl/argeo-commons.git/blobdiff - org.argeo.security.core/src/org/argeo/osgi/useradmin/LdifUserAdmin.java
Improve and simplify OSGi Boot
[lgpl/argeo-commons.git] / org.argeo.security.core / src / org / argeo / osgi / useradmin / LdifUserAdmin.java
index 33372e63feb66bddf077bc827389db9c10940ce6..521ae8bb6e89916c6b88ea490767658e8b3012fa 100644 (file)
 package org.argeo.osgi.useradmin;
 
+import static org.argeo.osgi.useradmin.LdifName.inetOrgPerson;
+import static org.argeo.osgi.useradmin.LdifName.objectClass;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
 import java.io.InputStream;
-import java.net.URI;
-import java.net.URISyntaxException;
+import java.io.OutputStream;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Dictionary;
-import java.util.LinkedHashMap;
+import java.util.HashSet;
+import java.util.Hashtable;
 import java.util.List;
-import java.util.Map;
+import java.util.Set;
 import java.util.SortedMap;
 import java.util.TreeMap;
 
-import javax.naming.InvalidNameException;
 import javax.naming.NamingEnumeration;
 import javax.naming.directory.Attributes;
 import javax.naming.ldap.LdapName;
+import javax.transaction.TransactionManager;
 
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.service.useradmin.Authorization;
+import org.argeo.util.naming.LdifParser;
+import org.argeo.util.naming.LdifWriter;
+import org.osgi.framework.Filter;
 import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.User;
-import org.osgi.service.useradmin.UserAdmin;
-
-/** User admin implementation using LDIF file(s) as backend. */
-public class LdifUserAdmin implements UserAdmin {
-       SortedMap<LdapName, LdifUser> users = new TreeMap<LdapName, LdifUser>();
-       SortedMap<LdapName, LdifGroup> groups = new TreeMap<LdapName, LdifGroup>();
 
-       private final boolean isReadOnly;
-       private final URI uri;
+/**
+ * A user admin based on a LDIF files. Requires a {@link TransactionManager} and
+ * an open transaction for write access.
+ */
+public class LdifUserAdmin extends AbstractUserDirectory {
+       private SortedMap<LdapName, DirectoryUser> users = new TreeMap<LdapName, DirectoryUser>();
+       private SortedMap<LdapName, DirectoryGroup> groups = new TreeMap<LdapName, DirectoryGroup>();
 
-       private List<String> indexedUserProperties = Arrays.asList(new String[] {
-                       "uid", "mail", "cn" });
-       private Map<String, Map<String, LdifUser>> userIndexes = new LinkedHashMap<String, Map<String, LdifUser>>();
+       public LdifUserAdmin(String uri, String baseDn) {
+               this(fromUri(uri, baseDn));
+       }
 
-       public LdifUserAdmin(String uri) {
-               this(uri, true);
+       public LdifUserAdmin(Dictionary<String, ?> properties) {
+               super(properties);
        }
 
-       public LdifUserAdmin(String uri, boolean isReadOnly) {
-               this.isReadOnly = isReadOnly;
-               try {
-                       this.uri = new URI(uri);
-               } catch (URISyntaxException e) {
-                       throw new ArgeoUserAdminException("Invalid URI " + uri, e);
-               }
+       public LdifUserAdmin(InputStream in) {
+               super(new Hashtable<String, Object>());
+               load(in);
+       }
 
-               if (!isReadOnly && !this.uri.getScheme().equals("file:"))
-                       throw new UnsupportedOperationException(this.uri.getScheme()
-                                       + "not supported read-write.");
+       private static Dictionary<String, Object> fromUri(String uri, String baseDn) {
+               Hashtable<String, Object> res = new Hashtable<String, Object>();
+               res.put(UserAdminConf.uri.name(), uri);
+               res.put(UserAdminConf.baseDn.name(), baseDn);
+               return res;
+       }
 
+       public void init() {
                try {
-                       load(this.uri.toURL().openStream());
+                       if (getUri().getScheme().equals("file")) {
+                               File file = new File(getUri());
+                               if (!file.exists())
+                                       return;
+                       }
+                       load(getUri().toURL().openStream());
                } catch (Exception e) {
-                       throw new ArgeoUserAdminException("Cannot open URL " + this.uri, e);
+                       throw new UserDirectoryException("Cannot open URL " + getUri(), e);
                }
        }
 
-       public LdifUserAdmin(InputStream in) {
-               load(in);
-               isReadOnly = true;
-               this.uri = null;
+       public void save() {
+               if (getUri() == null)
+                       throw new UserDirectoryException("Cannot save LDIF user admin: no URI is set");
+               if (isReadOnly())
+                       throw new UserDirectoryException("Cannot save LDIF user admin: " + getUri() + " is read-only");
+               try (FileOutputStream out = new FileOutputStream(new File(getUri()))) {
+                       save(out);
+               } catch (IOException e) {
+                       throw new UserDirectoryException("Cannot save user admin to " + getUri(), e);
+               }
+       }
+
+       public void save(OutputStream out) throws IOException {
+               try {
+                       LdifWriter ldifWriter = new LdifWriter(out);
+                       for (LdapName name : groups.keySet())
+                               ldifWriter.writeEntry(name, groups.get(name).getAttributes());
+                       for (LdapName name : users.keySet())
+                               ldifWriter.writeEntry(name, users.get(name).getAttributes());
+               } finally {
+                       out.close();
+               }
        }
 
        protected void load(InputStream in) {
                try {
+                       users.clear();
+                       groups.clear();
+
                        LdifParser ldifParser = new LdifParser();
                        SortedMap<LdapName, Attributes> allEntries = ldifParser.read(in);
                        for (LdapName key : allEntries.keySet()) {
                                Attributes attributes = allEntries.get(key);
-                               NamingEnumeration<?> objectClasses = attributes.get(
-                                               "objectClass").getAll();
+                               // check for inconsistency
+                               Set<String> lowerCase = new HashSet<String>();
+                               NamingEnumeration<String> ids = attributes.getIDs();
+                               while (ids.hasMoreElements()) {
+                                       String id = ids.nextElement().toLowerCase();
+                                       if (lowerCase.contains(id))
+                                               throw new UserDirectoryException(key + " has duplicate id " + id);
+                                       lowerCase.add(id);
+                               }
+
+                               // analyse object classes
+                               NamingEnumeration<?> objectClasses = attributes.get(objectClass.name()).getAll();
+                               // System.out.println(key);
                                objectClasses: while (objectClasses.hasMore()) {
                                        String objectClass = objectClasses.next().toString();
-                                       if (objectClass.equals("inetOrgPerson")) {
-                                               users.put(key, new LdifUser(key, attributes));
+                                       // System.out.println(" " + objectClass);
+                                       if (objectClass.equals(inetOrgPerson.name())) {
+                                               users.put(key, new LdifUser(this, key, attributes));
                                                break objectClasses;
-                                       } else if (objectClass.equals("groupOfNames")) {
-                                               groups.put(key, new LdifGroup(key, attributes));
+                                       } else if (objectClass.equals(getGroupObjectClass())) {
+                                               groups.put(key, new LdifGroup(this, key, attributes));
                                                break objectClasses;
                                        }
                                }
                        }
-
-                       // optimise
-                       for (LdifGroup group : groups.values())
-                               group.loadMembers(this);
-
-                       // indexes
-                       for (String attr : indexedUserProperties)
-                               userIndexes.put(attr, new TreeMap<String, LdifUser>());
-
-                       for (LdifUser user : users.values()) {
-                               Dictionary<String, Object> properties = user.getProperties();
-                               for (String attr : indexedUserProperties) {
-                                       Object value = properties.get(attr);
-                                       if (value != null) {
-                                               LdifUser otherUser = userIndexes.get(attr).put(
-                                                               value.toString(), user);
-                                               if (otherUser != null)
-                                                       throw new ArgeoUserAdminException("User " + user
-                                                                       + " and user " + otherUser
-                                                                       + " both habe property " + attr
-                                                                       + " set to " + value);
-                                       }
-                               }
-                       }
                } catch (Exception e) {
-                       throw new ArgeoUserAdminException(
-                                       "Cannot load user admin service from LDIF", e);
+                       throw new UserDirectoryException("Cannot load user admin service from LDIF", e);
                }
        }
 
        public void destroy() {
+               if (users == null || groups == null)
+                       throw new UserDirectoryException("User directory " + getBaseDn() + " is already destroyed");
                users.clear();
                users = null;
                groups.clear();
                groups = null;
        }
 
-       @Override
-       public Role getRole(String name) {
-               LdapName key;
-               try {
-                       key = new LdapName(name);
-               } catch (InvalidNameException e) {
-                       // TODO implements default base DN
-                       throw new IllegalArgumentException("Badly formatted role name: "
-                                       + name, e);
-               }
-
+       protected DirectoryUser daoGetRole(LdapName key) {
                if (groups.containsKey(key))
                        return groups.get(key);
                if (users.containsKey(key))
@@ -138,61 +148,91 @@ public class LdifUserAdmin implements UserAdmin {
                return null;
        }
 
-       @Override
-       public Authorization getAuthorization(User user) {
-               return new LdifAuthorization((LdifUser) user);
+       protected Boolean daoHasRole(LdapName dn) {
+               return users.containsKey(dn) || groups.containsKey(dn);
        }
 
-       @Override
-       public Role createRole(String name, int type) {
-               throw new UnsupportedOperationException();
-       }
-
-       @Override
-       public boolean removeRole(String name) {
-               throw new UnsupportedOperationException();
+       @SuppressWarnings("unchecked")
+       protected List<DirectoryUser> doGetRoles(Filter f) {
+               ArrayList<DirectoryUser> res = new ArrayList<DirectoryUser>();
+               if (f == null) {
+                       res.addAll(users.values());
+                       res.addAll(groups.values());
+               } else {
+                       for (DirectoryUser user : users.values()) {
+                               // System.out.println("\n" + user.getName());
+                               // Dictionary<String, Object> props = user.getProperties();
+                               // for (Enumeration<String> keys = props.keys(); keys
+                               // .hasMoreElements();) {
+                               // String key = keys.nextElement();
+                               // System.out.println(" " + key + "=" + props.get(key));
+                               // }
+                               if (f.match(user.getProperties()))
+                                       res.add(user);
+                       }
+                       for (DirectoryUser group : groups.values())
+                               if (f.match(group.getProperties()))
+                                       res.add(group);
+               }
+               return res;
        }
 
        @Override
-       public Role[] getRoles(String filter) throws InvalidSyntaxException {
-               throw new UnsupportedOperationException();
+       protected List<LdapName> getDirectGroups(LdapName dn) {
+               List<LdapName> directGroups = new ArrayList<LdapName>();
+               for (LdapName name : groups.keySet()) {
+                       DirectoryGroup group = groups.get(name);
+                       if (group.getMemberNames().contains(dn))
+                               directGroups.add(group.getDn());
+               }
+               return directGroups;
        }
 
        @Override
-       public User getUser(String key, String value) {
-               // TODO check value null or empty
-               if (key != null) {
-                       if (!userIndexes.containsKey(key))
-                               return null;
-                       return userIndexes.get(key).get(value);
+       protected void prepare(UserDirectoryWorkingCopy wc) {
+               // delete
+               for (LdapName dn : wc.getDeletedUsers().keySet()) {
+                       if (users.containsKey(dn))
+                               users.remove(dn);
+                       else if (groups.containsKey(dn))
+                               groups.remove(dn);
+                       else
+                               throw new UserDirectoryException("User to delete not found " + dn);
                }
-
-               // Try all indexes
-               List<LdifUser> collectedUsers = new ArrayList<LdifUser>(
-                               indexedUserProperties.size());
-               // try dn
-               LdifUser user = null;
-               try {
-                       user = (LdifUser) getRole(value);
-                       if (user != null)
-                               collectedUsers.add(user);
-               } catch (Exception e) {
-                       // silent
+               // add
+               for (LdapName dn : wc.getNewUsers().keySet()) {
+                       DirectoryUser user = wc.getNewUsers().get(dn);
+                       if (users.containsKey(dn) || groups.containsKey(dn))
+                               throw new UserDirectoryException("User to create found " + dn);
+                       else if (Role.USER == user.getType())
+                               users.put(dn, user);
+                       else if (Role.GROUP == user.getType())
+                               groups.put(dn, (DirectoryGroup) user);
+                       else
+                               throw new UserDirectoryException("Unsupported role type " + user.getType() + " for new user " + dn);
                }
-               for (String attr : userIndexes.keySet()) {
-                       user = userIndexes.get(attr).get(value);
-                       if (user != null)
-                               collectedUsers.add(user);
+               // modify
+               for (LdapName dn : wc.getModifiedUsers().keySet()) {
+                       Attributes modifiedAttrs = wc.getModifiedUsers().get(dn);
+                       DirectoryUser user;
+                       if (users.containsKey(dn))
+                               user = users.get(dn);
+                       else if (groups.containsKey(dn))
+                               user = groups.get(dn);
+                       else
+                               throw new UserDirectoryException("User to modify no found " + dn);
+                       user.publishAttributes(modifiedAttrs);
                }
+       }
 
-               if (collectedUsers.size() == 1)
-                       return collectedUsers.get(0);
-               return null;
-               // throw new UnsupportedOperationException();
+       @Override
+       protected void commit(UserDirectoryWorkingCopy wc) {
+               save();
        }
 
-       public boolean getIsReadOnly() {
-               return isReadOnly;
+       @Override
+       protected void rollback(UserDirectoryWorkingCopy wc) {
+               init();
        }
 
 }