LDAP user admin
authorMathieu Baudier <mbaudier@argeo.org>
Wed, 6 Apr 2016 15:58:52 +0000 (15:58 +0000)
committerMathieu Baudier <mbaudier@argeo.org>
Wed, 6 Apr 2016 15:58:52 +0000 (15:58 +0000)
git-svn-id: https://svn.argeo.org/commons/trunk@8864 4cfe0d0a-d680-48aa-b62c-e0a02a3f76cc

org.argeo.cms/src/org/argeo/cms/internal/auth/JcrSecurityModel.java [deleted file]
org.argeo.cms/src/org/argeo/cms/internal/auth/SimpleJcrSecurityModel.java [deleted file]
org.argeo.cms/src/org/argeo/cms/internal/kernel/NodeUserAdmin.java
org.argeo.security.core/src/org/argeo/osgi/useradmin/AbstractUserDirectory.java
org.argeo.security.core/src/org/argeo/osgi/useradmin/LdapUserAdmin.java
org.argeo.security.core/src/org/argeo/osgi/useradmin/LdifName.java
org.argeo.server.jcr/src/org/argeo/jcr/ArgeoNames.java

diff --git a/org.argeo.cms/src/org/argeo/cms/internal/auth/JcrSecurityModel.java b/org.argeo.cms/src/org/argeo/cms/internal/auth/JcrSecurityModel.java
deleted file mode 100644 (file)
index ad76922..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.cms.internal.auth;
-
-import java.util.List;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-/**
- * Manages data expected by the Argeo security model, such as user home and
- * profile.
- */
-public interface JcrSecurityModel {
-       /** Initialize the JCR security model */
-       public void init(Session adminSession) throws RepositoryException;
-
-       /**
-        * To be called before user details are loaded. Make sure than any logged in
-        * user has a home directory with full access and a profile with information
-        * about him (read access)
-        * 
-        * @return the user profile, never null
-        */
-       public Node sync(Session session, String username, List<String> roles);
-}
diff --git a/org.argeo.cms/src/org/argeo/cms/internal/auth/SimpleJcrSecurityModel.java b/org.argeo.cms/src/org/argeo/cms/internal/auth/SimpleJcrSecurityModel.java
deleted file mode 100644 (file)
index 7cb682c..0000000
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.cms.internal.auth;
-
-import java.util.List;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.Value;
-import javax.jcr.security.Privilege;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
-import org.argeo.cms.auth.AuthConstants;
-import org.argeo.jcr.ArgeoJcrConstants;
-import org.argeo.jcr.ArgeoNames;
-import org.argeo.jcr.ArgeoTypes;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.jcr.UserJcrUtils;
-
-/**
- * Manages data expected by the Argeo security model, such as user home and
- * profile.
- */
-public class SimpleJcrSecurityModel implements JcrSecurityModel {
-       private final static Log log = LogFactory
-                       .getLog(SimpleJcrSecurityModel.class);
-       // ArgeoNames not implemented as interface in order to ease derivation by
-       // Jackrabbit bundles
-
-       /** The home base path. */
-       private String homeBasePath = "/home";
-       private String peopleBasePath = ArgeoJcrConstants.PEOPLE_BASE_PATH;
-
-       @Override
-       public void init(Session adminSession) throws RepositoryException {
-               JcrUtils.mkdirs(adminSession, homeBasePath);
-               JcrUtils.mkdirs(adminSession, peopleBasePath);
-               adminSession.save();
-
-               JcrUtils.addPrivilege(adminSession, homeBasePath,
-                               AuthConstants.ROLE_USER_ADMIN, Privilege.JCR_READ);
-               JcrUtils.addPrivilege(adminSession, peopleBasePath,
-                               AuthConstants.ROLE_USER_ADMIN, Privilege.JCR_ALL);
-       }
-
-       public synchronized Node sync(Session session, String username,
-                       List<String> roles) {
-               // TODO check user name validity (e.g. should not start by ROLE_)
-
-               try {
-                       Node userHome = UserJcrUtils.getUserHome(session, username);
-                       if (userHome == null) {
-                               String homePath = generateUserPath(homeBasePath, username);
-                               userHome = JcrUtils.mkdirs(session, homePath);
-                               // userHome = JcrUtils.mkfolders(session, homePath);
-                               userHome.addMixin(ArgeoTypes.ARGEO_USER_HOME);
-                               userHome.setProperty(ArgeoNames.ARGEO_USER_ID, username);
-                               session.save();
-
-                               JcrUtils.clearAccessControList(session, homePath, username);
-                               JcrUtils.addPrivilege(session, homePath, username,
-                                               Privilege.JCR_ALL);
-                       } else {
-                               // for backward compatibility with pre 1.0 security model
-                               if (userHome.hasNode(ArgeoNames.ARGEO_PROFILE)) {
-                                       userHome.getNode(ArgeoNames.ARGEO_PROFILE).remove();
-                                       userHome.getSession().save();
-                               }
-                       }
-
-                       // Remote roles
-                       if (roles != null) {
-                               // writeRemoteRoles(userHome, roles);
-                       }
-
-                       Node userProfile = UserJcrUtils.getUserProfile(session, username);
-                       // new user
-                       if (userProfile == null) {
-                               String personPath = generateUserPath(peopleBasePath, username);
-                               Node personBase = JcrUtils.mkdirs(session, personPath);
-                               userProfile = personBase.addNode(ArgeoNames.ARGEO_PROFILE);
-                               userProfile.addMixin(ArgeoTypes.ARGEO_USER_PROFILE);
-                               userProfile.setProperty(ArgeoNames.ARGEO_USER_ID, username);
-                               userProfile.setProperty(ArgeoNames.ARGEO_ENABLED, true);
-                               userProfile.setProperty(ArgeoNames.ARGEO_ACCOUNT_NON_EXPIRED,
-                                               true);
-                               userProfile.setProperty(ArgeoNames.ARGEO_ACCOUNT_NON_LOCKED,
-                                               true);
-                               userProfile.setProperty(
-                                               ArgeoNames.ARGEO_CREDENTIALS_NON_EXPIRED, true);
-                               session.save();
-
-                               JcrUtils.clearAccessControList(session, userProfile.getPath(),
-                                               username);
-                               JcrUtils.addPrivilege(session, userProfile.getPath(), username,
-                                               Privilege.JCR_READ);
-                       }
-
-                       // Remote roles
-                       if (roles != null) {
-                               writeRemoteRoles(userProfile, roles);
-                       }
-                       return userProfile;
-               } catch (RepositoryException e) {
-                       JcrUtils.discardQuietly(session);
-                       throw new ArgeoException("Cannot sync node security model for "
-                                       + username, e);
-               }
-       }
-
-       /** Generate path for a new user home */
-       protected String generateUserPath(String base, String username) {
-               int atIndex = username.indexOf('@');
-               if (atIndex > 0) {
-                       String domain = username.substring(0, atIndex);
-                       String name = username.substring(atIndex + 1);
-                       return base + '/' + JcrUtils.firstCharsToPath(domain, 2) + '/'
-                                       + domain + '/' + JcrUtils.firstCharsToPath(name, 2) + '/'
-                                       + name;
-               } else if (atIndex == 0 || atIndex == (username.length() - 1)) {
-                       throw new ArgeoException("Unsupported username " + username);
-               } else {
-                       return base + '/' + JcrUtils.firstCharsToPath(username, 2) + '/'
-                                       + username;
-               }
-       }
-
-       /** Write remote roles used by remote access in the home directory */
-       protected void writeRemoteRoles(Node userHome, List<String> roles)
-                       throws RepositoryException {
-               boolean writeRoles = false;
-               if (userHome.hasProperty(ArgeoNames.ARGEO_REMOTE_ROLES)) {
-                       Value[] remoteRoles = userHome.getProperty(
-                                       ArgeoNames.ARGEO_REMOTE_ROLES).getValues();
-                       if (remoteRoles.length != roles.size())
-                               writeRoles = true;
-                       else
-                               for (int i = 0; i < remoteRoles.length; i++)
-                                       if (!remoteRoles[i].getString().equals(roles.get(i)))
-                                               writeRoles = true;
-               } else
-                       writeRoles = true;
-
-               if (writeRoles) {
-                       userHome.getSession().getWorkspace().getVersionManager()
-                                       .checkout(userHome.getPath());
-                       String[] roleIds = roles.toArray(new String[roles.size()]);
-                       userHome.setProperty(ArgeoNames.ARGEO_REMOTE_ROLES, roleIds);
-                       JcrUtils.updateLastModified(userHome);
-                       userHome.getSession().save();
-                       userHome.getSession().getWorkspace().getVersionManager()
-                                       .checkin(userHome.getPath());
-                       if (log.isDebugEnabled())
-                               log.debug("Wrote remote roles " + roles + " for "
-                                               + userHome.getProperty(ArgeoNames.ARGEO_USER_ID));
-               }
-
-       }
-
-       public void setHomeBasePath(String homeBasePath) {
-               this.homeBasePath = homeBasePath;
-       }
-
-}
index 2c6fe7de00ac60a618cf38eab1ef966d8f2ff46d..d4daef11f04b1f8205c9f1fa299dd9ca2d4dd3aa 100644 (file)
@@ -20,7 +20,6 @@ import javax.jcr.Node;
 import javax.jcr.Repository;
 import javax.jcr.RepositoryException;
 import javax.jcr.Session;
