+++ /dev/null
-/*
- * 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);
-}
+++ /dev/null
-/*
- * 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;
- }
-
-}
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;
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);
}
}
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();
((UserDirectory) nodeRoles).setTransactionManager(transactionManager);
for (UserAdmin userAdmin : userAdmins.values()) {
if (userAdmin instanceof UserDirectory)
- ((UserDirectory) userAdmin)
- .setTransactionManager(transactionManager);
+ ((UserDirectory) userAdmin).setTransactionManager(transactionManager);
}
// JCR
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;
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);
}
// 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;
//
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);
}
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);
}
}
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);
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);
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.");
}
}
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);
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
}
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);
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);
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);
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);
}
}
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));
+ // }
+ //
+ // }
}
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;
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;
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;
/** 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;
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;
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);
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 {
// 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();
@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 {
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
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());
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
}
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) {
}
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() {
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());
}
}
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;
@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()) {
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);
}
}
// 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);
// 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);
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:";
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";