-import javax.jcr.Value;
 import javax.jcr.security.Privilege;
 import javax.naming.InvalidNameException;
 import javax.naming.ldap.LdapName;
@@ -61,8 +60,7 @@ public class NodeUserAdmin implements UserAdmin, KernelConstants {
                try {
                        ROLES_BASE = new LdapName(AuthConstants.ROLES_BASEDN);
                } catch (InvalidNameException e) {
-                       throw new UserDirectoryException("Cannot initialize "
-                                       + NodeUserAdmin.class, e);
+                       throw new UserDirectoryException("Cannot initialize " + NodeUserAdmin.class, e);
                }
        }
 
@@ -79,8 +77,7 @@ public class NodeUserAdmin implements UserAdmin, KernelConstants {
 
        private final String cacheName = UserDirectory.class.getName();
 
-       public NodeUserAdmin(TransactionManager transactionManager,
-                       Repository repository) {
+       public NodeUserAdmin(TransactionManager transactionManager, Repository repository) {
                this.repository = repository;
                try {
                        this.adminSession = this.repository.login();
@@ -100,8 +97,7 @@ public class NodeUserAdmin implements UserAdmin, KernelConstants {
                ((UserDirectory) nodeRoles).setTransactionManager(transactionManager);
                for (UserAdmin userAdmin : userAdmins.values()) {
                        if (userAdmin instanceof UserDirectory)
-                               ((UserDirectory) userAdmin)
-                                               .setTransactionManager(transactionManager);
+                               ((UserDirectory) userAdmin).setTransactionManager(transactionManager);
                }
 
                // JCR
@@ -113,14 +109,11 @@ public class NodeUserAdmin implements UserAdmin, KernelConstants {
                for (LdapName name : userAdmins.keySet()) {
                        StringBuilder buf = new StringBuilder();
                        if (userAdmins.get(name) instanceof UserDirectory) {
-                               UserDirectory userDirectory = (UserDirectory) userAdmins
-                                               .get(name);
-                               String uri = UserAdminConf.propertiesAsUri(
-                                               userDirectory.getProperties()).toString();
+                               UserDirectory userDirectory = (UserDirectory) userAdmins.get(name);
+                               String uri = UserAdminConf.propertiesAsUri(userDirectory.getProperties()).toString();
                                res.put(uri, "");
                        } else {
-                               buf.append('/').append(name.toString())
-                                               .append("?readOnly=true");
+                               buf.append('/').append(name.toString()).append("?readOnly=true");
                        }
                }
                return res;
@@ -129,12 +122,10 @@ public class NodeUserAdmin implements UserAdmin, KernelConstants {
        public void destroy() {
                for (LdapName name : userAdmins.keySet()) {
                        if (userAdmins.get(name) instanceof UserDirectory) {
-                               UserDirectory userDirectory = (UserDirectory) userAdmins
-                                               .get(name);
+                               UserDirectory userDirectory = (UserDirectory) userAdmins.get(name);
                                try {
                                        // FIXME Make it less bitronix dependant
-                                       EhCacheXAResourceProducer.unregisterXAResource(cacheName,
-                                                       userDirectory.getXaResource());
+                                       EhCacheXAResourceProducer.unregisterXAResource(cacheName, userDirectory.getXaResource());
                                } catch (Exception e) {
                                        log.error("Cannot unregister resource from Bitronix", e);
                                }
@@ -193,12 +184,10 @@ public class NodeUserAdmin implements UserAdmin, KernelConstants {
                // gather system roles
                Set<String> systemRoles = new HashSet<String>();
                for (String role : rawAuthorization.getRoles()) {
-                       Authorization auth = nodeRoles.getAuthorization((User) userAdmin
-                                       .getRole(role));
+                       Authorization auth = nodeRoles.getAuthorization((User) userAdmin.getRole(role));
                        systemRoles.addAll(Arrays.asList(auth.getRoles()));
                }
-               Authorization authorization = new NodeAuthorization(
-                               rawAuthorization.getName(), rawAuthorization.toString(),
+               Authorization authorization = new NodeAuthorization(rawAuthorization.getName(), rawAuthorization.toString(),
                                systemRoles, rawAuthorization.getRoles());
                syncJcr(adminSession, authorization);
                return authorization;
@@ -209,19 +198,16 @@ public class NodeUserAdmin implements UserAdmin, KernelConstants {
        //
        public void addUserAdmin(String baseDn, UserAdmin userAdmin) {
                if (userAdmins.containsKey(baseDn))
-                       throw new UserDirectoryException(
-                                       "There is already a user admin for " + baseDn);
+                       throw new UserDirectoryException("There is already a user admin for " + baseDn);
                try {
                        userAdmins.put(new LdapName(baseDn), userAdmin);
                } catch (InvalidNameException e) {
-                       throw new UserDirectoryException("Badly formatted base DN "
-                                       + baseDn, e);
+                       throw new UserDirectoryException("Badly formatted base DN " + baseDn, e);
                }
                if (userAdmin instanceof UserDirectory) {
                        try {
                                // FIXME Make it less bitronix dependant
-                               EhCacheXAResourceProducer.registerXAResource(cacheName,
-                                               ((UserDirectory) userAdmin).getXaResource());
+                               EhCacheXAResourceProducer.registerXAResource(cacheName, ((UserDirectory) userAdmin).getXaResource());
                        } catch (Exception e) {
                                log.error("Cannot register resource to Bitronix", e);
                        }
@@ -245,22 +231,18 @@ public class NodeUserAdmin implements UserAdmin, KernelConstants {
                                res.add(userAdmins.get(baseDn));
                }
                if (res.size() == 0)
-                       throw new UserDirectoryException("Cannot find user admin for "
-                                       + name);
+                       throw new UserDirectoryException("Cannot find user admin for " + name);
                if (res.size() > 1)
-                       throw new UserDirectoryException("Multiple user admin found for "
-                                       + name);
+                       throw new UserDirectoryException("Multiple user admin found for " + name);
                return res.get(0);
        }
 
        public void setTransactionManager(TransactionManager transactionManager) {
                if (nodeRoles instanceof UserDirectory)
-                       ((UserDirectory) nodeRoles)
-                                       .setTransactionManager(transactionManager);
+                       ((UserDirectory) nodeRoles).setTransactionManager(transactionManager);
                for (UserAdmin userAdmin : userAdmins.values()) {
                        if (userAdmin instanceof UserDirectory)
-                               ((UserDirectory) userAdmin)
-                                               .setTransactionManager(transactionManager);
+                               ((UserDirectory) userAdmin).setTransactionManager(transactionManager);
                }
        }
 
@@ -270,8 +252,7 @@ public class NodeUserAdmin implements UserAdmin, KernelConstants {
                        File businessRolesFile = new File(nodeBaseDir, demoBaseDn + ".ldif");
                        if (!businessRolesFile.exists())
                                try {
-                                       FileUtils.copyInputStreamToFile(getClass()
-                                                       .getResourceAsStream(demoBaseDn + ".ldif"),
+                                       FileUtils.copyInputStreamToFile(getClass().getResourceAsStream(demoBaseDn + ".ldif"),
                                                        businessRolesFile);
                                } catch (IOException e) {
                                        throw new CmsException("Cannot copy demo resource", e);
@@ -284,28 +265,23 @@ public class NodeUserAdmin implements UserAdmin, KernelConstants {
                        try {
                                u = new URI(uri);
                                if (u.getPath() == null)
-                                       throw new CmsException("URI " + uri
-                                                       + " must have a path in order to determine base DN");
+                                       throw new CmsException("URI " + uri + " must have a path in order to determine base DN");
                                if (u.getScheme() == null) {
-                                       if (uri.startsWith("/") || uri.startsWith("./")
-                                                       || uri.startsWith("../"))
+                                       if (uri.startsWith("/") || uri.startsWith("./") || uri.startsWith("../"))
                                                u = new File(uri).getCanonicalFile().toURI();
                                        else if (!uri.contains("/")) {
-                                               u = new URI(nodeBaseDir.toURI()+ uri);
+                                               u = new URI(nodeBaseDir.toURI() + uri);
                                                // u = new File(nodeBaseDir, uri).getCanonicalFile()
                                                // .toURI();
                                        } else
-                                               throw new CmsException("Cannot interpret " + uri
-                                                               + " as an uri");
+                                               throw new CmsException("Cannot interpret " + uri + " as an uri");
                                } else if (u.getScheme().equals("file")) {
                                        u = new File(u).getCanonicalFile().toURI();
                                }
                        } catch (Exception e) {
-                               throw new CmsException(
-                                               "Cannot interpret " + uri + " as an uri", e);
+                               throw new CmsException("Cannot interpret " + uri + " as an uri", e);
                        }
-                       Dictionary<String, ?> properties = UserAdminConf.uriAsProperties(u
-                                       .toString());
+                       Dictionary<String, ?> properties = UserAdminConf.uriAsProperties(u.toString());
                        UserDirectory businessRoles;
                        if (u.getScheme().startsWith("ldap")) {
                                businessRoles = new LdapUserAdmin(properties);
@@ -315,18 +291,15 @@ public class NodeUserAdmin implements UserAdmin, KernelConstants {
                        businessRoles.init();
                        String baseDn = businessRoles.getBaseDn();
                        if (userAdmins.containsKey(baseDn))
-                               throw new UserDirectoryException(
-                                               "There is already a user admin for " + baseDn);
+                               throw new UserDirectoryException("There is already a user admin for " + baseDn);
                        try {
                                userAdmins.put(new LdapName(baseDn), (UserAdmin) businessRoles);
                        } catch (InvalidNameException e) {
-                               throw new UserDirectoryException("Badly formatted base DN "
-                                               + baseDn, e);
+                               throw new UserDirectoryException("Badly formatted base DN " + baseDn, e);
                        }
                        addUserAdmin(businessRoles.getBaseDn(), (UserAdmin) businessRoles);
                        if (log.isDebugEnabled())
-                               log.debug("User directory " + businessRoles.getBaseDn() + " ["
-                                               + u.getScheme() + "] enabled.");
+                               log.debug("User directory " + businessRoles.getBaseDn() + " [" + u.getScheme() + "] enabled.");
                }
 
        }
@@ -337,8 +310,7 @@ public class NodeUserAdmin implements UserAdmin, KernelConstants {
                        File nodeRolesFile = new File(nodeBaseDir, baseNodeRoleDn + ".ldif");
                        if (!nodeRolesFile.exists())
                                try {
-                                       FileUtils.copyInputStreamToFile(getClass()
-                                                       .getResourceAsStream(baseNodeRoleDn + ".ldif"),
+                                       FileUtils.copyInputStreamToFile(getClass().getResourceAsStream(baseNodeRoleDn + ".ldif"),
                                                        nodeRolesFile);
                                } catch (IOException e) {
                                        throw new CmsException("Cannot copy demo resource", e);
@@ -346,10 +318,8 @@ public class NodeUserAdmin implements UserAdmin, KernelConstants {
                        nodeRolesUri = nodeRolesFile.toURI().toString();
                }
 
-               Dictionary<String, ?> nodeRolesProperties = UserAdminConf
-                               .uriAsProperties(nodeRolesUri);
-               if (!nodeRolesProperties.get(UserAdminConf.baseDn.property()).equals(
-                               baseNodeRoleDn)) {
+               Dictionary<String, ?> nodeRolesProperties = UserAdminConf.uriAsProperties(nodeRolesUri);
+               if (!nodeRolesProperties.get(UserAdminConf.baseDn.property()).equals(baseNodeRoleDn)) {
                        throw new CmsException("Invalid base dn for node roles");
                        // TODO deal with "mounted" roles with a different baseDN
                }
@@ -375,10 +345,8 @@ public class NodeUserAdmin implements UserAdmin, KernelConstants {
                        JcrUtils.mkdirs(adminSession, peopleBasePath);
                        adminSession.save();
 
-                       JcrUtils.addPrivilege(adminSession, homeBasePath,
-                                       AuthConstants.ROLE_USER_ADMIN, Privilege.JCR_READ);
-                       JcrUtils.addPrivilege(adminSession, peopleBasePath,
-                                       AuthConstants.ROLE_USER_ADMIN, Privilege.JCR_ALL);
+                       JcrUtils.addPrivilege(adminSession, homeBasePath, AuthConstants.ROLE_USER_ADMIN, Privilege.JCR_READ);
+                       JcrUtils.addPrivilege(adminSession, peopleBasePath, AuthConstants.ROLE_USER_ADMIN, Privilege.JCR_ALL);
                        adminSession.save();
                } catch (RepositoryException e) {
                        throw new CmsException("Cannot initialize node user admin", e);
@@ -388,14 +356,13 @@ public class NodeUserAdmin implements UserAdmin, KernelConstants {
        private Node syncJcr(Session session, Authorization authorization) {
                // TODO check user name validity (e.g. should not start by ROLE_)
                String username = authorization.getName();
-               String[] roles = authorization.getRoles();
+               // String[] roles = authorization.getRoles();
                try {
                        Node userHome = UserJcrUtils.getUserHome(session, username);
                        if (userHome == null) {
                                String homePath = generateUserPath(homeBasePath, username);
                                if (session.itemExists(homePath))// duplicate user id
-                                       userHome = session.getNode(homePath).getParent()
-                                                       .addNode(JcrUtils.lastPathElement(homePath));
+                                       userHome = session.getNode(homePath).getParent().addNode(JcrUtils.lastPathElement(homePath));
                                else
                                        userHome = JcrUtils.mkdirs(session, homePath);
                                // userHome = JcrUtils.mkfolders(session, homePath);
@@ -404,8 +371,7 @@ public class NodeUserAdmin implements UserAdmin, KernelConstants {
                                session.save();
 
                                JcrUtils.clearAccessControList(session, homePath, username);
-                               JcrUtils.addPrivilege(session, homePath, username,
-                                               Privilege.JCR_ALL);
+                               JcrUtils.addPrivilege(session, homePath, username, Privilege.JCR_ALL);
                        }
 
                        Node userProfile = UserJcrUtils.getUserProfile(session, username);
@@ -414,38 +380,32 @@ public class NodeUserAdmin implements UserAdmin, KernelConstants {
                                String personPath = generateUserPath(peopleBasePath, username);
                                Node personBase;
                                if (session.itemExists(personPath))// duplicate user id
-                                       personBase = session.getNode(personPath).getParent()
-                                                       .addNode(JcrUtils.lastPathElement(personPath));
+                                       personBase = session.getNode(personPath).getParent().addNode(JcrUtils.lastPathElement(personPath));
                                else
                                        personBase = JcrUtils.mkdirs(session, personPath);
                                userProfile = personBase.addNode(ArgeoNames.ARGEO_PROFILE);
                                userProfile.addMixin(ArgeoTypes.ARGEO_USER_PROFILE);
                                userProfile.setProperty(ArgeoNames.ARGEO_USER_ID, username);
                                userProfile.setProperty(ArgeoNames.ARGEO_ENABLED, true);
-                               userProfile.setProperty(ArgeoNames.ARGEO_ACCOUNT_NON_EXPIRED,
-                                               true);
-                               userProfile.setProperty(ArgeoNames.ARGEO_ACCOUNT_NON_LOCKED,
-                                               true);
-                               userProfile.setProperty(
-                                               ArgeoNames.ARGEO_CREDENTIALS_NON_EXPIRED, true);
+                               userProfile.setProperty(ArgeoNames.ARGEO_ACCOUNT_NON_EXPIRED, true);
+                               userProfile.setProperty(ArgeoNames.ARGEO_ACCOUNT_NON_LOCKED, true);
+                               userProfile.setProperty(ArgeoNames.ARGEO_CREDENTIALS_NON_EXPIRED, true);
                                session.save();
 
-                               JcrUtils.clearAccessControList(session, userProfile.getPath(),
-                                               username);
-                               JcrUtils.addPrivilege(session, userProfile.getPath(), username,
-                                               Privilege.JCR_READ);
+                               JcrUtils.clearAccessControList(session, userProfile.getPath(), username);
+                               JcrUtils.addPrivilege(session, userProfile.getPath(), username, Privilege.JCR_READ);
                        }
 
                        // Remote roles
-                       if (roles != null) {
-                               writeRemoteRoles(userProfile, roles);
-                       }
-                       adminSession.save();
+                       // if (roles != null) {
+                       // writeRemoteRoles(userProfile, roles);
+                       // }
+                       if (adminSession.hasPendingChanges())
+                               adminSession.save();
                        return userProfile;
                } catch (RepositoryException e) {
                        JcrUtils.discardQuietly(session);
-                       throw new ArgeoException("Cannot sync node security model for "
-                                       + username, e);
+                       throw new ArgeoException("Cannot sync node security model for " + username, e);
                }
        }
 
@@ -462,46 +422,43 @@ public class NodeUserAdmin implements UserAdmin, KernelConstants {
                if (atIndex > 0) {
                        String domain = userId.substring(0, atIndex);
                        String name = userId.substring(atIndex + 1);
-                       return base + '/' + JcrUtils.firstCharsToPath(domain, 2) + '/'
-                                       + domain + '/' + JcrUtils.firstCharsToPath(name, 2) + '/'
-                                       + name;
+                       return base + '/' + JcrUtils.firstCharsToPath(domain, 2) + '/' + domain + '/'
+                                       + JcrUtils.firstCharsToPath(name, 2) + '/' + name;
                } else if (atIndex == 0 || atIndex == (userId.length() - 1)) {
                        throw new ArgeoException("Unsupported username " + userId);
                } else {
-                       return base + '/' + JcrUtils.firstCharsToPath(userId, 2) + '/'
-                                       + userId;
+                       return base + '/' + JcrUtils.firstCharsToPath(userId, 2) + '/' + userId;
                }
        }
 
-       /** Write remote roles used by remote access in the home directory */
-       private void writeRemoteRoles(Node userHome, String[] roles)
-                       throws RepositoryException {
-               boolean writeRoles = false;
-               if (userHome.hasProperty(ArgeoNames.ARGEO_REMOTE_ROLES)) {
-                       Value[] remoteRoles = userHome.getProperty(
-                                       ArgeoNames.ARGEO_REMOTE_ROLES).getValues();
-                       if (remoteRoles.length != roles.length)
-                               writeRoles = true;
-                       else
-                               for (int i = 0; i < remoteRoles.length; i++)
-                                       if (!remoteRoles[i].getString().equals(roles[i]))
-                                               writeRoles = true;
-               } else
-                       writeRoles = true;
-
-               if (writeRoles) {
-                       userHome.getSession().getWorkspace().getVersionManager()
-                                       .checkout(userHome.getPath());
-                       userHome.setProperty(ArgeoNames.ARGEO_REMOTE_ROLES, roles);
-                       JcrUtils.updateLastModified(userHome);
-                       userHome.getSession().save();
-                       userHome.getSession().getWorkspace().getVersionManager()
-                                       .checkin(userHome.getPath());
-                       if (log.isDebugEnabled())
-                               log.debug("Wrote remote roles " + roles + " for "
-                                               + userHome.getProperty(ArgeoNames.ARGEO_USER_ID));
-               }
-
-       }
-
+       // /** Write remote roles used by remote access in the home directory */
+       // private void writeRemoteRoles(Node userHome, String[] roles)
+       // throws RepositoryException {
+       // boolean writeRoles = false;
+       // if (userHome.hasProperty(ArgeoNames.ARGEO_REMOTE_ROLES)) {
+       // Value[] remoteRoles = userHome.getProperty(
+       // ArgeoNames.ARGEO_REMOTE_ROLES).getValues();
+       // if (remoteRoles.length != roles.length)
+       // writeRoles = true;
+       // else
+       // for (int i = 0; i < remoteRoles.length; i++)
+       // if (!remoteRoles[i].getString().equals(roles[i]))
+       // writeRoles = true;
+       // } else
+       // writeRoles = true;
+       //
+       // if (writeRoles) {
+       // userHome.getSession().getWorkspace().getVersionManager()
+       // .checkout(userHome.getPath());
+       // userHome.setProperty(ArgeoNames.ARGEO_REMOTE_ROLES, roles);
+       // JcrUtils.updateLastModified(userHome);
+       // userHome.getSession().save();
+       // userHome.getSession().getWorkspace().getVersionManager()
+       // .checkin(userHome.getPath());
+       // if (log.isDebugEnabled())
+       // log.debug("Wrote remote roles " + roles + " for "
+       // + userHome.getProperty(ArgeoNames.ARGEO_USER_ID));
+       // }
+       //
+       // }
 }
index f871cd25e8af8c8c97e96e06ab9f62ff2136bcaa..768610b8e22ae68262e8f8ca9d54abd5851ba70f 100644 (file)
@@ -1,15 +1,10 @@
 package org.argeo.osgi.useradmin;
 
-import static org.argeo.osgi.useradmin.LdifName.gidNumber;
-import static org.argeo.osgi.useradmin.LdifName.homeDirectory;
 import static org.argeo.osgi.useradmin.LdifName.inetOrgPerson;
 import static org.argeo.osgi.useradmin.LdifName.objectClass;
 import static org.argeo.osgi.useradmin.LdifName.organizationalPerson;
 import static org.argeo.osgi.useradmin.LdifName.person;
-import static org.argeo.osgi.useradmin.LdifName.posixAccount;
 import static org.argeo.osgi.useradmin.LdifName.top;
-import static org.argeo.osgi.useradmin.LdifName.uid;
-import static org.argeo.osgi.useradmin.LdifName.uidNumber;
 
 import java.io.File;
 import java.net.URI;
@@ -23,7 +18,6 @@ import java.util.Iterator;
 import java.util.List;
 
 import javax.naming.InvalidNameException;
-import javax.naming.NamingException;
 import javax.naming.directory.Attributes;
 import javax.naming.directory.BasicAttribute;
 import javax.naming.directory.BasicAttributes;
@@ -35,7 +29,6 @@ import javax.transaction.TransactionManager;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
 import org.osgi.framework.Filter;
 import org.osgi.framework.FrameworkUtil;
 import org.osgi.framework.InvalidSyntaxException;
@@ -46,8 +39,7 @@ import org.osgi.service.useradmin.UserAdmin;
 
 /** Base class for a {@link UserDirectory}. */
 abstract class AbstractUserDirectory implements UserAdmin, UserDirectory {
-       private final static Log log = LogFactory
-                       .getLog(AbstractUserDirectory.class);
+       private final static Log log = LogFactory.getLog(AbstractUserDirectory.class);
 
        private final Hashtable<String, Object> properties;
        private final String baseDn;
@@ -58,12 +50,11 @@ abstract class AbstractUserDirectory implements UserAdmin, UserDirectory {
        private final URI uri;
 
        private UserAdmin externalRoles;
-       private List<String> indexedUserProperties = Arrays.asList(new String[] {
-                       LdifName.uid.name(), LdifName.mail.name(), LdifName.cn.name() });
+       private List<String> indexedUserProperties = Arrays
+                       .asList(new String[] { LdifName.uid.name(), LdifName.mail.name(), LdifName.cn.name() });
 
        private String memberAttributeId = "member";
-       private List<String> credentialAttributeIds = Arrays
-                       .asList(new String[] { LdifName.userPassword.name() });
+       private List<String> credentialAttributeIds = Arrays.asList(new String[] { LdifName.userPassword.name() });
 
        private TransactionManager transactionManager;
        // private TransactionSynchronizationRegistry transactionRegistry;
@@ -87,16 +78,14 @@ abstract class AbstractUserDirectory implements UserAdmin, UserDirectory {
                        try {
                                uri = new URI(uriStr);
                        } catch (URISyntaxException e) {
-                               throw new UserDirectoryException("Badly formatted URI "
-                                               + uriStr, e);
+                               throw new UserDirectoryException("Badly formatted URI " + uriStr, e);
                        }
 
                baseDn = UserAdminConf.baseDn.getValue(properties).toString();
                String readOnlyStr = UserAdminConf.readOnly.getValue(properties);
                if (readOnlyStr == null) {
                        readOnly = readOnlyDefault(uri);
-                       properties.put(UserAdminConf.readOnly.property(),
-                                       Boolean.toString(readOnly));
+                       properties.put(UserAdminConf.readOnly.property(), Boolean.toString(readOnly));
                } else
                        readOnly = new Boolean(readOnlyStr);
 
@@ -148,8 +137,7 @@ abstract class AbstractUserDirectory implements UserAdmin, UserDirectory {
                        throw new UserDirectoryException("Cannot get transaction", e);
                }
                if (transaction == null)
-                       throw new UserDirectoryException(
-                                       "A transaction needs to be active in order to edit");
+                       throw new UserDirectoryException("A transaction needs to be active in order to edit");
                if (xaResource.wc() == null) {
                        // UserDirectoryWorkingCopy wc = new UserDirectoryWorkingCopy(this);
                        try {
@@ -157,8 +145,7 @@ abstract class AbstractUserDirectory implements UserAdmin, UserDirectory {
                                // editingTransactionXid = wc.getXid();
                                // workingCopy.set(wc);
                        } catch (Exception e) {
-                               throw new UserDirectoryException("Cannot enlist " + xaResource,
-                                               e);
+                               throw new UserDirectoryException("Cannot enlist " + xaResource, e);
                        }
                } else {
                        // UserDirectoryWorkingCopy wc = xaResource.wc();
@@ -240,8 +227,7 @@ abstract class AbstractUserDirectory implements UserAdmin, UserDirectory {
        @Override
        public User getUser(String key, String value) {
                // TODO check value null or empty
-               List<DirectoryUser> collectedUsers = new ArrayList<DirectoryUser>(
-                               getIndexedUserProperties().size());
+               List<DirectoryUser> collectedUsers = new ArrayList<DirectoryUser>(getIndexedUserProperties().size());
                if (key != null) {
                        doGetUser(key, value, collectedUsers);
                } else {
@@ -261,28 +247,23 @@ abstract class AbstractUserDirectory implements UserAdmin, UserDirectory {
                if (collectedUsers.size() == 1)
                        return collectedUsers.get(0);
                else if (collectedUsers.size() > 1)
-                       log.warn(collectedUsers.size() + " users for "
-                                       + (key != null ? key + "=" : "") + value);
+                       log.warn(collectedUsers.size() + " users for " + (key != null ? key + "=" : "") + value);
                return null;
        }
 
-       protected void doGetUser(String key, String value,
-                       List<DirectoryUser> collectedUsers) {
+       protected void doGetUser(String key, String value, List<DirectoryUser> collectedUsers) {
                try {
-                       Filter f = FrameworkUtil
-                                       .createFilter("(" + key + "=" + value + ")");
+                       Filter f = FrameworkUtil.createFilter("(" + key + "=" + value + ")");
                        List<DirectoryUser> users = doGetRoles(f);
                        collectedUsers.addAll(users);
                } catch (InvalidSyntaxException e) {
-                       throw new UserDirectoryException("Cannot get user with " + key
-                                       + "=" + value, e);
+                       throw new UserDirectoryException("Cannot get user with " + key + "=" + value, e);
                }
        }
 
        @Override
        public Authorization getAuthorization(User user) {
-               return new LdifAuthorization((DirectoryUser) user,
-                               getAllRoles((DirectoryUser) user));
+               return new LdifAuthorization((DirectoryUser) user, getAllRoles((DirectoryUser) user));
        }
 
        @Override
@@ -290,11 +271,10 @@ abstract class AbstractUserDirectory implements UserAdmin, UserDirectory {
                checkEdit();
                UserDirectoryWorkingCopy wc = getWorkingCopy();
                LdapName dn = toDn(name);
-               if ((daoHasRole(dn) && !wc.getDeletedUsers().containsKey(dn))
-                               || wc.getNewUsers().containsKey(dn))
+               if ((daoHasRole(dn) && !wc.getDeletedUsers().containsKey(dn)) || wc.getNewUsers().containsKey(dn))
                        throw new UserDirectoryException("Already a role " + name);
                BasicAttributes attrs = new BasicAttributes(true);
-               attrs.put("dn", dn.toString());
+               // attrs.put(LdifName.dn.name(), dn.toString());
                Rdn nameRdn = dn.getRdn(dn.size() - 1);
                // TODO deal with multiple attr RDN
                attrs.put(nameRdn.getType(), nameRdn.getValue());
@@ -315,41 +295,20 @@ abstract class AbstractUserDirectory implements UserAdmin, UserDirectory {
                if (type == Role.USER) {
                        String userObjClass = newUserObjectClass(dn);
                        objClass.add(userObjClass);
-                       if (posixAccount.name().equals(userObjClass)) {
-                               objClass.add(inetOrgPerson.name());
-                               objClass.add(organizationalPerson.name());
-                               objClass.add(person.name());
-
-                               String username;
-                               try {
-                                       username = dn.getRdn(dn.size() - 1).toAttributes()
-                                                       .get(uid.name()).get().toString();
-                               } catch (NamingException e) {
-                                       throw new UserDirectoryException(
-                                                       "Cannot extract username from " + dn, e);
-                               }
-                               // TODO look for uid in attributes too?
-                               attrs.put(uidNumber.name(), new Long(max(uidNumber.name()) + 1));
-                               attrs.put(homeDirectory.name(), generateHomeDirectory(username));
-                               // TODO create user private group
-                               // NB: on RHEL, the 'users' group has gid 100
-                               attrs.put(gidNumber.name(), 100);
-                               // attrs.put(LdifName.loginShell.name(),"/sbin/nologin");
-                       } else if (inetOrgPerson.name().equals(userObjClass)) {
+                       if (inetOrgPerson.name().equals(userObjClass)) {
                                objClass.add(organizationalPerson.name());
                                objClass.add(person.name());
                        } else if (organizationalPerson.name().equals(userObjClass)) {
                                objClass.add(person.name());
                        }
-                       objClass.add(top);
+                       objClass.add(top.name());
                        attrs.put(objClass);
                        newRole = new LdifUser(this, dn, attrs);
                } else if (type == Role.GROUP) {
                        String groupObjClass = getGroupObjectClass();
                        objClass.add(groupObjClass);
-                       objClass.add(LdifName.extensibleObject.name());
-                       attrs.put(gidNumber.name(), new Long(max(gidNumber.name()) + 1));
-                       objClass.add(top);
+                       // objClass.add(LdifName.extensibleObject.name());
+                       objClass.add(top.name());
                        attrs.put(objClass);
                        newRole = new LdifGroup(this, dn, attrs);
                } else
@@ -372,65 +331,66 @@ abstract class AbstractUserDirectory implements UserAdmin, UserDirectory {
                }
                for (LdapName groupDn : getDirectGroups(dn)) {
                        DirectoryUser group = doGetRole(groupDn);
-                       group.getAttributes().get(getMemberAttributeId())
-                                       .remove(dn.toString());
+                       group.getAttributes().get(getMemberAttributeId()).remove(dn.toString());
                }
                return actuallyDeleted;
        }
 
-       // POSIX
-       /** Generate path for a new user home */
-       protected String generateHomeDirectory(String username) {
-               String base = homeDirectoryBase;
-               int atIndex = username.indexOf('@');
-               if (atIndex > 0) {
-                       String domain = username.substring(0, atIndex);
-                       String name = username.substring(atIndex + 1);
-                       return base + '/' + firstCharsToPath(domain, 2) + '/' + domain
-                                       + '/' + firstCharsToPath(name, 2) + '/' + name;
-               } else if (atIndex == 0 || atIndex == (username.length() - 1)) {
-                       throw new ArgeoException("Unsupported username " + username);
-               } else {
-                       return base + '/' + firstCharsToPath(username, 2) + '/' + username;
-               }
-       }
+       // // POSIX
+       // /** Generate path for a new user home */
+       // protected String generateHomeDirectory(String username) {
+       // String base = homeDirectoryBase;
+       // int atIndex = username.indexOf('@');
+       // if (atIndex > 0) {
+       // String domain = username.substring(0, atIndex);
+       // String name = username.substring(atIndex + 1);
+       // return base + '/' + firstCharsToPath(domain, 2) + '/' + domain + '/' +
+       // firstCharsToPath(name, 2) + '/'
+       // + name;
+       // } else if (atIndex == 0 || atIndex == (username.length() - 1)) {
+       // throw new ArgeoException("Unsupported username " + username);
+       // } else {
+       // return base + '/' + firstCharsToPath(username, 2) + '/' + username;
+       // }
+       // }
+       //
+       // protected long max(String attr) {
+       // long max;
+       // try {
+       // List<DirectoryUser> users = doGetRoles(FrameworkUtil.createFilter("(" +
+       // attr + "=*)"));
+       // max = 1000;
+       // for (DirectoryUser user : users) {
+       // long uid =
+       // Long.parseLong(user.getAttributes().get(attr).get().toString());
+       // if (uid > max)
+       // max = uid;
+       // }
+       // } catch (Exception e) {
+       // throw new UserDirectoryException("Cannot get max of " + attr, e);
+       // }
+       // return max;
+       // }
 
-       protected long max(String attr) {
-               long max;
-               try {
-                       List<DirectoryUser> users = doGetRoles(FrameworkUtil
-                                       .createFilter("(" + attr + "=*)"));
-                       max = 1000;
-                       for (DirectoryUser user : users) {
-                               long uid = Long.parseLong(user.getAttributes().get(attr).get()
-                                               .toString());
-                               if (uid > max)
-                                       max = uid;
-                       }
-               } catch (Exception e) {
-                       throw new UserDirectoryException("Cannot get max of " + attr, e);
-               }
-               return max;
-       }
-
-       /**
-        * Creates depth from a string (typically a username) by adding levels based
-        * on its first characters: "aBcD",2 => a/aB
-        */
-       public static String firstCharsToPath(String str, Integer nbrOfChars) {
-               if (str.length() < nbrOfChars)
-                       throw new ArgeoException("String " + str
-                                       + " length must be greater or equal than " + nbrOfChars);
-               StringBuffer path = new StringBuffer("");
-               StringBuffer curr = new StringBuffer("");
-               for (int i = 0; i < nbrOfChars; i++) {
-                       curr.append(str.charAt(i));
-                       path.append(curr);
-                       if (i < nbrOfChars - 1)
-                               path.append('/');
-               }
-               return path.toString();
-       }
+       // /**
+       // * Creates depth from a string (typically a username) by adding levels
+       // based
+       // * on its first characters: "aBcD",2 => a/aB
+       // */
+       // public static String firstCharsToPath(String str, Integer nbrOfChars) {
+       // if (str.length() < nbrOfChars)
+       // throw new ArgeoException("String " + str + " length must be greater or
+       // equal than " + nbrOfChars);
+       // StringBuffer path = new StringBuffer("");
+       // StringBuffer curr = new StringBuffer("");
+       // for (int i = 0; i < nbrOfChars; i++) {
+       // curr.append(str.charAt(i));
+       // path.append(curr);
+       // if (i < nbrOfChars - 1)
+       // path.append('/');
+       // }
+       // return path.toString();
+       // }
 
        // TRANSACTION
        protected void prepare(UserDirectoryWorkingCopy wc) {
@@ -511,11 +471,7 @@ abstract class AbstractUserDirectory implements UserAdmin, UserDirectory {
        }
 
        protected String newUserObjectClass(LdapName dn) {
-               if (dn != null
-                               && dn.getRdn(dn.size() - 1).toAttributes().get(uid.name()) != null)
-                       return posixAccount.name();
-               else
-                       return getUserObjectClass();
+               return getUserObjectClass();
        }
 
        protected String getGroupObjectClass() {
index 22d9a54227b383d629f13e6be760731bd01b972d..c2e26ca4cfc09b610cc9880679f9175c8da7ea83 100644 (file)
@@ -40,26 +40,21 @@ public class LdapUserAdmin extends AbstractUserDirectory {
                super(properties);
                try {
                        Hashtable<String, Object> connEnv = new Hashtable<String, Object>();
-                       connEnv.put(Context.INITIAL_CONTEXT_FACTORY,
-                                       "com.sun.jndi.ldap.LdapCtxFactory");
+                       connEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
                        connEnv.put(Context.PROVIDER_URL, getUri().toString());
-                       connEnv.put("java.naming.ldap.attributes.binary",
-                                       LdifName.userPassword.name());
+                       connEnv.put("java.naming.ldap.attributes.binary", LdifName.userPassword.name());
 
                        initialLdapContext = new InitialLdapContext(connEnv, null);
                        // StartTlsResponse tls = (StartTlsResponse) ctx
                        // .extendedOperation(new StartTlsRequest());
                        // tls.negotiate();
-                       initialLdapContext.addToEnvironment(
-                                       Context.SECURITY_AUTHENTICATION, "simple");
+                       initialLdapContext.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
                        Object principal = properties.get(Context.SECURITY_PRINCIPAL);
                        if (principal != null) {
-                               initialLdapContext.addToEnvironment(Context.SECURITY_PRINCIPAL,
-                                               principal.toString());
+                               initialLdapContext.addToEnvironment(Context.SECURITY_PRINCIPAL, principal.toString());
                                Object creds = properties.get(Context.SECURITY_CREDENTIALS);
                                if (creds != null) {
-                                       initialLdapContext.addToEnvironment(
-                                                       Context.SECURITY_CREDENTIALS, creds.toString());
+                                       initialLdapContext.addToEnvironment(Context.SECURITY_CREDENTIALS, creds.toString());
 
                                }
                        }
@@ -99,12 +94,10 @@ public class LdapUserAdmin extends AbstractUserDirectory {
                        LdifUser res;
                        if (attrs.get(objectClass.name()).contains(getGroupObjectClass()))
                                res = new LdifGroup(this, name, attrs);
-                       else if (attrs.get(objectClass.name()).contains(
-                                       getUserObjectClass()))
+                       else if (attrs.get(objectClass.name()).contains(getUserObjectClass()))
                                res = new LdifUser(this, name, attrs);
                        else
-                               throw new UserDirectoryException("Unsupported LDAP type for "
-                                               + name);
+                               throw new UserDirectoryException("Unsupported LDAP type for " + name);
                        return res;
                } catch (NamingException e) {
                        return null;
@@ -114,15 +107,14 @@ public class LdapUserAdmin extends AbstractUserDirectory {
        @Override
        protected List<DirectoryUser> doGetRoles(Filter f) {
                try {
-                       String searchFilter = f != null ? f.toString() : "(|("
-                                       + objectClass + "=" + getUserObjectClass() + ")("
-                                       + objectClass + "=" + getGroupObjectClass() + "))";
+                       String searchFilter = f != null ? f.toString()
+                                       : "(|(" + objectClass + "=" + getUserObjectClass() + ")(" + objectClass + "="
+                                                       + getGroupObjectClass() + "))";
                        SearchControls searchControls = new SearchControls();
                        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
 
                        String searchBase = getBaseDn();
-                       NamingEnumeration<SearchResult> results = getLdapContext().search(
-                                       searchBase, searchFilter, searchControls);
+                       NamingEnumeration<SearchResult> results = getLdapContext().search(searchBase, searchFilter, searchControls);
 
                        ArrayList<DirectoryUser> res = new ArrayList<DirectoryUser>();
                        results: while (results.hasMoreElements()) {
@@ -136,49 +128,41 @@ public class LdapUserAdmin extends AbstractUserDirectory {
                                else if (objectClassAttr.contains(getUserObjectClass()))
                                        role = new LdifUser(this, dn, attrs);
                                else {
-                                       log.warn("Unsupported LDAP type for "
-                                                       + searchResult.getName());
+                                       log.warn("Unsupported LDAP type for " + searchResult.getName());
                                        continue results;
                                }
                                res.add(role);
                        }
                        return res;
                } catch (Exception e) {
-                       throw new UserDirectoryException(
-                                       "Cannot get roles for filter " + f, e);
+                       throw new UserDirectoryException("Cannot get roles for filter " + f, e);
                }
        }
 
-       private LdapName toDn(String baseDn, Binding binding)
-                       throws InvalidNameException {
-               return new LdapName(binding.isRelative() ? binding.getName() + ","
-                               + baseDn : binding.getName());
+       private LdapName toDn(String baseDn, Binding binding) throws InvalidNameException {
+               return new LdapName(binding.isRelative() ? binding.getName() + "," + baseDn : binding.getName());
        }
 
        @Override
        protected List<LdapName> getDirectGroups(LdapName dn) {
                List<LdapName> directGroups = new ArrayList<LdapName>();
                try {
-                       String searchFilter = "(&(" + objectClass + "="
-                                       + getGroupObjectClass() + ")(" + getMemberAttributeId()
+                       String searchFilter = "(&(" + objectClass + "=" + getGroupObjectClass() + ")(" + getMemberAttributeId()
                                        + "=" + dn + "))";
 
                        SearchControls searchControls = new SearchControls();
                        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
 
                        String searchBase = getBaseDn();
-                       NamingEnumeration<SearchResult> results = getLdapContext().search(
-                                       searchBase, searchFilter, searchControls);
+                       NamingEnumeration<SearchResult> results = getLdapContext().search(searchBase, searchFilter, searchControls);
 
                        while (results.hasMoreElements()) {
-                               SearchResult searchResult = (SearchResult) results
-                                               .nextElement();
+                               SearchResult searchResult = (SearchResult) results.nextElement();
                                directGroups.add(toDn(searchBase, searchResult));
                        }
                        return directGroups;
                } catch (Exception e) {
-                       throw new ArgeoException("Cannot populate direct members of " + dn,
-                                       e);
+                       throw new ArgeoException("Cannot populate direct members of " + dn, e);
                }
        }
 
@@ -189,20 +173,17 @@ public class LdapUserAdmin extends AbstractUserDirectory {
                        // delete
                        for (LdapName dn : wc.getDeletedUsers().keySet()) {
                                if (!entryExists(dn))
-                                       throw new UserDirectoryException("User to delete no found "
-                                                       + dn);
+                                       throw new UserDirectoryException("User to delete no found " + dn);
                        }
                        // add
                        for (LdapName dn : wc.getNewUsers().keySet()) {
                                if (entryExists(dn))
-                                       throw new UserDirectoryException("User to create found "
-                                                       + dn);
+                                       throw new UserDirectoryException("User to create found " + dn);
                        }
                        // modify
                        for (LdapName dn : wc.getModifiedUsers().keySet()) {
-                               if (!entryExists(dn))
-                                       throw new UserDirectoryException("User to modify not found "
-                                                       + dn);
+                               if (!wc.getNewUsers().containsKey(dn) && !entryExists(dn))
+                                       throw new UserDirectoryException("User to modify not found " + dn);
                        }
                } catch (NamingException e) {
                        throw new UserDirectoryException("Cannot prepare LDAP", e);
@@ -232,8 +213,7 @@ public class LdapUserAdmin extends AbstractUserDirectory {
                        // modify
                        for (LdapName dn : wc.getModifiedUsers().keySet()) {
                                Attributes modifiedAttrs = wc.getModifiedUsers().get(dn);
-                               getLdapContext().modifyAttributes(dn,
-                                               DirContext.REPLACE_ATTRIBUTE, modifiedAttrs);
+                               getLdapContext().modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE, modifiedAttrs);
                        }
                } catch (NamingException e) {
                        throw new UserDirectoryException("Cannot commit LDAP", e);
index ff8803dedb48fde1984a363d6f27dd7834804ae9..919e5073f88e1d5e751aba174227b4cc08eb0c56 100644 (file)
@@ -10,10 +10,8 @@ import javax.naming.ldap.LdapName;
 public enum LdifName {
        // Attributes
        dn, dc, cn, sn, uid, mail, displayName, objectClass, userPassword, givenName, description, member,
-       // POSIX attributes
-       uidNumber, gidNumber, homeDirectory, loginShell, gecos,
        // Object classes
-       posixAccount, inetOrgPerson, organizationalPerson, person, groupOfNames, groupOfUniqueNames, extensibleObject, top;
+       inetOrgPerson, organizationalPerson, person, groupOfNames, groupOfUniqueNames, top;
 
        public final static String PREFIX = "ldap:";
 
index 6e3eca9992e05610ce7adb435af10685095b41f3..1d4582a78fcf0ca89cd8d3afb78c9d7af61d6a09 100644 (file)
@@ -27,7 +27,7 @@ public interface ArgeoNames {
 
        public final static String ARGEO_REMOTE = "argeo:remote";
        public final static String ARGEO_PASSWORD = "argeo:password";
-       public final static String ARGEO_REMOTE_ROLES = "argeo:remoteRoles";
+//     public final static String ARGEO_REMOTE_ROLES = "argeo:remoteRoles";
 
        // user profile
        public final static String ARGEO_PROFILE = "argeo:profile";