You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jetspeed-dev@portals.apache.org by ta...@apache.org on 2003/01/28 05:49:45 UTC
cvs commit: jakarta-jetspeed/src/java/org/apache/jetspeed/util Base64.java
taylor 2003/01/27 20:49:44
Modified: src/java/org/apache/jetspeed/om/security/ldap
BaseLDAPObject.java LDAPGroup.java
LDAPPermission.java LDAPRole.java LDAPUser.java
src/java/org/apache/jetspeed/services JetspeedLDAP.java
src/java/org/apache/jetspeed/services/ldap Connector.java
LDAPService.java LDAPURL.java
src/java/org/apache/jetspeed/services/security/ldap
LDAPAuthentication.java LDAPGroupManagement.java
LDAPPermissionManagement.java
LDAPRoleManagement.java LDAPUserManagement.java
UnixCrypt.java
src/java/org/apache/jetspeed/util Base64.java
Log:
LDAP patch from Sami Leino
-- unit tests all working
-- performance enhancements to getUser to fetch all users in one request
-- better propagation of exceptions from LDAP service to business layer
Revision Changes Path
1.4 +187 -21 jakarta-jetspeed/src/java/org/apache/jetspeed/om/security/ldap/BaseLDAPObject.java
Index: BaseLDAPObject.java
===================================================================
RCS file: /home/cvs/jakarta-jetspeed/src/java/org/apache/jetspeed/om/security/ldap/BaseLDAPObject.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- BaseLDAPObject.java 9 Dec 2002 20:24:08 -0000 1.3
+++ BaseLDAPObject.java 28 Jan 2003 04:49:43 -0000 1.4
@@ -54,31 +54,103 @@
package org.apache.jetspeed.om.security.ldap;
-import javax.naming.*;
-import javax.naming.directory.*;
-import java.util.Vector;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
+import java.util.TimeZone;
+import java.util.Vector;
+import javax.naming.Context;
+import javax.naming.Name;
+import javax.naming.NameNotFoundException;
+import javax.naming.NameParser;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.OperationNotSupportedException;
+import javax.naming.directory.Attribute;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.BasicAttribute;
+import javax.naming.directory.BasicAttributes;
+import javax.naming.directory.DirContext;
+import javax.naming.directory.ModificationItem;
+import javax.naming.directory.SearchControls;
import org.apache.jetspeed.services.ldap.LDAPURL;
+import org.apache.jetspeed.util.Base64;
+import org.apache.turbine.util.Log;
/**
* The Base LDAP Object extending DirContext.
*
* @author <a href="mailto:ender@kilicoglu.nom.tr">Ender Kilicoglu</a>
* @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
+ * @author <a href="mailto:sami.leino@netorek.fi">Sami Leino</a>
*
* @version $Id$
*/
public class BaseLDAPObject implements DirContext
{
- protected LDAPURL ldapurl;
- protected boolean updated = false;
- protected String name;
- protected String Id;
- protected Attributes myAttrs;
- protected boolean isNew = false;
- protected BasicAttributes rmAttrs = new BasicAttributes();
+ // Constants
+ protected final static String OK = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+ protected final static String LDAP_DATE_PATTERN = "yyyyMMddmmHHss'Z'";
+
+ // Instance variables
+ protected LDAPURL ldapurl = null;
+ protected boolean updated = false;
+ protected String name = null;
+ protected String Id = null;
+ protected Attributes myAttrs = null;
+ protected boolean isNew = false;
+ protected BasicAttributes rmAttrs = new BasicAttributes();
+
+ /**
+ * <p>Creates an "LDAP-safe" ID from a String so that
+ * the generated ID is as similar as possible to the
+ * original value. For example, value "Ryhm�" ("group"
+ * in Finnish language) would be converted to "ryhma".
+ * If the value contains an unknown character, it will
+ * be replaced by letter 'X'.</p>
+ */
+ public String createId(String value)
+ {
+ value = value.replace('�', 'a');
+ value = value.replace('�', 'a');
+ value = value.replace('�', 'o');
+ value = value.replace('�', 'A');
+ value = value.replace('�', 'A');
+ value = value.replace('�', 'O');
+ StringBuffer buf = new StringBuffer();
+
+ for (int i=0; i < value.length(); i++)
+ {
+ char currentChar = value.charAt(i);
+ if (isOK(currentChar)) buf.append(currentChar);
+ else buf.append('X');
+ }
+
+ return buf.toString();
+ }
+
+ /**
+ * <p>Checks if the specified character can be used
+ * in LDAP attribute name.</p>
+ */
+ public boolean isOK(char value)
+ {
+ for (int i=0; i < OK.length(); i++)
+ {
+ if (value == OK.charAt(i)) return true;
+ }
+
+ return false;
+ }
/**
* <p>Set's the objectClass for this object.</p>
@@ -105,6 +177,57 @@
myAttrs.put(oc);
}
+ protected String formatDate(Date date)
+ {
+ if (date == null)
+ {
+ date = new Date();
+ }
+
+ SimpleDateFormat formatter = new SimpleDateFormat(LDAP_DATE_PATTERN);
+ formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
+ return formatter.format(date);
+ }
+
+ protected Date parseDate(String value)
+ {
+ return parseDate(value, true);
+ }
+
+ protected Date parseDate(String value, boolean initializeIfNotSet)
+ {
+ try
+ {
+ SimpleDateFormat parser = new SimpleDateFormat(LDAP_DATE_PATTERN);
+ parser.setTimeZone(TimeZone.getTimeZone("GMT"));
+ return parser.parse(value);
+ }
+ catch (Exception e)
+ {
+ Log.warn("Could not parse date '" + value + "'");
+ if (initializeIfNotSet) return new Date();
+ else return null;
+ }
+ }
+
+ protected String serializePerm(Hashtable permStorage)
+ throws Exception
+ {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream os = new ObjectOutputStream(baos);
+ os.writeObject(permStorage);
+ return Base64.encodeAsString(baos.toByteArray());
+ }
+
+ protected Hashtable deserializePerm(String permStorageContentsEncoded)
+ throws Exception
+ {
+ byte[] decoded = Base64.decodeAsByteArray(permStorageContentsEncoded);
+ ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
+ ObjectInputStream is = new ObjectInputStream(bais);
+ return (Hashtable)is.readObject();
+ }
+
/**
* Updated Function
*
@@ -167,6 +290,7 @@
}
//UTIL Funcs
+
protected void removeutil(String field, boolean updatable)
{
myAttrs.remove(field);
@@ -179,17 +303,34 @@
protected void setutil(String field, String value)
{
myAttrs.remove(field);
+ if (value == null || value.length() == 0) value = " ";
myAttrs.put(field, value);
updated = true;
}
- protected void setutil(String field, Vector value)
+ protected void setutil(String field, Vector values)
+ {
+ setutil(field, values, false);
+ }
+
+ protected void setutil(String field, Vector values, boolean create)
{
myAttrs.remove(field);
- for(Enumeration enum = value.elements(); enum.hasMoreElements();)
+
+ if (values == null || (values.size() == 0 && create))
+ {
+ updated = true;
+ return;
+ }
+
+ Attribute attr = new BasicAttribute(field);
+ for(Enumeration enum = values.elements(); enum.hasMoreElements();)
{
- myAttrs.put(field, (String)enum.nextElement());
+ String nextValue = (String)enum.nextElement();
+ attr.add(nextValue);
}
+
+ myAttrs.put(attr);
updated = true;
}
@@ -202,7 +343,17 @@
protected String getutil(String field)
{
- if (myAttrs.get(field) == null)
+ return getutil(field, myAttrs);
+ }
+
+ protected Vector getutil(String field, boolean empty)
+ {
+ return getutil(field, myAttrs, empty);
+ }
+
+ protected String getutil(String field, Attributes attrs)
+ {
+ if (attrs.get(field) == null)
{
return new String("");
}
@@ -210,31 +361,45 @@
{
try
{
- return myAttrs.get(field).getAll().next().toString();
+ return attrs.get(field).getAll().next().toString();
}
catch (NamingException e)
{
- return new String("");
+ return new String("");
}
}
}
- protected Vector getutil(String field,boolean empty)
+ protected String fastgetutil(String field, Attributes attrs)
+ throws NamingException
+ {
+ Attribute values = attrs.get(field);
+ if (values == null) return new String("");
+
+ NamingEnumeration e = values.getAll();
+ if (e == null || !e.hasMore()) return new String("");
+
+ return e.next().toString();
+ }
+
+ protected Vector getutil(String field, Attributes attrs, boolean empty)
{
Vector values= null;
String temp;
+
if (empty)
{
values = new Vector();
}
- if (!(myAttrs.get(field) == null))
+ if (!(attrs.get(field) == null))
{
try
{
- for(NamingEnumeration enum = myAttrs.get(field).getAll(); enum.hasMore(); )
+ for(NamingEnumeration enum = attrs.get(field).getAll(); enum.hasMore(); )
{
- temp= (String)enum.nextElement();
+ temp = (String)enum.nextElement();
+
if (null != temp)
{
values.add(temp);
@@ -245,6 +410,7 @@
{
}
}
+
return values;
}
1.4 +18 -26 jakarta-jetspeed/src/java/org/apache/jetspeed/om/security/ldap/LDAPGroup.java
Index: LDAPGroup.java
===================================================================
RCS file: /home/cvs/jakarta-jetspeed/src/java/org/apache/jetspeed/om/security/ldap/LDAPGroup.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- LDAPGroup.java 9 Dec 2002 20:24:08 -0000 1.3
+++ LDAPGroup.java 28 Jan 2003 04:49:43 -0000 1.4
@@ -54,14 +54,13 @@
package org.apache.jetspeed.om.security.ldap;
-import java.util.Hashtable;
-import java.util.Vector;
import javax.naming.directory.Attribute;
-import javax.naming.directory.BasicAttribute;
+import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttributes;
import org.apache.jetspeed.om.security.Group;
import org.apache.jetspeed.services.JetspeedLDAP;
import org.apache.jetspeed.services.ldap.LDAPURL;
+import org.apache.jetspeed.services.security.GroupException;
/**
*
@@ -96,25 +95,22 @@
public LDAPGroup(String id)
{
- this.id = id;
- this.name = id;
+ this.setId(id);
isNew = true;
}
public LDAPGroup(String name, boolean isNew)
{
+ name = super.createId(name);
super.ldapurl = JetspeedLDAP.buildURL(ATTR_GROUP_ID + "=" + name + "," + ORGANIZATIONAL_UNIT);
this.isNew = isNew;
if (isNew)
{
- this.id = name;
- this.name = name;
-
+ this.setName(name);
super.myAttrs = new BasicAttributes();
- super.myAttrs.put(ATTR_GROUP_ID, name);
- super.myAttrs.put(ATTR_GROUP_NAME, name);
-
+ super.myAttrs.put(ATTR_GROUP_ID, this.getId());
+ super.myAttrs.put(ATTR_GROUP_NAME, this.getName());
super.setObjectClass(OBJECT_CLASS);
}
else
@@ -135,26 +131,21 @@
// --------------------- Persistence operations ----------------------
- public boolean update(boolean create)
+ public void update(boolean create)
+ throws GroupException
{
removeutil("createTimeStamp", false);
removeutil("modifyTimeStamp", false);
- if (JetspeedLDAP.exists(ldapurl))
- {
- JetspeedLDAP.deleteAttrs(super.ldapurl, super.rmAttrs);
- JetspeedLDAP.updateEntry(super.ldapurl, super.myAttrs);
- }
- else if (create)
+ if (create)
{
- JetspeedLDAP.addEntry(super.ldapurl, super.myAttrs);
+ if (JetspeedLDAP.addEntry(super.ldapurl, super.myAttrs) == false) throw new GroupException("Failed to insert group in LDAP!");
}
- else
+ else if (JetspeedLDAP.exists(super.ldapurl))
{
- return false;
+ JetspeedLDAP.deleteAttrs(super.ldapurl, super.rmAttrs);
+ if (JetspeedLDAP.updateEntry(super.ldapurl, super.myAttrs) == false) throw new GroupException("Failed to update group in LDAP!");
}
-
- return true;
}
// ------------------------ Accessor methods -------------------------
@@ -176,7 +167,8 @@
*/
public void setName(String groupName)
{
- name = groupName;
+ setId(groupName);
+ name = super.createId(groupName);
}
/**
@@ -198,7 +190,7 @@
{
if (this.id == null)
{
- this.id = id;
+ this.id = super.createId(id);
}
}
1.4 +21 -31 jakarta-jetspeed/src/java/org/apache/jetspeed/om/security/ldap/LDAPPermission.java
Index: LDAPPermission.java
===================================================================
RCS file: /home/cvs/jakarta-jetspeed/src/java/org/apache/jetspeed/om/security/ldap/LDAPPermission.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- LDAPPermission.java 9 Dec 2002 20:24:08 -0000 1.3
+++ LDAPPermission.java 28 Jan 2003 04:49:43 -0000 1.4
@@ -54,14 +54,11 @@
package org.apache.jetspeed.om.security.ldap;
+import javax.naming.directory.BasicAttributes;
+import org.apache.jetspeed.om.security.Permission;
import org.apache.jetspeed.services.JetspeedLDAP;
import org.apache.jetspeed.services.ldap.LDAPURL;
-import java.util.Vector;
-import javax.naming.*;
-import javax.naming.directory.*;
-import java.util.Hashtable;
-import java.util.Vector;
-import org.apache.jetspeed.om.security.Permission;
+import org.apache.jetspeed.services.security.PermissionException;
/**
*
@@ -96,32 +93,29 @@
public LDAPPermission(String id)
{
- this.id = id;
- this.name = id;
+ this.setId(id);
isNew = true;
}
public LDAPPermission(String name, boolean isNew)
{
+ name = super.createId(name);
super.ldapurl = JetspeedLDAP.buildURL(ATTR_PERMISSION_ID + "=" + name + "," + ORGANIZATIONAL_UNIT);
this.isNew = isNew;
if (isNew)
{
- this.id = name;
- this.name = name;
-
+ this.setName(name);
super.myAttrs = new BasicAttributes();
myAttrs.put(ATTR_PERMISSION_ID, id);
myAttrs.put(ATTR_PERMISSION_NAME, name);
-
super.setObjectClass(OBJECT_CLASS);
}
else
{
super.myAttrs = JetspeedLDAP.read(ldapurl);
- this.id = getutil(ATTR_PERMISSION_ID);
- this.name = getutil(ATTR_PERMISSION_NAME);
+ this.id = super.getutil(ATTR_PERMISSION_ID);
+ this.name = super.getutil(ATTR_PERMISSION_NAME);
}
}
@@ -129,32 +123,27 @@
{
super.ldapurl = ldapurl;
super.myAttrs = JetspeedLDAP.read(ldapurl);
- this.id = getutil(ATTR_PERMISSION_ID);
- this.name = getutil(ATTR_PERMISSION_NAME);
+ this.id = super.getutil(ATTR_PERMISSION_ID);
+ this.name = super.getutil(ATTR_PERMISSION_NAME);
}
// --------------------- Persistence operations ----------------------
- public boolean update(boolean create)
+ public void update(boolean create)
+ throws PermissionException
{
removeutil("createTimeStamp", false);
removeutil("modifyTimeStamp", false);
- if (JetspeedLDAP.exists(super.ldapurl))
+ if (create)
{
- JetspeedLDAP.deleteAttrs(super.ldapurl, super.rmAttrs);
- JetspeedLDAP.updateEntry(super.ldapurl, super.myAttrs);
+ if (JetspeedLDAP.addEntry(super.ldapurl, super.myAttrs) == false) throw new PermissionException("Could not insert permission in LDAP!");
}
- else if (create)
+ else if (JetspeedLDAP.exists(super.ldapurl))
{
- JetspeedLDAP.addEntry(ldapurl,myAttrs);
- }
- else
- {
- return false;
+ JetspeedLDAP.deleteAttrs(super.ldapurl, super.rmAttrs);
+ if (JetspeedLDAP.updateEntry(super.ldapurl, super.myAttrs) == false) throw new PermissionException("Could not update permission in LDAP!");
}
-
- return true;
}
// ------------------------ Accessor methods -------------------------
@@ -176,7 +165,8 @@
*/
public void setName(String permissionName)
{
- name = permissionName;
+ setId(permissionName);
+ name = super.createId(permissionName);
}
/**
@@ -198,7 +188,7 @@
{
if (this.id == null)
{
- this.id = id;
+ this.id = super.createId(id);
}
}
1.4 +23 -24 jakarta-jetspeed/src/java/org/apache/jetspeed/om/security/ldap/LDAPRole.java
Index: LDAPRole.java
===================================================================
RCS file: /home/cvs/jakarta-jetspeed/src/java/org/apache/jetspeed/om/security/ldap/LDAPRole.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- LDAPRole.java 9 Dec 2002 20:24:08 -0000 1.3
+++ LDAPRole.java 28 Jan 2003 04:49:43 -0000 1.4
@@ -62,6 +62,7 @@
import org.apache.jetspeed.om.security.Role;
import org.apache.jetspeed.services.JetspeedLDAP;
import org.apache.jetspeed.services.ldap.LDAPURL;
+import org.apache.jetspeed.services.security.RoleException;
/**
*
@@ -99,24 +100,22 @@
public LDAPRole(String id)
{
- rolePermissions = new Vector();
- this.id = id;
- this.name = id;
+ this.setId(id);
isNew = true;
+ rolePermissions = new Vector();
}
public LDAPRole(String name, boolean isNew)
{
+ name = super.createId(name);
super.ldapurl = JetspeedLDAP.buildURL(ATTR_ROLE_ID + "=" + name + "," + ORGANIZATIONAL_UNIT);
this.isNew = isNew;
if (isNew)
{
rolePermissions = new Vector();
- this.id = name;
- this.name = name;
-
+ this.setName(name);
super.myAttrs = new BasicAttributes();
super.myAttrs.put(ATTR_ROLE_ID, this.id);
super.myAttrs.put(ATTR_ROLE_NAME, this.name);
@@ -142,29 +141,28 @@
// --------------------- Persistence operations ----------------------
-
- public boolean update(boolean create)
+ public void update(boolean create)
+ throws RoleException
{
removeutil("createTimeStamp", false);
removeutil("modifyTimeStamp", false);
- if (JetspeedLDAP.exists(super.ldapurl))
- {
- removePreviousPermissionsFromLDAP();
- JetspeedLDAP.deleteAttrs(super.ldapurl, super.rmAttrs);
- super.myAttrs.put(toAttribute(ATTR_ROLE_PERMISSIONS, rolePermissions));
- JetspeedLDAP.updateEntry(super.ldapurl, super.myAttrs);
- }
- else if (create)
+ setutil(ATTR_ROLE_PERMISSIONS, rolePermissions, create);
+
+ if (create)
{
- JetspeedLDAP.addEntry(super.ldapurl, super.myAttrs);
+ if (JetspeedLDAP.addEntry(super.ldapurl, super.myAttrs) == false) throw new RoleException("Failed to insert role in LDAP!");
}
- else
+ else if (JetspeedLDAP.exists(super.ldapurl))
{
- return false;
+ JetspeedLDAP.deleteAttrs(super.ldapurl, super.rmAttrs);
+ // These two method calls shouldn't be needed anymore.
+ // If you face some problems with role permissions,
+ // you can remove the comments from below and try again.
+ // removePreviousPermissionsFromLDAP();
+ // super.myAttrs.put(toAttribute(ATTR_ROLE_PERMISSIONS, rolePermissions));
+ if (JetspeedLDAP.updateEntry(super.ldapurl, super.myAttrs) == false) throw new RoleException("Failed to update role in LDAP!");
}
-
- return true;
}
public void removePreviousPermissionsFromLDAP()
@@ -215,7 +213,8 @@
*/
public void setName(String roleName)
{
- name = roleName;
+ setId(roleName);
+ name = super.createId(roleName);
}
/**
@@ -237,7 +236,7 @@
{
if (this.id == null)
{
- this.id = id;
+ this.id = super.createId(id);
}
}
1.4 +130 -188 jakarta-jetspeed/src/java/org/apache/jetspeed/om/security/ldap/LDAPUser.java
Index: LDAPUser.java
===================================================================
RCS file: /home/cvs/jakarta-jetspeed/src/java/org/apache/jetspeed/om/security/ldap/LDAPUser.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- LDAPUser.java 9 Dec 2002 20:24:08 -0000 1.3
+++ LDAPUser.java 28 Jan 2003 04:49:43 -0000 1.4
@@ -54,28 +54,29 @@
package org.apache.jetspeed.om.security.ldap;
-import org.apache.jetspeed.services.JetspeedUserManagement;
-import org.apache.jetspeed.services.JetspeedAuthentication;
-import org.apache.jetspeed.om.security.JetspeedUser;
-import org.apache.turbine.om.security.User;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
-import java.text.SimpleDateFormat;
-import java.util.Vector;
-import java.util.Enumeration;
import java.util.Date;
+import java.util.Enumeration;
import java.util.Hashtable;
+import java.util.Vector;
+import javax.naming.directory.Attribute;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.BasicAttribute;
+import javax.naming.directory.BasicAttributes;
import javax.servlet.http.HttpSessionBindingEvent;
-import org.apache.turbine.util.Log;
-import org.apache.turbine.util.ObjectUtils;
-import org.apache.jetspeed.services.resources.JetspeedResources;
+import javax.servlet.http.HttpSessionBindingListener;
+import org.apache.jetspeed.om.security.JetspeedUser;
+import org.apache.jetspeed.services.JetspeedAuthentication;
import org.apache.jetspeed.services.JetspeedLDAP;
-import org.apache.jetspeed.services.security.ldap.UnixCrypt;
+import org.apache.jetspeed.services.JetspeedUserManagement;
import org.apache.jetspeed.services.ldap.LDAPURL;
-import org.apache.jetspeed.util.Base64;
-import javax.naming.*;
-import javax.naming.directory.*;
-import java.io.*;
+import org.apache.jetspeed.services.resources.JetspeedResources;
+import org.apache.jetspeed.services.security.JetspeedSecurityException;
+import org.apache.jetspeed.services.security.UserException;
+import org.apache.turbine.om.security.User;
+import org.apache.turbine.util.Log;
+import org.apache.turbine.util.ObjectUtils;
/**
*
@@ -85,18 +86,28 @@
* @version $Id$
*
*/
-public class LDAPUser extends BaseLDAPObject implements JetspeedUser {
+public class LDAPUser extends BaseLDAPObject implements JetspeedUser, HttpSessionBindingListener {
// ---------------------------- Constants ----------------------------
- protected static final String OBJECT_CLASS = "jetspeedpermission";
- protected static final String ORGANIZATIONAL_UNIT = "ou=permissions";
+ protected static final String OBJECT_CLASS = "jetspeeduser";
+ protected static final String ORGANIZATIONAL_UNIT = "ou=users";
- protected static final String ATTR_USER_ID = "uid";
- protected static final String ATTR_OBJECT_DATA = "objectdata";
-
- protected static final boolean SAVE_EXTRA_ATTRIBUTES = false;
- protected static final String LDAP_DATE_PATTERN = "yyyy.MM.dd G 'at' hh:mm:ss a zzz";
+ protected static final String ATTR_UID = "uid";
+ protected static final String ATTR_UID_NUMBER = "uidNumber";
+ protected static final String ATTR_USER_PASSWORD = "userPassword";
+ protected static final String ATTR_NAME = "name";
+ protected static final String ATTR_GIVEN_NAME = "givenName";
+ protected static final String ATTR_SN = "sn";
+ protected static final String ATTR_MAIL = "mail";
+ protected static final String ATTR_OBJECT_DATA = "objectdata";
+ protected static final String ATTR_OBJECT_CLASS = "objectClass";
+ protected static final String ATTR_USER_GROUP_ROLE = "usergrouprole";
+ protected static final String ATTR_LAST_LOGIN_DATE = "lastlogindate";
+ protected static final String ATTR_LAST_MODIFIED_DATE = "lastmodifieddate";
+ protected static final String ATTR_CREATION_DATE = "creationdate";
+ protected static final String ATTR_CONFIRMED = "confirm";
+ protected static final String ATTR_DISABLED = "disabled";
// ------------------------- Member variables ------------------------
@@ -115,11 +126,14 @@
/** This is data that will not survive a servlet engine restart. */
private Hashtable tempStorage = null;
+ /** Name of the user */
protected String name = "";
+ /** Is this object "new" or does it already exist in the datastore? */
protected boolean isNew = false;
- private Vector groupRoles = null;
+ /** User's roles. */
+ protected Vector groupRoles = null;
// --------------------------- Constructors --------------------------
@@ -134,13 +148,13 @@
*/
public LDAPUser(String username, boolean isNew)
{
- ldapurl = JetspeedLDAP.buildURL("uid=" + username + ",ou=users");
+ super.ldapurl = JetspeedLDAP.buildURL(ATTR_UID + "=" + username + "," + ORGANIZATIONAL_UNIT);
this.isNew = isNew;
createDate = new Date();
lastAccessDate = createDate;
- tempStorage = new Hashtable(10);
- permStorage = new Hashtable(10);
+ tempStorage = new Hashtable(20);
+ permStorage = new Hashtable(50);
groupRoles = new Vector();
setHasLoggedIn(Boolean.FALSE);
@@ -148,196 +162,118 @@
{
setDisabled(false);
setUserName(username);
+ String uidNumber = new Long(System.currentTimeMillis()).toString();
+ setUserId(uidNumber);
myAttrs = new BasicAttributes();
- myAttrs.put("uid", username);
- Attribute oc = new BasicAttribute("objectclass");
+ myAttrs.put(ATTR_UID, username);
+ myAttrs.put(ATTR_UID_NUMBER, uidNumber);
+ Attribute oc = new BasicAttribute(ATTR_OBJECT_CLASS);
oc.add("jetspeeduser");
myAttrs.put(oc);
}
else
{
- myAttrs = JetspeedLDAP.read(ldapurl);
- setName(getutil("name"));
- setEmail(getutil("mail"));
- setFirstName(getutil("givenName"));
- setLastName(getutil("sn"));
- setUserName(username);
- this.groupRoles = getutil("usergrouprole", true);
-
- setLastLogin(parseDate(getutil("lastlogindate")));
- lastAccessDate = parseDate(getutil("lastmodifieddate"));
- setCreateDate(parseDate(getutil("creationdate")));
- String temp = getutil("disabled");
- if (temp != null && temp.equals("TRUE")) setDisabled(true);
- else setDisabled(false);
-
- try
- {
- setPermStorage(deserializePerm(getutil(ATTR_OBJECT_DATA)));
- }
- catch (Exception e)
- {
- }
+ myAttrs = JetspeedLDAP.read(ldapurl);
+ fillObject(myAttrs);
}
}
- public LDAPUser( LDAPURL ldapurl )
+ public LDAPUser(LDAPURL ldapurl)
{
- createDate = new Date();
- tempStorage = new Hashtable(10);
- permStorage = new Hashtable(10);
+ fillObject(JetspeedLDAP.read(ldapurl));
+ }
+
+ public LDAPUser(Attributes attributes)
+ {
+ fillObject(attributes);
+ }
+
+ private void fillObject(Attributes attributes)
+ {
+ tempStorage = new Hashtable(20);
+ permStorage = new Hashtable(50);
setHasLoggedIn(Boolean.FALSE);
- groupRoles = new Vector();
- this.ldapurl = ldapurl;
- myAttrs = JetspeedLDAP.read(ldapurl);
+
+ myAttrs = attributes;
try
{
- setPermStorage(deserializePerm(getutil(ATTR_OBJECT_DATA)));
+ setPermStorage(deserializePerm(getutil(ATTR_OBJECT_DATA, attributes)));
}
catch (Exception e)
{
}
-
- setUserName(getutil("uid"));
- setEmail(getutil("mail"));
- setFirstName(getutil("givenName"));
- setLastName(getutil("sn"));
- setName(getutil("name"));
- setConfirmed(getutil("confirm"));
-
- setLastLogin(parseDate(getutil("lastlogindate")));
- lastAccessDate = parseDate(getutil("lastmodifieddate"));
- setCreateDate(parseDate(getutil("creationdate")));
- String temp = getutil("disabled");
- if (temp != null && temp.equals("TRUE")) setDisabled(true);
- else setDisabled(false);
+
+ setUserName(getutil(ATTR_UID, attributes));
+ setUserId(getutil(ATTR_UID_NUMBER, attributes));
+ setEmail(getutil(ATTR_MAIL, attributes));
+ setFirstName(getutil(ATTR_GIVEN_NAME, attributes));
+ setLastName(getutil(ATTR_SN, attributes));
+ // setName(getutil(ATTR_NAME, attributes));
+ setConfirmed(getutil(ATTR_CONFIRMED, attributes));
+
+ setLastLogin(parseDate(getutil(ATTR_LAST_LOGIN_DATE, attributes)));
+ lastAccessDate = parseDate(getutil(ATTR_LAST_MODIFIED_DATE, attributes));
+ setCreateDate(parseDate(getutil(ATTR_CREATION_DATE, attributes)));
+ String temp = getutil(ATTR_DISABLED, attributes);
+ if (temp != null && temp.equals("TRUE")) setDisabled(true);
+ else setDisabled(false);
try
{
- setPassword(new String ((byte[]) myAttrs.get("userPassword").getAll().nextElement()));
+ setPassword(new String ((byte[]) attributes.get(ATTR_USER_PASSWORD).getAll().nextElement()));
}
catch (Exception e)
{
}
- this.groupRoles = getutil( "usergrouprole", true );
- }
+ this.groupRoles = getutil( ATTR_USER_GROUP_ROLE, attributes, true );
+ ldapurl = JetspeedLDAP.buildURL(ATTR_UID + "=" + getUserName() + "," + ORGANIZATIONAL_UNIT);
+ }
// --------------------- Persistence operations ----------------------
- public boolean update(boolean create)
+ public void update(boolean create)
+ throws JetspeedSecurityException
{
removeutil("createTimeStamp", false);
removeutil("modifyTimeStamp", false);
- setutil("userPassword",(String)getPerm(User.PASSWORD) );
- setutil("mail",(String)getPerm(User.EMAIL));
- setutil("confirm",(String)getPerm(User.CONFIRM_VALUE));
- setutil("sn",(String)getPerm(User.LAST_NAME));
- setutil("givenName",(String)getPerm(User.FIRST_NAME));
-
- setutil("usergrouprole", groupRoles);
+ setutil(ATTR_USER_PASSWORD,(String)getPerm(User.PASSWORD) );
+ setutil(ATTR_MAIL,(String)getPerm(User.EMAIL));
+ setutil(ATTR_CONFIRMED,(String)getPerm(User.CONFIRM_VALUE));
+ setutil(ATTR_SN,(String)getPerm(User.LAST_NAME));
+ setutil(ATTR_GIVEN_NAME,(String)getPerm(User.FIRST_NAME));
+ setutil(ATTR_USER_GROUP_ROLE, this.getGroupRoles(), create);
+ // setutilMulti(ATTR_USER_GROUP_ROLE, groupRoles);
+ setutil(ATTR_LAST_LOGIN_DATE, formatDate(getLastLogin()));
+ setutil(ATTR_LAST_MODIFIED_DATE, formatDate(getLastAccessDate()));
+ setutil(ATTR_CREATION_DATE, formatDate(getCreateDate()));
+ if (getDisabled() == true) setutil(ATTR_DISABLED, "TRUE");
+ else setutil(ATTR_DISABLED, "FALSE");
- if (SAVE_EXTRA_ATTRIBUTES)
+ try
+ {
+ setutil(ATTR_OBJECT_DATA, serializePerm(permStorage));
+ }
+ catch (Exception e)
{
- try
- {
- setutil("lastlogindate", formatDate(getLastLogin()));
- setutil("lastmodifieddate", formatDate(getLastAccessDate()));
- setutil("creationdate", formatDate(getCreateDate()));
- if (getDisabled() == true) setutil("disabled", "TRUE");
- else setutil("disabled", "FALSE");
- setutil(ATTR_OBJECT_DATA, serializePerm(permStorage));
- }
- catch (Exception e)
- {
- Log.warn("Setting extra user attributes failed!", e);
- }
+ Log.warn("Could not serialize object data!" , e);
}
-
- if (JetspeedLDAP.exists(ldapurl))
- {
- JetspeedLDAP.deleteAttrs(ldapurl, rmAttrs);
- JetspeedLDAP.updateEntry(ldapurl, myAttrs);
- }
- else if (create)
+
+ if (create)
{
ldapurl = JetspeedLDAP.buildURL("uid=" + (String)getPerm(User.USERNAME) + ",ou=users");
- setutil("uid", (String)getPerm(User.USERNAME));
- JetspeedLDAP.addEntry(ldapurl,myAttrs);
- }
- else
- {
- return false;
- }
-
- return true;
- }
-
- // ----------------------- Utility operations ------------------------
-
- protected String formatDate(Date date)
- {
- if (date == null)
- {
- date = new Date();
- }
-
- SimpleDateFormat formatter = new SimpleDateFormat(LDAP_DATE_PATTERN);
- return formatter.format(date);
- }
-
- protected Date parseDate(String value)
- {
- try
- {
- SimpleDateFormat parser = new SimpleDateFormat(LDAP_DATE_PATTERN);
- return parser.parse(value);
+ setutil(ATTR_UID, (String)getPerm(User.USERNAME));
+ if (JetspeedLDAP.addEntry(ldapurl, myAttrs) == false) throw new UserException("Could not insert user data to LDAP!");
}
- catch (Exception e)
+ else if (JetspeedLDAP.exists(ldapurl))
{
- return new Date();
+ JetspeedLDAP.deleteAttrs(ldapurl, rmAttrs);
+ if (JetspeedLDAP.updateEntry(ldapurl, myAttrs) == false) throw new UserException("Could not update user data to LDAP!");
}
}
- /*
- protected byte[] serializePerm(Hashtable permStorage)
- throws Exception
- {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStream os = new ObjectOutputStream(baos);
- os.writeObject(permStorage);
- return baos.toByteArray();
- }
-
- protected Hashtable deserializePerm(byte[] permStorageContentsEncoded)
- throws Exception
- {
- ByteArrayInputStream bais = new ByteArrayInputStream(permStorageContentsEncoded);
- ObjectInputStream is = new ObjectInputStream(bais);
- return (Hashtable)is.readObject();
- }
- */
-
- protected String serializePerm(Hashtable permStorage)
- throws Exception
- {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStream os = new ObjectOutputStream(baos);
- os.writeObject(permStorage);
- return Base64.encodeAsString(baos.toByteArray());
- }
-
- protected Hashtable deserializePerm(String permStorageContentsEncoded)
- throws Exception
- {
- byte[] decoded = Base64.decodeAsByteArray(permStorageContentsEncoded);
- ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
- ObjectInputStream is = new ObjectInputStream(bais);
- return (Hashtable)is.readObject();
- }
-
// ------------------------ Accessor methods -------------------------
public Vector getGroupRoles()
@@ -359,10 +295,10 @@
{
groupRoles.remove(groupRoleStr);
}
- }
- }
-
- public void removeGroupRoles(String groupName, String roleName)
+ }
+ }
+
+ public void removeGroupRole(String groupName, String roleName)
{
for (Enumeration enum = groupRoles.elements(); enum.hasMoreElements();)
{
@@ -377,6 +313,7 @@
/**
* Returns the primary principle for this User, the user id.
*
+
* @return the user id.
*/
public String getUserId()
@@ -404,6 +341,7 @@
setPerm(JetspeedUser.USER_ID, id);
}
}
+
/**
* Gets the access counter for a user during a session.
*
@@ -529,7 +467,7 @@
{
if (this.permStorage == null)
{
- this.permStorage = new Hashtable();
+ this.permStorage = new Hashtable(50);
}
return this.permStorage;
}
@@ -592,6 +530,7 @@
catch (Exception e)
{
}
+
return tmp;
}
@@ -604,6 +543,7 @@
public String getFirstName()
{
String tmp = null;
+
try
{
tmp = (String) getPerm (User.FIRST_NAME);
@@ -627,16 +567,16 @@
public String getLastName()
{
String tmp = null;
+
try
{
tmp = (String) getPerm (User.LAST_NAME);
if (tmp.length() == 0) tmp = null;
}
catch (Exception e)
-
-
{
}
+
return tmp;
}
@@ -648,6 +588,7 @@
*/
public boolean hasLoggedIn()
{
+
Boolean loggedIn = getHasLoggedIn();
return (loggedIn != null && loggedIn.booleanValue());
}
@@ -786,7 +727,7 @@
{
if (this.tempStorage == null)
{
- this.tempStorage = new Hashtable();
+ this.tempStorage = new Hashtable(20);
}
return this.tempStorage;
}
@@ -807,7 +748,7 @@
* returns this value as a boolean. This is private because you
* should use hasLoggedIn() instead.
*
- * @return True if someone has logged in.
+ * @return True if someone has logged in.
*/
private Boolean getHasLoggedIn()
{
@@ -938,7 +879,6 @@
*/
public void valueBound(HttpSessionBindingEvent hsbe)
{
- // Currently we have no need for this method.
}
/**
@@ -949,23 +889,23 @@
*/
public void valueUnbound(HttpSessionBindingEvent hsbe)
{
- try
+ try
{
java.util.Date now = new java.util.Date();
-
if (this.hasLoggedIn())
{
if ( JetspeedResources.getBoolean("automatic.logout.save", false) )
{
JetspeedUserManagement.saveUser(this);
}
+
JetspeedAuthentication.logout();
}
}
catch ( Exception e )
{
- Log.error("TurbineUser.valueUnbound(): " + e.getMessage(), e);
+ Log.error("LDAPUser.valueUnbound(): " + e.getMessage(), e);
// To prevent messages being lost in case the logging system
// goes away before sessions get unbound on servlet container
@@ -1001,6 +941,7 @@
public boolean getDisabled()
{
boolean disabled = false;
+
try
{
String tmp = (String) getPerm (JetspeedUser.DISABLED);
@@ -1013,6 +954,7 @@
catch (Exception e)
{
}
+
return disabled;
}
1.3 +23 -6 jakarta-jetspeed/src/java/org/apache/jetspeed/services/JetspeedLDAP.java
Index: JetspeedLDAP.java
===================================================================
RCS file: /home/cvs/jakarta-jetspeed/src/java/org/apache/jetspeed/services/JetspeedLDAP.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- JetspeedLDAP.java 9 Dec 2002 20:24:08 -0000 1.2
+++ JetspeedLDAP.java 28 Jan 2003 04:49:43 -0000 1.3
@@ -54,23 +54,27 @@
package org.apache.jetspeed.services;
+import java.util.Vector;
+import javax.naming.NamingEnumeration;
+import javax.naming.directory.Attribute;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.DirContext;
import org.apache.jetspeed.services.ldap.LDAPService;
import org.apache.jetspeed.services.ldap.LDAPURL;
+import org.apache.turbine.services.Service;
import org.apache.turbine.services.TurbineServices;
-import javax.naming.*;
-import javax.naming.directory.*;
-import java.util.Vector;
-
/**
*
* @author <a href="mailto:ender@kilicoglu.nom.tr">Ender KILICOGLU</a>
+ * @author <a href="mailto:sami.leino@netorek.fi">Sami Leino</a>
+ *
* @version $Id$
*
*/
public class JetspeedLDAP
{
- private static LDAPService getService()
+ public static LDAPService getService()
{
return(LDAPService)TurbineServices
.getInstance()
@@ -136,6 +140,19 @@
public static boolean renameEntry(LDAPURL url, String newDN)
{
return getService().renameEntry(url, newDN);
+ }
+
+ public static NamingEnumeration search(DirContext ctx, String dn, String filter, String attribs[], int type)
+ {
+ try
+ {
+ return getService().search(ctx, dn, filter, attribs, type);
+ }
+ catch (Exception e)
+ {
+ e.printStackTrace();
+ return null;
+ }
}
public static Vector search(LDAPURL url, String filter, String attribs[], boolean subTreeScope)
1.3 +0 -0 jakarta-jetspeed/src/java/org/apache/jetspeed/services/ldap/Connector.java
Index: Connector.java
===================================================================
RCS file: /home/cvs/jakarta-jetspeed/src/java/org/apache/jetspeed/services/ldap/Connector.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
1.4 +246 -100 jakarta-jetspeed/src/java/org/apache/jetspeed/services/ldap/LDAPService.java
Index: LDAPService.java
===================================================================
RCS file: /home/cvs/jakarta-jetspeed/src/java/org/apache/jetspeed/services/ldap/LDAPService.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- LDAPService.java 9 Dec 2002 20:24:08 -0000 1.3
+++ LDAPService.java 28 Jan 2003 04:49:43 -0000 1.4
@@ -1,4 +1,4 @@
-/* ====================================================================
+/* ================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2001 The Apache Software Foundation. All rights
@@ -54,20 +54,39 @@
package org.apache.jetspeed.services.ldap;
-import org.apache.turbine.services.TurbineServices;
-import org.apache.turbine.services.TurbineBaseService;
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.Properties;
+import java.util.StringTokenizer;
+import java.util.Vector;
+import javax.naming.AuthenticationException;
+import javax.naming.CommunicationException;
+import javax.naming.Context;
+import javax.naming.Name;
+import javax.naming.NameNotFoundException;
+import javax.naming.NameParser;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.ReferralException;
+import javax.naming.directory.Attribute;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.DirContext;
+import javax.naming.directory.InitialDirContext;
+import javax.naming.directory.ModificationItem;
+import javax.naming.directory.SearchControls;
+import javax.naming.directory.SearchResult;
+import javax.servlet.ServletConfig;
import org.apache.turbine.services.InitializationException;
+import org.apache.turbine.services.TurbineBaseService;
+import org.apache.turbine.services.TurbineServices;
import org.apache.turbine.services.resources.ResourceService;
import org.apache.turbine.util.Log;
-import javax.servlet.ServletConfig;
-import org.apache.turbine.services.servlet.TurbineServlet;
-import java.util.*;
-import javax.naming.*;
-import javax.naming.directory.*;
/**
*
* @author <a href="mailto:ender@kilicoglu.nom.tr">Ender KILICOGLU</a>
+ * @author <a href="mailto:sami.leino@netorek.fi">Sami Leino</a>
+ *
* @version $Id$
*
*/
@@ -89,13 +108,6 @@
private Hashtable connections;
private Connector connector;
-
-
-
-
-
-
-
private int limit;
private int timeout;
private int version;
@@ -117,7 +129,9 @@
private String attributesList[];
private NameParser parser;
private boolean showOpAttributes;
+ private boolean useCachedDirContexts;
private Properties env;
+
/**
* Main Connection Function
*
@@ -134,9 +148,11 @@
try
{
DirContext ctx = new InitialDirContext(env);
- // connections.put(basedn, ctx);
- if(parser == null)
- parser = ctx.getNameParser("");
+ if (useCachedDirContexts)
+ {
+ connections.put(basedn, ctx);
+ }
+ if(parser == null) parser = ctx.getNameParser("");
return true;
}
catch(NamingException e)
@@ -145,6 +161,7 @@
}
return false;
}
+
/**
* Connection Function
*
@@ -155,11 +172,21 @@
*/
public DirContext connect(LDAPURL url)
{
+
String base = url.getBase();
DirContext ctx = (DirContext)connections.get(base);
if(ctx != null)
- return ctx;
-
+ {
+ // System.out.println("LDAPService: returning cached context.");
+ // System.out.println("LDAPService: DN is " + url.getDN());
+ return ctx;
+ }
+ else
+ {
+ // System.out.println("LDAPService: creating new context for base " + base);
+ // System.out.println("LDAPService: DN is " + url.getDN());
+ }
+
setDefaultEnv();
env.put("java.naming.provider.url", base);
do
@@ -167,7 +194,7 @@
try
{
ctx = new InitialDirContext(env);
- // connections.put(base, ctx);
+ if (useCachedDirContexts) connections.put(base, ctx);
return ctx;
}
catch(AuthenticationException e)
@@ -200,6 +227,7 @@
return ctx;
} while(true);
}
+
/**
* Reset Given Connection Function
*
@@ -210,6 +238,7 @@
*/
private void resetConnection(LDAPURL url)
{
+ // System.out.println("LDAPService: resetConnection() called.");
connections.remove(url.getBase());
}
/**
@@ -223,37 +252,51 @@
showOpAttributes = attributesList != null;
env.put("java.naming.referral", "ignore");
env.put("java.naming.batchsize", String.valueOf(batchsize));
+
if(anonymousBind)
{
env.remove("java.naming.security.principal");
env.remove("java.naming.security.credentials");
- } else
+ }
+ else
{
env.put("java.naming.security.principal", managerdn);
env.put("java.naming.security.credentials", password);
}
+
env.put("java.naming.security.authentication", securityAuthentication);
if(saslclientpckgs != null)
- env.put("javax.security.sasl.client.pkgs", saslclientpckgs);
- else
+ {
+ env.put("javax.security.sasl.client.pkgs", saslclientpckgs);
+ }
+ else
+ {
env.remove("javax.security.sasl.client.pkgs");
+ }
+
env.put("java.naming.ldap.derefAliases", "never");
env.put("java.naming.ldap.deleteRDN", "true" );
env.put("java.naming.ldap.version", String.valueOf(version));
+
if( securityProtocol != null)
{
env.put("java.naming.security.protocol", securityProtocol);
if(securityProtocol.equalsIgnoreCase("ssl"))
+ {
env.put("java.naming.ldap.factory.socket", socketFactory );
- } else
+ }
+ }
+ else
{
env.remove("java.naming.security.protocol");
env.remove("java.naming.ldap.factory.socket");
}
-// env.put("com.sun.jndi.ldap.trace.ber", System.err);
+
+ // env.put("com.sun.jndi.ldap.trace.ber", System.err);
env.put("java.naming.factory.initial", (Object)(jndiprovider));
}
- /**
+
+ /**
* Disconnection Function
*
* tries to disconnect all connection.
@@ -263,9 +306,12 @@
public boolean disconnect()
{
+ // System.out.println("LDAPService: disconnect() called.");
DirContext ctx = null;
+
for(Enumeration enum = connections.elements(); enum.hasMoreElements();)
- try
+ {
+ try
{
ctx = (DirContext)enum.nextElement();
ctx.close();
@@ -274,11 +320,35 @@
{
Log.error("LDAP Service: Disconnect failed", e);
}
-
+ }
+
connections.clear();
return true;
}
+ public boolean checkAndCloseContext(Context context)
+ {
+ try
+ {
+ if (!useCachedDirContexts)
+ {
+ context.close();
+ // System.out.println("LDAPService: closeContext() called.");
+ }
+ else
+ {
+ // System.out.println("LDAPService: context left in cache.");
+ }
+ return true;
+ }
+ catch(NamingException e)
+ {
+ Log.error("LDAP Service: closeContext() failed", e);
+ return false;
+ }
+ }
+
+
/**
* Delete Atrribute Function
*
@@ -303,7 +373,8 @@
}
return false;
}
- /**
+
+ /**
* Add Attribute Function
*
* add given attribute to given <code>LDAPURL</code>.
@@ -326,6 +397,7 @@
}
return false;
}
+
/**
* Add entry Function
*
@@ -339,11 +411,13 @@
public boolean addEntry(LDAPURL url, Attributes at)
{
DirContext ctx = connect(url);
+
if(ctx == null)
return false;
try
{
ctx.createSubcontext(url.getDN(), at);
+ checkAndCloseContext(ctx);
}
catch(ReferralException e)
{
@@ -352,11 +426,15 @@
}
catch(NamingException e)
{
- Log.debug ("LDAP Service: Failed to add new entry " + url.getDN(), e);
+
+e.printStackTrace();
+
+ Log.error("LDAP Service: Failed to add new entry " + url.getDN(), e);
return false;
}
return true;
}
+
/**
* Query existense of an Object Function
*
@@ -368,11 +446,12 @@
public boolean exists(LDAPURL url)
{
DirContext ctx = connect(url);
- if(ctx == null)
- return false;
+ if(ctx == null) return false;
+
try
{
NamingEnumeration results = search(ctx, url.getDN(), "(objectclass=*)", DEFAULT_ATTR, 0, false);
+ checkAndCloseContext(ctx);
return true;
}
catch(NameNotFoundException _ex)
@@ -384,6 +463,7 @@
return false;
}
}
+
/**
* Compare Function
*
@@ -406,6 +486,7 @@
Name prefix = src.getPrefix(src.size() - 1);
return dst.compareTo(prefix) != 0 ? 0 : 3;
}
+
/**
* Import Function
*
@@ -424,6 +505,7 @@
if(type == 0)
rs = addEntry(myurl, entry);
else
+
if(type == 1)
rs = updateEntry(myurl, entry);
else
@@ -433,6 +515,7 @@
return 0;
return !rs ? -1 : 1;
}
+
/**
* Modify Function
*
@@ -447,11 +530,12 @@
throws NamingException
{
DirContext ctx = connect(url);
- if(ctx == null)
- return false;
+ if(ctx == null) return false;
+
try
{
ctx.modifyAttributes(url.getDN(), mods);
+ checkAndCloseContext(ctx);
}
catch(ReferralException e)
{
@@ -485,21 +569,28 @@
public Attributes read(LDAPURL url)
{
DirContext ctx = connect(url);
- if(ctx == null)
- return null;
+ if(ctx == null) return null;
+
Attributes attrs = null;
try
{
if(showOpAttributes)
+ {
attrs = ctx.getAttributes(url.getDN(), attributesList);
+ }
else
+ {
attrs = ctx.getAttributes(url.getDN());
+ }
+ checkAndCloseContext(ctx);
}
catch(ReferralException e)
{
LDAPURL myurl = getReferralUrl(e);
if(myurl.getDN().length() == 0)
+ {
myurl.setDN(url.getDN());
+ }
return read(myurl);
}
catch(CommunicationException e)
@@ -510,7 +601,9 @@
return null;
}
if(connector.connectionFailed(url))
+ {
resetConnection(url);
+ }
}
catch(NamingException e)
{
@@ -519,6 +612,7 @@
}
return attrs;
}
+
/**
* Rename Entry Function
*
@@ -531,11 +625,12 @@
public boolean renameEntry(LDAPURL url, String newDN)
{
DirContext ctx = connect(url);
- if(ctx == null)
- return false;
+ if(ctx == null) return false;
+
try
{
ctx.rename(url.getDN(), newDN);
+ checkAndCloseContext(ctx);
}
catch(ReferralException e)
{
@@ -549,6 +644,7 @@
}
return true;
}
+
/**
* Sync Entry Function
*
@@ -561,11 +657,12 @@
public boolean synchEntry(LDAPURL url, Attributes ats)
{
DirContext ctx = connect(url);
- if(ctx == null)
- return false;
+ if(ctx == null) return false;
+
try
{
ctx.modifyAttributes(url.getDN(), 2, ats);
+ checkAndCloseContext(ctx);
}
catch(ReferralException e)
{
@@ -590,6 +687,7 @@
}
return true;
}
+
/**
* Delete Attributes Function
*
@@ -602,11 +700,12 @@
public boolean deleteAttrs(LDAPURL url, Attributes ats)
{
DirContext ctx = connect(url);
- if(ctx == null)
- return false;
+ if(ctx == null) return false;
+
try
{
ctx.modifyAttributes(url.getDN(), DirContext.REMOVE_ATTRIBUTE, ats);
+ checkAndCloseContext(ctx);
}
catch(ReferralException e)
{
@@ -618,6 +717,7 @@
try
{
ctx.createSubcontext(url.getDN(), ats);
+ checkAndCloseContext(ctx);
}
catch(NamingException _ex2)
{
@@ -631,6 +731,7 @@
}
return true;
}
+
/**
* Delete Entry Function
*
@@ -638,16 +739,16 @@
*
* @param url object to delete.
* @return boolean true if success else false.
-
*/
public boolean deleteEntry(LDAPURL url)
{
DirContext ctx = connect(url);
- if(ctx == null)
- return false;
+ if(ctx == null) return false;
+
try
{
ctx.destroySubcontext(url.getDN());
+ checkAndCloseContext(ctx);
}
catch(ReferralException e)
{
@@ -661,6 +762,7 @@
}
return true;
}
+
/**
* Find Entry Name Function
*
@@ -672,19 +774,20 @@
public LDAPURL findEntryName(LDAPURL url)
{
DirContext ctx = connect(url);
- if(ctx == null)
- return null;
+ if(ctx == null) return null;
+
Name name = parse(url.getDN());
String base = name.getPrefix(name.size() - 1).toString();
String dn = url.getDN();
String rdn = name.get(name.size() - 1).toString();
int i = 1;
boolean foundName = true;
+
while(foundName)
+ {
try
{
NamingEnumeration results = search(ctx, dn, "(objectclass=*)", DEFAULT_ATTR, 0, false);
- results.close();
if(i == 1)
rdn = rdn + " copy";
else
@@ -705,8 +808,13 @@
{
return null;
}
+ }
+
+ checkAndCloseContext(ctx);
+
return null;
}
+
/**
* Delete Tree Function
*
@@ -718,11 +826,12 @@
public boolean deleteTree(LDAPURL url)
{
DirContext ctx = connect(url);
- if(ctx == null)
- return false;
+ if(ctx == null) return false;
+
String entryDN = null;
LDAPURL myurl = null;
String baseDN = url.getDN();
+
try
{
for(NamingEnumeration results = search(ctx, baseDN, "(objectclass=*)", DEFAULT_ATTR, 1, false); results.hasMore();)
@@ -732,11 +841,11 @@
myurl = new LDAPURL(url.getHost(), url.getPort(), entryDN);
if(!deleteTree(myurl))
{
- results.close();
return false;
}
}
+ checkAndCloseContext(ctx);
}
catch(NamingException e)
{
@@ -745,6 +854,7 @@
}
return deleteEntry(url);
}
+
/**
* Transfer Function
*
@@ -757,7 +867,6 @@
* @param withChildren transfer with childs.
* @return boolean true if success else false.
*/
-
public boolean transfer(LDAPURL fromUrl, LDAPURL toUrl, boolean delete, boolean replace, boolean withChildren)
{
LDAPURL dstUrl = toUrl;
@@ -770,6 +879,7 @@
return transferEntry(fromUrl, dstUrl, delete, replace);
}
+
/**
* Transfer with updates Function
*
@@ -793,6 +903,7 @@
addEntry(fromUrl, ats);
return false;
}
+
/**
* Transfer without updates Function
*
@@ -813,6 +924,7 @@
else
return transferEntry(fromUrl, ats, toUrl, delete, replace);
}
+
/**
* Transfer Tree Function
*
@@ -824,22 +936,22 @@
* @param replace replace if exist.
* @return boolean true if success else false.
*/
-
private boolean transferTreeSub(LDAPURL fromUrl, LDAPURL toUrl, boolean delete, boolean replace)
{
DirContext ctx = connect(fromUrl);
- if(ctx == null)
- return false;
+ if(ctx == null) return false;
Attributes ats = read(fromUrl);
- if(ats == null)
- return false;
+ if(ats == null) return false;
+
String srcDN = fromUrl.getDN();
String dstDN = toUrl.getDN();
boolean createdBase = false;
boolean rc = false;
boolean moreReferrals = true;
+
while(moreReferrals)
+ {
try
{
NamingEnumeration results = search(ctx, srcDN, "(objectclass=*)", DEFAULT_ATTR, 1, false);
@@ -878,23 +990,26 @@
if(delete)
{
moreReferrals = false;
- } else
+ }
+ else
{
if(!createdBase)
{
- if(!updateEntry(toUrl, ats, replace))
- return false;
+ if(!updateEntry(toUrl, ats, replace)) return false;
createdBase = true;
}
+
LDAPURL srcUrl = getReferralUrl(e);
String tmpDstDN = getName(srcUrl.getDN()) + ", " + dstDN;
LDAPURL dstUrl = new LDAPURL(toUrl.getHost(), toUrl.getPort(), tmpDstDN);
boolean rs = transferTreeSub(srcUrl, dstUrl, delete, replace);
- if(!rs)
- return false;
+ if(!rs)return false;
+
moreReferrals = e.skipReferral();
try
{
+ // Close old context
+ checkAndCloseContext(ctx);
ctx = (DirContext)e.getReferralContext();
}
catch(NamingException _ex) { }
@@ -905,8 +1020,12 @@
Log.debug("LDAP Service: Transfer Tree failed", e);
return false;
}
+ }
+
+ checkAndCloseContext(ctx);
return true;
}
+
/**
* Update Atribute Function
*
@@ -930,6 +1049,7 @@
}
return false;
}
+
/**
* Update Atributes Function
*
@@ -939,15 +1059,15 @@
* @param at atrributes to update.
* @return boolean true if success else false.
*/
-
public boolean updateEntry(LDAPURL url, Attributes at)
{
DirContext ctx = connect(url);
- if(ctx == null)
- return false;
+ if(ctx == null) return false;
+
try
{
ctx.modifyAttributes(url.getDN(), 2, at);
+ checkAndCloseContext(ctx);
}
catch(ReferralException e)
{
@@ -956,11 +1076,12 @@
}
catch(NamingException e)
{
- Log.debug("LDAP Service: Failed to update entry " + url.getDN(), e);
+ Log.error("LDAP Service: Failed to update entry " + url.getDN(), e);
return false;
}
return true;
}
+
/**
* Update Entry Function
*
@@ -971,11 +1092,11 @@
* @param replace replace if exist.
* @return boolean true if success else false.
*/
-
public boolean updateEntry(LDAPURL url, Attributes ats, boolean replace)
{
return replace ? synchEntry(url, ats) : addEntry(url, ats);
}
+
/**
* Search Function
*
@@ -989,10 +1110,10 @@
* @exception NamingException
* @return NamingEnumeration Results.
*/
- private NamingEnumeration search(DirContext ctx, String dn, String filter, String attribs[], int type)
+ public NamingEnumeration search(DirContext ctx, String dn, String filter, String attribs[], int type)
throws NamingException
{
- return search(ctx, dn, filter, attribs, type, true);
+ return search(ctx, dn, filter, attribs, type, true);
}
/**
@@ -1023,6 +1144,7 @@
NamingEnumeration results = ctx.search(dn, filter, constraints);
return results;
}
+
/**
* Search Function
*
@@ -1036,6 +1158,14 @@
*/
public Vector search(LDAPURL url, String filter, String attribs[], boolean subTreeScope)
{
+ /*
+ System.out.println("===== LDAPService: search");
+ System.out.println("===== LDAPService: " + url);
+ System.out.println("===== LDAPService: " + filter);
+ System.out.println("===== LDAPService: " + attribs);
+ System.out.println("===== LDAPService: " + subTreeScope);
+ */
+
Vector results = new Vector();
String attrs[] = new String[attribs.length + 1];
attrs[0] = "objectclass";
@@ -1045,6 +1175,7 @@
return results;
}
+
/**
* Search Function
*
@@ -1057,13 +1188,11 @@
* @param rs Result
* @return boolean true if success else false.
*/
-
private boolean subSearch(LDAPURL url, String filter, String attribs[], int scope, Vector rs)
{
DirContext ctx = connect(url);
-
- if(ctx == null)
- return false;
+ if(ctx == null) return false;
+
String entryDN = null;
Attributes at = null;
Attribute a = null;
@@ -1073,7 +1202,8 @@
boolean moreReferrals = true;
while(moreReferrals)
- try
+ {
+ try
{
Vector vl;
for(NamingEnumeration results = search(ctx, baseDN, filter, attribs, scope); results.hasMore(); rs.addElement(vl))
@@ -1108,11 +1238,13 @@
myurl = getReferralUrl(e);
subscope = scope != 1 ? scope : 0;
boolean error = subSearch(myurl, filter, attribs, subscope, rs);
- if(!error)
- return error;
+ if(!error) return error;
+
moreReferrals = e.skipReferral();
try
{
+ // Close old context
+ checkAndCloseContext(ctx);
ctx = (DirContext)e.getReferralContext();
}
catch(NamingException _ex) { }
@@ -1122,6 +1254,9 @@
Log.debug("LDAP Service: Search failed", e);
return false;
}
+ }
+
+ checkAndCloseContext(ctx);
return true;
}
@@ -1133,17 +1268,20 @@
* @param attrvalue input.
* @return String Value.
*/
-
- public String removeAttrName(String attrvalue) {
- StringTokenizer token = new StringTokenizer(attrvalue,"=");
- if (token.countTokens()==2) {
- token.nextToken();
- return token.nextToken();
- }
- else {
- return attrvalue;
- }
+ public String removeAttrName(String attrvalue)
+ {
+ StringTokenizer token = new StringTokenizer(attrvalue,"=");
+ if (token.countTokens()==2)
+ {
+ token.nextToken();
+ return token.nextToken();
+ }
+ else
+ {
+ return attrvalue;
+ }
}
+
/**
* Return full DN Function
*
@@ -1153,7 +1291,6 @@
* @param base Base DN.
* @return String DN.
*/
-
private String getFixedDN(String rdn, String base)
{
return getDN(fixName(rdn), base);
@@ -1167,7 +1304,6 @@
* @param dn DN.
* @return String Name.
*/
-
public String getName(String dn)
{
try
@@ -1180,6 +1316,7 @@
return null;
}
}
+
/**
* Fix Name Function
*
@@ -1188,7 +1325,6 @@
* @param name Name to fix.
* @return String Fixed name.
*/
-
private String fixName(String name)
{
if(name.length() > 0 && name.charAt(0) == '"')
@@ -1203,11 +1339,13 @@
}
return buf.toString();
- } else
+ }
+ else
{
return name;
}
}
+
/**
* Return full DN Function
*
@@ -1217,7 +1355,6 @@
* @param base Base DN.
* @return String full DN.
*/
-
private String getDN(String rdn, String base)
{
if(rdn.length() == 0)
@@ -1227,7 +1364,8 @@
else
return rdn + ", " + base;
}
- /**
+
+ /**
* Return Name Function
*
* Add Base DN to given DN.
@@ -1235,7 +1373,6 @@
* @param dn full DN.
* @return Name Name for given DN.
*/
-
public Name parse(String dn)
{
try
@@ -1247,6 +1384,7 @@
return null;
}
}
+
/**
* Get Referral URL Function
*
@@ -1255,7 +1393,6 @@
* @param e Exception to extract.
* @return LDAPURL referrral URL.
*/
-
public LDAPURL getReferralUrl(ReferralException e)
{
String url = (String)e.getReferralInfo();
@@ -1269,6 +1406,7 @@
}
return null;
}
+
///////////////////////////////////////////////////////////////////////////
// Service Init
///////////////////////////////////////////////////////////////////////////
@@ -1279,7 +1417,6 @@
* @param conf The <code>ServletConfig</code>
* @exception InitializationException if the service fails to initialize
*/
-
public void init( ServletConfig conf ) throws InitializationException
{
connections = new Hashtable();
@@ -1304,12 +1441,14 @@
this.securityAuthentication = serviceConf.getString("securityauthentication","simple");
this.securityProtocol = serviceConf.getString("securityprotocol");
this.socketFactory = serviceConf.getString("socketfactory");
+ this.useCachedDirContexts = serviceConf.getBoolean("contextcache", false);
this.jndiprovider = serviceConf.getString("jndiprovider",DEFAULT_CTX);
this.saslclientpckgs = serviceConf.getString("saslclientpckgs");
mainConnect(new LDAPURL(host,port,basedn));
setInit(true);
}
+
/**
* This is the late initialization method called by the
* Turbine <code>Service</code> framework
@@ -1331,6 +1470,7 @@
}
}
}
+
/**
* Repair Given Parameter Function
*
@@ -1339,11 +1479,13 @@
* @param value String to repair.
* @return String Repaired String.
*/
- private String repair(String value){
+ private String repair(String value)
+ {
value = value.replace('/', '=');
value = value.replace('%', ',');
return value;
}
+
/**
* Tokenizer Wrapper Function
*
@@ -1355,12 +1497,16 @@
*/
private String[] getList(String value, String separator)
{
- if(value == null)
- return null;
+ if(value == null) return null;
+
StringTokenizer tokens = new StringTokenizer(value, separator);
String at[] = new String[tokens.countTokens()];
+
for(int i = 0; tokens.hasMoreTokens(); i++)
+ {
at[i] = tokens.nextToken();
+ }
+
return at;
}
1.5 +0 -0 jakarta-jetspeed/src/java/org/apache/jetspeed/services/ldap/LDAPURL.java
Index: LDAPURL.java
===================================================================
RCS file: /home/cvs/jakarta-jetspeed/src/java/org/apache/jetspeed/services/ldap/LDAPURL.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
1.4 +41 -44 jakarta-jetspeed/src/java/org/apache/jetspeed/services/security/ldap/LDAPAuthentication.java
Index: LDAPAuthentication.java
===================================================================
RCS file: /home/cvs/jakarta-jetspeed/src/java/org/apache/jetspeed/services/security/ldap/LDAPAuthentication.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- LDAPAuthentication.java 9 Dec 2002 20:24:08 -0000 1.3
+++ LDAPAuthentication.java 28 Jan 2003 04:49:44 -0000 1.4
@@ -54,57 +54,51 @@
package org.apache.jetspeed.services.security.ldap;
+import java.security.Principal;
+import javax.naming.directory.BasicAttributes;
import javax.servlet.ServletConfig;
-
-import org.apache.turbine.util.Log;
-import org.apache.turbine.services.TurbineBaseService;
-import org.apache.turbine.services.TurbineServices;
-import org.apache.turbine.services.InitializationException;
-import org.apache.turbine.services.resources.ResourceService;
-
-import org.apache.jetspeed.services.security.PortalAuthentication;
-import org.apache.jetspeed.services.security.LoginException;
-
-import org.apache.jetspeed.services.JetspeedSecurity;
import org.apache.jetspeed.om.security.JetspeedUser;
-import org.apache.jetspeed.om.security.JetspeedUserFactory;
import org.apache.jetspeed.om.security.UserNamePrincipal;
-
+import org.apache.jetspeed.services.JetspeedSecurity;
import org.apache.jetspeed.services.JetspeedUserManagement;
+import org.apache.jetspeed.services.rundata.JetspeedRunData;
+import org.apache.jetspeed.services.rundata.JetspeedRunDataService;
+import org.apache.jetspeed.services.security.FailedLoginException;
+import org.apache.jetspeed.services.security.JetspeedSecurityCache;
+import org.apache.jetspeed.services.security.JetspeedSecurityException;
import org.apache.jetspeed.services.security.JetspeedSecurityService;
import org.apache.jetspeed.services.security.LoginException;
-import org.apache.jetspeed.services.security.FailedLoginException;
+import org.apache.jetspeed.services.security.PortalAuthentication;
import org.apache.jetspeed.services.security.UnknownUserException;
-import org.apache.jetspeed.services.security.UserException;
-import org.apache.jetspeed.services.security.JetspeedSecurityException;
-import org.apache.jetspeed.services.security.JetspeedSecurityCache;
-import org.apache.jetspeed.services.rundata.JetspeedRunDataService;
-import org.apache.jetspeed.services.rundata.JetspeedRunData;
+import org.apache.turbine.om.security.User;
+import org.apache.turbine.services.InitializationException;
+import org.apache.turbine.services.Service;
+import org.apache.turbine.services.TurbineBaseService;
+import org.apache.turbine.services.TurbineServices;
+import org.apache.turbine.services.resources.ResourceService;
import org.apache.turbine.services.rundata.RunDataService;
-
-//openisp
-import javax.naming.*;
-import javax.naming.directory.*;
-import org.apache.jetspeed.om.security.ldap.LDAPUser;
-import org.apache.jetspeed.services.JetspeedLDAP;
-import org.apache.jetspeed.services.ldap.LDAPURL;
+import org.apache.turbine.util.RunData;
/**
*
* @author <a href="mailto:ender@kilicoglu.nom.tr">Ender KILICOGLU</a>
+ * @author <a href="mailto:sami.leino@netorek.fi">Sami Leino</a>
+ *
* @version $Id$
*
*/
-public class LDAPAuthentication extends TurbineBaseService
- implements PortalAuthentication
+public class LDAPAuthentication extends TurbineBaseService
+ implements PortalAuthentication
{
- /** The JetspeedRunData Service. */
- private JetspeedRunDataService runDataService = null;
-
+ // Constants
private final static String CONFIG_ANONYMOUS_USER = "user.anonymous";
- String anonymousUser = "anon";
- private final static String CACHING_ENABLE = "caching.enable";
- private boolean cachingEnable = true;
+ private final static String CACHING_ENABLE = "caching.enable";
+
+ // Instance variables.
+ private JetspeedRunDataService runDataService = null;
+ private String anonymousUser = "anon";
+ private boolean cachingEnable = true;
+
/**
* Given a public credential(username) and private credential(password),
* perform authentication. If authentication succeeds, a <code>JetspeedUser</code>
@@ -123,7 +117,7 @@
{
JetspeedUser user = null;
BasicAttributes attr= new BasicAttributes();
- String[] attrs = {"ou","userPassword","uid","mail"};
+ String[] attrs = {"ou", "userPassword", "uid", "mail"};
String dN = null;
username = JetspeedSecurity.convertUserName(username);
@@ -142,7 +136,7 @@
throw new LoginException(e.toString());
}
- if(!UnixCrypt.matches(user.getPassword().substring(7),password))
+ if(!UnixCrypt.matches(user.getPassword().substring(7), password))
{
throw new FailedLoginException("Credential authentication failure");
}
@@ -159,7 +153,8 @@
{
user.updateLastLogin();
putUserIntoContext(user);
- if (cachingEnable)
+
+ if (cachingEnable)
{
JetspeedSecurityCache.load(username);
}
@@ -183,14 +178,16 @@
throws LoginException
{
JetspeedUser user = null;
+
try
{
user = JetspeedUserManagement.getUser(new UserNamePrincipal(anonymousUser));
user.setHasLoggedIn(new Boolean(false));
putUserIntoContext(user);
+
if (cachingEnable)
{
- JetspeedSecurityCache.load(user.getUserName());
+ JetspeedSecurityCache.load(user.getUserName());
}
}
@@ -215,10 +212,10 @@
{
try
{
- //if (cachingEnable)
- //{
- // JetspeedSecurityCache.unload(getUserFromContext().getUserName());
- //}
+ // if (cachingEnable)
+ // {
+ // JetspeedSecurityCache.unload(getUserFromContext().getUserName());
+ // }
getAnonymousUser();
}
catch (Exception e)
@@ -245,7 +242,7 @@
.getResources(JetspeedSecurityService.SERVICE_NAME);
anonymousUser = serviceConf.getString(CONFIG_ANONYMOUS_USER, anonymousUser);
- cachingEnable = serviceConf.getBoolean( CACHING_ENABLE, cachingEnable );
+ cachingEnable = serviceConf.getBoolean(CACHING_ENABLE, cachingEnable);
this.runDataService =
(JetspeedRunDataService)TurbineServices.getInstance()
1.5 +116 -102 jakarta-jetspeed/src/java/org/apache/jetspeed/services/security/ldap/LDAPGroupManagement.java
Index: LDAPGroupManagement.java
===================================================================
RCS file: /home/cvs/jakarta-jetspeed/src/java/org/apache/jetspeed/services/security/ldap/LDAPGroupManagement.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
--- LDAPGroupManagement.java 9 Dec 2002 20:24:08 -0000 1.4
+++ LDAPGroupManagement.java 28 Jan 2003 04:49:44 -0000 1.5
@@ -54,78 +54,61 @@
package org.apache.jetspeed.services.security.ldap;
-import java.util.Iterator;
-import java.util.Vector;
-import java.util.HashMap;
+import java.security.Principal;
import java.util.Enumeration;
+import java.util.Iterator;
import java.util.StringTokenizer;
-
+import java.util.Vector;
+import javax.naming.directory.BasicAttributes;
import javax.servlet.ServletConfig;
-//openisp
-import javax.naming.*;
-import javax.naming.directory.*;
-
+import org.apache.jetspeed.om.profile.Profile;
+import org.apache.jetspeed.om.profile.ProfileException;
+import org.apache.jetspeed.om.security.Group;
+import org.apache.jetspeed.om.security.UserNamePrincipal;
import org.apache.jetspeed.om.security.ldap.LDAPGroup;
import org.apache.jetspeed.om.security.ldap.LDAPUser;
import org.apache.jetspeed.services.JetspeedLDAP;
+import org.apache.jetspeed.services.JetspeedSecurity;
+import org.apache.jetspeed.services.Profiler;
+import org.apache.jetspeed.services.PsmlManager;
import org.apache.jetspeed.services.ldap.LDAPURL;
-
-// Jetspeed Security
+import org.apache.jetspeed.services.rundata.JetspeedRunData;
+import org.apache.jetspeed.services.rundata.JetspeedRunDataService;
+import org.apache.jetspeed.services.security.GroupException;
import org.apache.jetspeed.services.security.GroupManagement;
-
-import org.apache.jetspeed.om.security.JetspeedUser;
-import org.apache.jetspeed.om.security.BaseJetspeedUser;
-import org.apache.jetspeed.om.security.BaseJetspeedGroup;
-import org.apache.jetspeed.om.security.Group;
-import org.apache.jetspeed.om.security.Role;
-
-import org.apache.jetspeed.services.JetspeedSecurity;
-import org.apache.jetspeed.services.security.UserManagement;
+import org.apache.jetspeed.services.security.JetspeedSecurityException;
import org.apache.jetspeed.services.security.JetspeedSecurityService;
-import org.apache.jetspeed.om.security.UserNamePrincipal;
-
-// Jetspeed Security Exceptions
-import org.apache.jetspeed.services.security.GroupException;
import org.apache.jetspeed.services.security.UnknownUserException;
-import org.apache.jetspeed.services.security.NotUniqueUserException;
-import org.apache.jetspeed.services.security.JetspeedSecurityException;
-
-import org.apache.jetspeed.services.PsmlManager;
-
-// Profile
-import org.apache.jetspeed.om.profile.Profile;
-import org.apache.jetspeed.services.Profiler;
-import org.apache.jetspeed.om.profile.ProfileException;
-
-// Rundata
-import org.apache.jetspeed.services.rundata.JetspeedRunDataService;
-import org.apache.jetspeed.services.rundata.JetspeedRunData;
-import org.apache.turbine.services.rundata.RunDataService;
-
-// Turbine
-import org.apache.turbine.util.Log;
+import org.apache.turbine.services.InitializationException;
+import org.apache.turbine.services.Service;
import org.apache.turbine.services.TurbineBaseService;
import org.apache.turbine.services.TurbineServices;
-import org.apache.turbine.services.InitializationException;
import org.apache.turbine.services.resources.ResourceService;
+import org.apache.turbine.services.rundata.RunDataService;
+import org.apache.turbine.util.RunData;
/**
*
* @author <a href="mailto:ender@kilicoglu.nom.tr">Ender KILICOGLU</a>
+ * @author <a href="mailto:sami.leino@netorek.fi">Sami Leino</a>
+ *
* @version $Id$
*
*/
public class LDAPGroupManagement extends TurbineBaseService
implements GroupManagement
{
- private JetspeedRunDataService runDataService = null;
-
- private final static String CONFIG_DEFAULT_ROLE = "role.default";
- String defaultRole = "user";
- private final static String CASCADE_DELETE = "programmatic.cascade.delete";
+ // Constants
+ private final static String CONFIG_DEFAULT_ROLE = "role.default";
+ private final static String CASCADE_DELETE = "programmatic.cascade.delete";
+ private final static String DEFAULT_DEFAULT_ROLE = "user";
private final static boolean DEFAULT_CASCADE_DELETE = true;
- private boolean cascadeDelete;
- String[] attrs = {"ou","uid"};
+ private final static String[] ATTRS = { "ou", "uid", "groupname" };
+
+ // Instance variables
+ private JetspeedRunDataService runDataService = null;
+ private boolean cascadeDelete = false;
+ private String defaultRole = null;
///////////////////////////////////////////////////////////////////////////
// Group Management Interfaces
@@ -145,6 +128,7 @@
public Iterator getGroups(String username)
throws JetspeedSecurityException
{
+ Vector groups = new Vector();
StringTokenizer st;
LDAPUser user;
@@ -156,21 +140,23 @@
{
throw new GroupException("Failed to Retrieve User: ", e);
}
- Vector groups= new Vector();
+
try
{
for (Enumeration enum = user.getGroupRoles().elements() ;enum.hasMoreElements() ;)
{
st = new StringTokenizer((String)enum.nextElement(),",");
- groups.add(new LDAPGroup(st.nextToken(),false));
+ groups.add(new LDAPGroup(st.nextToken(), false));
}
}
catch(Exception e)
{
throw new GroupException("Failed to retrieve groups ", e);
}
+
return groups.iterator();
}
+
/**
* Retrieves all <code>Group</code>s.
*
@@ -186,23 +172,29 @@
{
BasicAttributes attr= new BasicAttributes();
Vector groups = new Vector();
- Vector userurls;
+ Vector groupurls;
+
try
{
- userurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=groups"),
- "(objectclass=jetspeedgroup)",attrs,true);
- if (userurls.size() > 0){
- for (Enumeration enum = userurls.elements();enum.hasMoreElements() ;){
- groups.add(new LDAPGroup((LDAPURL) (((Vector)enum.nextElement()).firstElement())));
- }
- } else {
- throw new UnknownUserException("No groups ");
- }
+ groupurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=groups"),
+ "(objectclass=jetspeedgroup)", ATTRS, true);
+ if (groupurls.size() > 0)
+ {
+ for (Enumeration enum = groupurls.elements();enum.hasMoreElements() ;)
+ {
+ groups.add(new LDAPGroup((LDAPURL) (((Vector)enum.nextElement()).firstElement())));
+ }
+ }
+ else
+ {
+ throw new UnknownUserException("No groups");
+ }
}
catch(Exception e)
{
throw new GroupException("Failed to retrieve groups ", e);
}
+
return groups.iterator();
}
@@ -218,10 +210,13 @@
* @exception NotUniqueEntityException when the public credentials fail to meet
* the security provider-specific unique constraints.
* @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
+ *
*/
public void addGroup(Group group)
throws JetspeedSecurityException
{
+ LDAPGroup ldapGroup = null;
+
if(groupExists(group.getName()))
{
throw new GroupException("The group '" +
@@ -229,7 +224,8 @@
}
try
{
- new LDAPGroup(group.getName(),true).update(true);
+ ldapGroup = new LDAPGroup(group.getName(), true);
+ ldapGroup.update(true);
}
catch(Exception e)
{
@@ -239,13 +235,13 @@
try
{
- addDefaultGroupPSML(group);
+ addDefaultGroupPSML(ldapGroup);
}
catch (Exception e)
{
try
{
- removeGroup(group.getName());
+ removeGroup(ldapGroup.getName());
}
catch (Exception e2)
{
@@ -262,6 +258,7 @@
JetspeedRunDataService runDataService =
(JetspeedRunDataService)TurbineServices.getInstance()
.getService(RunDataService.SERVICE_NAME);
+
JetspeedRunData rundata = runDataService.getCurrentRunData();
Profile profile = Profiler.createProfile();
profile.setGroup(group);
@@ -280,6 +277,7 @@
throw new GroupException("Failed to create Group PSML", e);
}
}
+
/**
* Saves a <code>Group</code> into permanent storage.
*
@@ -302,13 +300,12 @@
try
{
- }
+ }
catch(Exception e)
{
throw new GroupException("Failed to create group '" +
group.getName() + "'", e);
}
-
}
/**
@@ -328,9 +325,11 @@
{
LDAPGroup group = new LDAPGroup(groupname, false);
JetspeedLDAP.deleteEntry(group.getldapurl());
+
if(cascadeDelete)
{
}
+
PsmlManager.removeGroupDocuments(group);
}
catch(Exception e)
@@ -338,7 +337,6 @@
throw new GroupException("Failed to remove group '" +
groupname + "'", e);
}
-
}
/**
@@ -364,8 +362,8 @@
}
try
{
- user.addGroupRole(groupname,defaultRole);
- user.update(false);
+ user.addGroupRole(groupname, defaultRole);
+ user.update(false);
}
catch(Exception e)
{
@@ -386,6 +384,7 @@
throws JetspeedSecurityException
{
LDAPUser user;
+
try
{
user = (LDAPUser)JetspeedSecurity.getUser(new UserNamePrincipal(username));
@@ -394,10 +393,11 @@
{
throw new GroupException("Failed to Retrieve User: ", e);
}
+
try
{
- user.removeGroup(groupName);
- user.update(false);
+ user.removeGroup(groupName);
+ user.update(false);
}
catch(Exception e)
{
@@ -417,6 +417,7 @@
public boolean inGroup(String username, String groupname)
throws JetspeedSecurityException
{
+ Vector groups= new Vector();
StringTokenizer st;
LDAPUser user;
@@ -429,12 +430,12 @@
throw new GroupException("Failed to Retrieve User: ", e);
}
- Vector groups= new Vector();
try
{
for (Enumeration enum = user.getGroupRoles().elements() ;enum.hasMoreElements() ;)
{
st = new StringTokenizer((String)enum.nextElement(),",");
+
if (st.nextToken().equalsIgnoreCase(groupname))
{
return true;
@@ -445,10 +446,10 @@
{
throw new GroupException("Failed to retrieve groups ", e);
}
+
return false;
}
-
/**
* Retrieves a single <code>Group</code> for a given groupname principal.
*
@@ -456,49 +457,58 @@
* to determine if the requestor has permission to perform this action.
*
* @param groupname a group principal identity to be retrieved.
+ *
* @return Group the group record retrieved.
+ *
* @exception GroupException when the security provider has a general failure.
* @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
+ *
*/
public Group getGroup(String groupname)
throws JetspeedSecurityException
{
BasicAttributes attr= new BasicAttributes();
-
LDAPGroup group;
- Vector userurls;
+ Vector groupurls;
+
try
{
- userurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=groups"),
- "(&(uid="+ groupname+")(objectclass=jetspeedgroup))",attrs,true);
- if (userurls.size() == 1){
- return new LDAPGroup((LDAPURL) ((Vector)userurls.elementAt(0)).firstElement());
- }else if(userurls.size() > 1){
- throw new GroupException("Multiple groups with same name");
- }
+ groupurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=groups"),
+ "(&(uid="+ groupname+")(objectclass=jetspeedgroup))", ATTRS, true);
+ if (groupurls.size() == 1)
+ {
+ return new LDAPGroup((LDAPURL)((Vector)groupurls.elementAt(0)).firstElement());
+ }
+ else if(groupurls.size() > 1)
+ {
+ throw new GroupException("Multiple groups with same name");
+ }
+ else
+ {
+ throw new GroupException("Unknown group '" + groupname + "'");
+ }
}
catch(Exception e)
{
throw new GroupException("Failed to retrieve groups ", e);
}
- throw new GroupException("Unknown group '" + groupname + "'");
-
}
-
///////////////////////////////////////////////////////////////////////////
// Internal
///////////////////////////////////////////////////////////////////////////
protected JetspeedRunData getRunData()
- {
- JetspeedRunData rundata = null;
- if (this.runDataService != null)
- {
- rundata = this.runDataService.getCurrentRunData();
- }
- return rundata;
- }
+ {
+ JetspeedRunData rundata = null;
+
+ if (this.runDataService != null)
+ {
+ rundata = this.runDataService.getCurrentRunData();
+ }
+
+ return rundata;
+ }
/**
* Check whether a specified group exists.
@@ -514,27 +524,31 @@
throws GroupException
{
BasicAttributes attr= new BasicAttributes();
- Vector userurls;
+ Vector groupurls;
+
try
{
- userurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=groups"),
- "(&(uid="+ groupName+")(objectclass=jetspeedgroup))",attrs,true);
- if (userurls.size() > 0){
- return true;
- }
+ groupurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=groups"),
+ "(&(uid="+ groupName+")(objectclass=jetspeedgroup))", ATTRS, true);
+ if (groupurls.size() > 0)
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
}
catch(Exception e)
{
throw new GroupException("Failed to retrieve groups ", e);
}
- return false;
}
///////////////////////////////////////////////////////////////////////////
// Service Init
///////////////////////////////////////////////////////////////////////////
-
/**
* This is the early initialization method called by the
* Turbine <code>Service</code> framework
@@ -556,7 +570,7 @@
(JetspeedRunDataService)TurbineServices.getInstance()
.getService(RunDataService.SERVICE_NAME);
- defaultRole = serviceConf.getString(CONFIG_DEFAULT_ROLE, defaultRole);
+ defaultRole = serviceConf.getString(CONFIG_DEFAULT_ROLE, DEFAULT_DEFAULT_ROLE);
cascadeDelete = serviceConf.getBoolean( CASCADE_DELETE, DEFAULT_CASCADE_DELETE );
setInit(true);
1.4 +42 -64 jakarta-jetspeed/src/java/org/apache/jetspeed/services/security/ldap/LDAPPermissionManagement.java
Index: LDAPPermissionManagement.java
===================================================================
RCS file: /home/cvs/jakarta-jetspeed/src/java/org/apache/jetspeed/services/security/ldap/LDAPPermissionManagement.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- LDAPPermissionManagement.java 9 Dec 2002 20:24:08 -0000 1.3
+++ LDAPPermissionManagement.java 28 Jan 2003 04:49:44 -0000 1.4
@@ -54,74 +54,54 @@
package org.apache.jetspeed.services.security.ldap;
+import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
-import java.util.HashMap;
-import java.util.Enumeration;
+import javax.naming.directory.BasicAttributes;
import javax.servlet.ServletConfig;
-
-
-// Jetspeed Security
-import org.apache.jetspeed.services.security.PermissionManagement;
-import org.apache.jetspeed.services.security.JetspeedSecurityCache;
-import org.apache.jetspeed.services.security.CachedAcl;
-
-import org.apache.jetspeed.om.security.JetspeedUser;
-import org.apache.jetspeed.om.security.BaseJetspeedUser;
-import org.apache.jetspeed.om.security.Role;
import org.apache.jetspeed.om.security.Permission;
-
-import org.apache.jetspeed.services.JetspeedSecurity;
-import org.apache.jetspeed.services.security.UserManagement;
-import org.apache.jetspeed.services.security.JetspeedSecurityService;
-import org.apache.jetspeed.om.security.UserNamePrincipal;
-import org.apache.jetspeed.om.security.BaseJetspeedPermission;
-
-// Jetspeed Security Exceptions
-import org.apache.jetspeed.services.security.PermissionException;
-import org.apache.jetspeed.services.security.JetspeedSecurityException;
-
-import org.apache.jetspeed.services.PsmlManager;
-
-//openisp
-import javax.naming.*;
-import javax.naming.directory.*;
-
+import org.apache.jetspeed.om.security.Role;
import org.apache.jetspeed.om.security.ldap.LDAPPermission;
-import org.apache.jetspeed.om.security.ldap.LDAPUser;
import org.apache.jetspeed.om.security.ldap.LDAPRole;
import org.apache.jetspeed.services.JetspeedLDAP;
+import org.apache.jetspeed.services.JetspeedSecurity;
import org.apache.jetspeed.services.ldap.LDAPURL;
-
-
-// Rundata
-import org.apache.jetspeed.services.rundata.JetspeedRunDataService;
import org.apache.jetspeed.services.rundata.JetspeedRunData;
-import org.apache.turbine.services.rundata.RunDataService;
-
-// Turbine
-import org.apache.turbine.util.Log;
+import org.apache.jetspeed.services.rundata.JetspeedRunDataService;
+import org.apache.jetspeed.services.security.JetspeedSecurityCache;
+import org.apache.jetspeed.services.security.JetspeedSecurityException;
+import org.apache.jetspeed.services.security.JetspeedSecurityService;
+import org.apache.jetspeed.services.security.PermissionException;
+import org.apache.jetspeed.services.security.PermissionManagement;
+import org.apache.turbine.services.InitializationException;
+import org.apache.turbine.services.Service;
import org.apache.turbine.services.TurbineBaseService;
import org.apache.turbine.services.TurbineServices;
-import org.apache.turbine.services.InitializationException;
import org.apache.turbine.services.resources.ResourceService;
+import org.apache.turbine.services.rundata.RunDataService;
/**
*
* @author <a href="mailto:ender@kilicoglu.nom.tr">Ender KILICOGLU</a>
+ * @author <a href="mailto:sami.leino@netorek.fi">Sami Leino</a>
+ *
* @version $Id$
*
*/
public class LDAPPermissionManagement extends TurbineBaseService
implements PermissionManagement
{
- private JetspeedRunDataService runDataService = null;
- private final static String CASCADE_DELETE = "programmatic.cascade.delete";
+ // Constants
+ private final static String CASCADE_DELETE = "programmatic.cascade.delete";
+ private final static String CACHING_ENABLE = "caching.enable";
private final static boolean DEFAULT_CASCADE_DELETE = true;
- private boolean cascadeDelete;
- private final static String CACHING_ENABLE = "caching.enable";
- private boolean cachingEnable = true;
- String[] attrs = {"ou", "uid"};
+ private final static boolean DEFAULT_CACHING_ENABLE = true;
+ private final static String[] ATTRS = { "ou", "uid", "permissionname" };
+
+ // Instance variables
+ private JetspeedRunDataService runDataService = null;
+ private boolean cascadeDelete = false;
+ private boolean cachingEnable = false;
///////////////////////////////////////////////////////////////////////////
// Permission Management Interfaces
@@ -159,7 +139,7 @@
}
userurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=roles"),
- "(&(uid="+ roleName+")(objectclass=jetspeedrole))",attrs,true);
+ "(&(uid=" + roleName + ")(objectclass=jetspeedrole))", ATTRS, true);
if (userurls.size() > 0)
{
@@ -192,13 +172,6 @@
public Iterator getPermissions()
throws JetspeedSecurityException
-
-
-
-
-
-
-
{
BasicAttributes attr= new BasicAttributes();
Vector permissions = new Vector();
@@ -207,7 +180,7 @@
try
{
permissionurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=permissions"),
- "(objectclass=jetspeedpermission)",attrs,true);
+ "(objectclass=jetspeedpermission)", ATTRS, true);
if (permissionurls.size() > 0)
{
@@ -247,7 +220,7 @@
}
try
{
- new LDAPPermission(permission.getName(),true).update(true) ;
+ new LDAPPermission(permission.getName(), true).update(true);
}
catch(Exception e)
{
@@ -305,7 +278,7 @@
}
}
- /**
+ /**
* Grants a permission to a role.
*
* The security service may optionally check the current user context
@@ -336,7 +309,6 @@
{
JetspeedSecurityCache.addPermission(roleName, permission);
}
-
}
catch(Exception e)
{
@@ -347,7 +319,6 @@
/**
* Revokes a permission from a role.
*
-
* The security service may optionally check the current user context
* to determine if the requestor has permission to perform this action.
*
@@ -366,8 +337,13 @@
try
{
userurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=roles"),
- "(&(uid="+ roleName+")(objectclass=jetspeedrole))",attrs,true);
- if (userurls.size() > 0)
+ "(&(uid="+ roleName+")(objectclass=jetspeedrole))", ATTRS, true);
+
+ if (userurls.size() == 0)
+ {
+ throw new PermissionException("Role '" + roleName + "' does not exist!");
+ }
+ else
{
role = new LDAPRole((LDAPURL) ((Vector)userurls.elementAt(0)).firstElement());
role.getRolePermissions().remove(permissionName);
@@ -411,11 +387,11 @@
}
userurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=roles"),
- "(&(uid="+ roleName+")(objectclass=jetspeedrole))",attrs,true);
+ "(&(uid="+ roleName+")(objectclass=jetspeedrole))", ATTRS, true);
+
if (userurls.size() > 0)
{
role = new LDAPRole((LDAPURL) ((Vector)userurls.elementAt(0)).firstElement());
-
return role.permissionExists(permissionName);
}
}
@@ -457,10 +433,12 @@
protected JetspeedRunData getRunData()
{
JetspeedRunData rundata = null;
+
if (this.runDataService != null)
{
rundata = this.runDataService.getCurrentRunData();
}
+
return rundata;
}
@@ -483,7 +461,7 @@
try
{
permissionurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=permissions"),
- "(&(uid=" + permissionName + ")(objectclass=jetspeedpermission))",attrs,true);
+ "(&(uid=" + permissionName + ")(objectclass=jetspeedpermission))", ATTRS, true);
if (permissionurls.size() > 0)
{
1.6 +84 -86 jakarta-jetspeed/src/java/org/apache/jetspeed/services/security/ldap/LDAPRoleManagement.java
Index: LDAPRoleManagement.java
===================================================================
RCS file: /home/cvs/jakarta-jetspeed/src/java/org/apache/jetspeed/services/security/ldap/LDAPRoleManagement.java,v
retrieving revision 1.5
retrieving revision 1.6
diff -u -r1.5 -r1.6
--- LDAPRoleManagement.java 9 Dec 2002 20:24:08 -0000 1.5
+++ LDAPRoleManagement.java 28 Jan 2003 04:49:44 -0000 1.6
@@ -54,78 +54,63 @@
package org.apache.jetspeed.services.security.ldap;
-import java.util.Iterator;
-import java.util.Vector;
-import java.util.HashMap;
+import java.security.Principal;
import java.util.Enumeration;
+import java.util.Iterator;
import java.util.StringTokenizer;
-
+import java.util.Vector;
+import javax.naming.directory.BasicAttributes;
import javax.servlet.ServletConfig;
-//openisp
-import javax.naming.*;
-import javax.naming.directory.*;
-import org.apache.jetspeed.om.security.ldap.LDAPUser;
+import org.apache.jetspeed.om.profile.Profile;
+import org.apache.jetspeed.om.profile.ProfileException;
+import org.apache.jetspeed.om.security.Role;
+import org.apache.jetspeed.om.security.UserNamePrincipal;
import org.apache.jetspeed.om.security.ldap.LDAPRole;
+import org.apache.jetspeed.om.security.ldap.LDAPUser;
import org.apache.jetspeed.services.JetspeedLDAP;
+import org.apache.jetspeed.services.JetspeedSecurity;
+import org.apache.jetspeed.services.Profiler;
+import org.apache.jetspeed.services.PsmlManager;
import org.apache.jetspeed.services.ldap.LDAPURL;
-
-// Jetspeed Security
-import org.apache.jetspeed.services.security.RoleManagement;
-import org.apache.jetspeed.services.security.JetspeedSecurityCache;
+import org.apache.jetspeed.services.rundata.JetspeedRunData;
+import org.apache.jetspeed.services.rundata.JetspeedRunDataService;
import org.apache.jetspeed.services.security.CachedAcl;
-
-import org.apache.jetspeed.om.security.JetspeedUser;
-import org.apache.jetspeed.om.security.BaseJetspeedUser;
-//import org.apache.jetspeed.om.security.BaseJetspeedRole;
-import org.apache.jetspeed.om.security.Group;
-import org.apache.jetspeed.om.security.Role;
-
-import org.apache.jetspeed.services.JetspeedSecurity;
-import org.apache.jetspeed.services.security.UserManagement;
+import org.apache.jetspeed.services.security.JetspeedSecurityCache;
+import org.apache.jetspeed.services.security.JetspeedSecurityException;
import org.apache.jetspeed.services.security.JetspeedSecurityService;
-import org.apache.jetspeed.om.security.UserNamePrincipal;
-
-// Jetspeed Security Exceptions
import org.apache.jetspeed.services.security.RoleException;
+import org.apache.jetspeed.services.security.RoleManagement;
import org.apache.jetspeed.services.security.UnknownUserException;
-import org.apache.jetspeed.services.security.NotUniqueUserException;
-import org.apache.jetspeed.services.security.JetspeedSecurityException;
-
-import org.apache.jetspeed.services.PsmlManager;
-
-// Profile
-import org.apache.jetspeed.om.profile.Profile;
-import org.apache.jetspeed.services.Profiler;
-import org.apache.jetspeed.om.profile.ProfileException;
-
-// Rundata
-import org.apache.jetspeed.services.rundata.JetspeedRunDataService;
-import org.apache.jetspeed.services.rundata.JetspeedRunData;
-import org.apache.turbine.services.rundata.RunDataService;
-
-// Turbine
-import org.apache.turbine.util.Log;
+import org.apache.turbine.services.InitializationException;
+import org.apache.turbine.services.Service;
import org.apache.turbine.services.TurbineBaseService;
import org.apache.turbine.services.TurbineServices;
-import org.apache.turbine.services.InitializationException;
import org.apache.turbine.services.resources.ResourceService;
+import org.apache.turbine.services.rundata.RunDataService;
+import org.apache.turbine.util.RunData;
/**
*
* @author <a href="mailto:ender@kilicoglu.nom.tr">Ender KILICOGLU</a>
+ * @author <a href="mailto:sami.leino@netorek.fi">Sami Leino</a>
+ *
* @version $Id$
*
*/
public class LDAPRoleManagement extends TurbineBaseService
implements RoleManagement
{
- private JetspeedRunDataService runDataService = null;
- private final static String CASCADE_DELETE = "programmatic.cascade.delete";
+ // Constants
+ private final static String CASCADE_DELETE = "programmatic.cascade.delete";
+ private final static String CACHING_ENABLE = "caching.enable";
private final static boolean DEFAULT_CASCADE_DELETE = true;
- private boolean cascadeDelete;
- private final static String CACHING_ENABLE = "caching.enable";
- private boolean cachingEnable = true;
- String[] attrs = {"ou","uid"};
+ private final static boolean DEFAULT_CACHING_ENABLE = true;
+ private final static String[] ATTRS = { "ou", "uid", "rolename", "rolepermissions" };
+
+ // Instance variables
+ private JetspeedRunDataService runDataService = null;
+ private boolean cascadeDelete = false;
+ private boolean cachingEnable = false;
///////////////////////////////////////////////////////////////////////////
// Role Management Interfaces
@@ -165,6 +150,7 @@
}
Vector roles= new Vector();
+
try
{
for (Enumeration enum = user.getGroupRoles().elements() ;enum.hasMoreElements() ;)
@@ -197,16 +183,21 @@
BasicAttributes attr= new BasicAttributes();
Vector roles = new Vector();
Vector roleurls;
+
try
{
- roleurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=roles"),"(objectclass=jetspeedrole)",attrs,true);
- if (roleurls.size() > 0){
- for (Enumeration enum = roleurls.elements();enum.hasMoreElements() ;){
- roles.add(new LDAPRole((LDAPURL) (((Vector)enum.nextElement()).firstElement())));
- }
- } else {
- throw new UnknownUserException("No role ");
- }
+ roleurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=roles"),"(objectclass=jetspeedrole)", ATTRS, true);
+ if (roleurls.size() > 0)
+ {
+ for (Enumeration enum = roleurls.elements(); enum.hasMoreElements() ;)
+ {
+ roles.add(new LDAPRole((LDAPURL) (((Vector)enum.nextElement()).firstElement())));
+ }
+ }
+ else
+ {
+ throw new UnknownUserException("No role ");
+ }
}
catch(Exception e)
{
@@ -227,6 +218,8 @@
public void addRole(Role role)
throws JetspeedSecurityException
{
+ LDAPRole ldapRole = null;
+
if(roleExists(role.getName()))
{
throw new RoleException("The role '" +
@@ -235,7 +228,8 @@
try
{
- new LDAPRole(role.getName(),true).update(true) ;
+ ldapRole = new LDAPRole(role.getName(), true);
+ ldapRole.update(true);
}
catch(Exception e)
{
@@ -245,18 +239,18 @@
if (cachingEnable)
{
- JetspeedSecurityCache.addRole(role);
+ JetspeedSecurityCache.addRole(ldapRole);
}
try
{
- addDefaultRolePSML(role);
+ addDefaultRolePSML(ldapRole);
}
catch (Exception e)
{
try
{
- removeRole(role.getName());
+ removeRole(ldapRole.getName());
}
catch (Exception e2)
{
@@ -287,6 +281,7 @@
}
catch(Exception e2)
{
+e.printStackTrace();
}
throw new RoleException("Failed to create Role PSML", e);
}
@@ -338,12 +333,14 @@
{
try
{
- LDAPRole role = new LDAPRole(roleName,false);
+ LDAPRole role = new LDAPRole(roleName, false);
JetspeedLDAP.deleteEntry(role.getldapurl());
PsmlManager.removeRoleDocuments(role);
+
if(cascadeDelete)
{
}
+
if (cachingEnable)
{
JetspeedSecurityCache.removeAllRoles(roleName);
@@ -354,8 +351,8 @@
throw new RoleException("Failed to remove group '" +
roleName + "'", e);
}
-
}
+
/**
* Grants a role to a user.
*
@@ -376,26 +373,24 @@
role = (LDAPRole)JetspeedSecurity.getRole(roleName);
}
catch(JetspeedSecurityException e)
-
{
throw new RoleException("Failed to Retrieve User or Role: ", e);
}
try
{
- user.addGroupRole(JetspeedSecurity.JETSPEED_GROUP, roleName);
- user.update(false);
+ user.addGroupRole(JetspeedSecurity.JETSPEED_GROUP, roleName);
+ user.update(false);
- if (cachingEnable)
- {
- JetspeedSecurityCache.addRole(username, role);
- }
+ if (cachingEnable)
+ {
+ JetspeedSecurityCache.addRole(username, role);
+ }
}
catch(Exception e)
{
throw new RoleException("Failed to add role info ", e);
}
-
}
/**
@@ -423,7 +418,7 @@
try
{
- user.removeGroupRoles(JetspeedSecurity.JETSPEED_GROUP, roleName);
+ user.removeGroupRole(JetspeedSecurity.JETSPEED_GROUP, roleName);
user.update(false);
if (cachingEnable)
@@ -506,7 +501,7 @@
try
{
roleurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=roles"),
- "(&(uid="+ roleName+")(objectclass=jetspeedrole))",attrs,true);
+ "(&(uid=" + roleName + ")(objectclass=jetspeedrole))", ATTRS, true);
if (roleurls.size() == 1)
{
@@ -523,19 +518,20 @@
}
throw new RoleException("Unknown role '" + roleName + "'");
}
+
///////////////////////////////////////////////////////////////////////////
// Internal
///////////////////////////////////////////////////////////////////////////
protected JetspeedRunData getRunData()
- {
- JetspeedRunData rundata = null;
- if (this.runDataService != null)
- {
- rundata = this.runDataService.getCurrentRunData();
- }
- return rundata;
- }
+ {
+ JetspeedRunData rundata = null;
+ if (this.runDataService != null)
+ {
+ rundata = this.runDataService.getCurrentRunData();
+ }
+ return rundata;
+ }
/**
* Check whether a specified role exists.
@@ -552,13 +548,15 @@
{
BasicAttributes attr= new BasicAttributes();
Vector roleurls;
+
try
{
roleurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=roles"),
- "(&(uid="+ roleName+")(objectclass=jetspeedrole))",attrs,true);
- if (roleurls.size() > 0){
- return true;
- }
+ "(&(uid=" + roleName + ")(objectclass=jetspeedrole))", ATTRS, true);
+ if (roleurls.size() > 0)
+ {
+ return true;
+ }
}
catch(Exception e)
{
@@ -594,7 +592,7 @@
.getService(RunDataService.SERVICE_NAME);
cascadeDelete = serviceConf.getBoolean( CASCADE_DELETE, DEFAULT_CASCADE_DELETE );
- cachingEnable = serviceConf.getBoolean( CACHING_ENABLE, cachingEnable );
+ cachingEnable = serviceConf.getBoolean( CACHING_ENABLE, DEFAULT_CACHING_ENABLE );
setInit(true);
}
1.5 +110 -74 jakarta-jetspeed/src/java/org/apache/jetspeed/services/security/ldap/LDAPUserManagement.java
Index: LDAPUserManagement.java
===================================================================
RCS file: /home/cvs/jakarta-jetspeed/src/java/org/apache/jetspeed/services/security/ldap/LDAPUserManagement.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
--- LDAPUserManagement.java 9 Dec 2002 20:24:08 -0000 1.4
+++ LDAPUserManagement.java 28 Jan 2003 04:49:44 -0000 1.5
@@ -54,76 +54,80 @@
package org.apache.jetspeed.services.security.ldap;
-// Turbine
-import org.apache.turbine.util.Log;
-import org.apache.turbine.services.TurbineBaseService;
-import org.apache.turbine.services.TurbineServices;
-import org.apache.turbine.services.InitializationException;
-import org.apache.turbine.services.resources.ResourceService;
-
-// Jetspeed Security
-import org.apache.jetspeed.om.security.ldap.LDAPUser;
-import org.apache.jetspeed.services.JetspeedLDAP;
-import org.apache.jetspeed.services.ldap.LDAPURL;
-
+import java.security.Principal;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Vector;
+import javax.naming.Context;
+import javax.naming.NamingEnumeration;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.BasicAttributes;
+import javax.naming.directory.DirContext;
+import javax.naming.directory.SearchResult;
+import javax.servlet.ServletConfig;
+import org.apache.jetspeed.om.profile.Profile;
import org.apache.jetspeed.om.security.JetspeedUser;
+import org.apache.jetspeed.om.security.Role;
import org.apache.jetspeed.om.security.UserNamePrincipal;
-import org.apache.jetspeed.om.security.UserIdPrincipal;
-
+import org.apache.jetspeed.om.security.ldap.LDAPUser;
+import org.apache.jetspeed.services.JetspeedLDAP;
import org.apache.jetspeed.services.JetspeedSecurity;
import org.apache.jetspeed.services.Profiler;
import org.apache.jetspeed.services.PsmlManager;
-import org.apache.jetspeed.services.security.UserManagement;
-import org.apache.jetspeed.services.security.JetspeedSecurityService;
-
+import org.apache.jetspeed.services.ldap.LDAPURL;
+import org.apache.jetspeed.services.rundata.JetspeedRunData;
+import org.apache.jetspeed.services.rundata.JetspeedRunDataService;
import org.apache.jetspeed.services.security.CredentialsManagement;
-import org.apache.jetspeed.services.security.UserException;
-import org.apache.jetspeed.services.security.UnknownUserException;
-import org.apache.jetspeed.services.security.NotUniqueUserException;
import org.apache.jetspeed.services.security.JetspeedSecurityException;
-import org.apache.jetspeed.services.rundata.JetspeedRunDataService;
-import org.apache.jetspeed.services.rundata.JetspeedRunData;
+import org.apache.jetspeed.services.security.JetspeedSecurityService;
+import org.apache.jetspeed.services.security.NotUniqueUserException;
+import org.apache.jetspeed.services.security.UnknownUserException;
+import org.apache.jetspeed.services.security.UserException;
+import org.apache.jetspeed.services.security.UserManagement;
+import org.apache.turbine.om.security.User;
+import org.apache.turbine.services.InitializationException;
+import org.apache.turbine.services.Service;
+import org.apache.turbine.services.TurbineBaseService;
+import org.apache.turbine.services.TurbineServices;
+import org.apache.turbine.services.resources.ResourceService;
import org.apache.turbine.services.rundata.RunDataService;
-import org.apache.jetspeed.services.resources.JetspeedResources;
-
-import org.apache.jetspeed.om.profile.Profile;
-
-import java.security.Principal;
-import java.util.Iterator;
-import java.util.List;
-import javax.servlet.ServletConfig;
-import javax.naming.*;
-import javax.naming.directory.*;
-import java.util.Vector;
-import java.util.Enumeration;
+import org.apache.turbine.util.Log;
+import org.apache.turbine.util.RunData;
/**
*
* @author <a href="mailto:ender@kilicoglu.nom.tr">Ender KILICOGLU</a>
+ * @author <a href="mailto:sami.leino@netorek.fi">Sami Leino</a>
+ *
* @version $Id$
*
*/
public class LDAPUserManagement extends TurbineBaseService
- implements UserManagement,
- CredentialsManagement
+ implements UserManagement,
+ CredentialsManagement
{
+ // Constants
private final static String CONFIG_SECURE_PASSWORDS_KEY = "secure.passwords";
private final static String CONFIG_SECURE_PASSWORDS_ALGORITHM = "secure.passwords.algorithm";
private final static String CONFIG_SECURE_PASSWORDS_SUFFIX = "secure.passwords.suffix";
private final static String CONFIG_NEWUSER_ROLES = "newuser.roles";
private final static String [] DEFAULT_CONFIG_NEWUSER_ROLES = { "user" };
- protected boolean securePasswords = false;
- protected String passwordsAlgorithm = "crypt";
- protected String passwordsSuffix = "{crypt}";
- protected String roles[] = null;
- protected String[] attrs = { "ou", "userPassword", "uid", "mail"};
-
- /** The JetspeedRunData Service. */
- private JetspeedRunDataService runDataService = null;
+ private final String[] ATTRS = { "ou", "userPassword", "uid", "mail", "sn", "givenName",
+ "uidNumber", "name", "objectdata", "objectClass",
+ "usergrouprole", "lastlogindate", "lastmodifieddate",
+ "creationdate", "confirm", "disabled" };
+
+ // Instance variables
+ protected JetspeedRunDataService runDataService = null;
+ protected boolean securePasswords = false;
+ protected String passwordsAlgorithm = "crypt";
+ protected String passwordsSuffix = "{crypt}";
+ protected String roles[] = null;
///////////////////////////////////////////////////////////////////////////
- // User Management Interfaces
+ // User Management Interfaces
///////////////////////////////////////////////////////////////////////////
/**
@@ -136,23 +140,29 @@
* to determine if the requestor has permission to perform this action.
*
* @param principal a principal identity to be retrieved.
+ *
* @return a <code>JetspeedUser</code> associated to the principal identity.
* @exception UserException when the security provider has a general failure retrieving a user.
* @exception UnknownUserException when the security provider cannot match
* the principal identity to a user.
- * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
+ * @exception InsufficientPrivilegeException when the requestor is denied
+ * due to insufficient privilege
*/
public JetspeedUser getUser(Principal principal)
throws JetspeedSecurityException
{
- BasicAttributes attr= new BasicAttributes();
+ BasicAttributes attr = new BasicAttributes();
Vector userurls = new Vector();
LDAPUser user = null;
try
{
userurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=users"),
- "(&(uid="+principal.getName()+")(objectclass=jetspeeduser))",attrs,true);
+ "(&(uid="+principal.getName()+")(objectclass=jetspeeduser))", ATTRS, true);
+ /*
+ userurls = JetspeedLDAP.search(JetspeedLDAP.buildURL("ou=users"),
+ "(&(uid="+principal.getName()+")(objectclass=jetspeeduser))", null, true);
+ */
}
catch (Exception e)
{
@@ -187,7 +197,7 @@
throws JetspeedSecurityException
{
String filter = "(objectclass=jetspeeduser)";
- return getUsersUsingLDAPSpecificFilter(filter);
+ return getUsersUsingLDAPSpecificFilter(filter, null);
}
/**
@@ -199,12 +209,13 @@
* @return a collection of <code>JetspeedUser</code> entities.
* @exception UserException when the security provider has a general failure retrieving users.
* @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
+ *
*/
public Iterator getUsers(String filter)
throws JetspeedSecurityException
{
// String ldapFilter = convert(filter);
- return getUsersUsingLDAPSpecificFilter(filter);
+ return getUsersUsingLDAPSpecificFilter(filter, null);
}
/**
@@ -217,33 +228,40 @@
* @exception UserException when the security provider has a general failure retrieving users.
* @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
*/
- private Iterator getUsersUsingLDAPSpecificFilter(String filter)
+ protected Iterator getUsersUsingLDAPSpecificFilter(String filter, String[] attributesToFetch)
throws JetspeedSecurityException
{
String baseDN = "ou=users";
- Vector userurls = new Vector();
+ NamingEnumeration userEnum = null;
+ List resultList = new Vector(1024);
try
{
LDAPURL url = JetspeedLDAP.buildURL( baseDN );
- userurls = JetspeedLDAP.search( url, filter, attrs, true );
+ DirContext ctx = JetspeedLDAP.getService().connect(url);
+ userEnum = JetspeedLDAP.search(ctx, url.getDN(), filter, attributesToFetch, JetspeedLDAP.getService().SUB);
+
+ while (userEnum.hasMoreElements())
+ {
+ LDAPUser user = buildUser(((SearchResult)userEnum.nextElement()).getAttributes());
+ resultList.add( user );
+ }
+
+ JetspeedLDAP.getService().checkAndCloseContext(ctx);
}
catch ( Exception e )
{
throw new UserException( "Failed to retrieve user with filter:" + filter, e );
}
- List resultList = new Vector( userurls.size() );
- for ( int i = 0; i < userurls.size(); i++ )
- {
- Vector v = (Vector) userurls.get( i );
- LDAPURL userurl = (LDAPURL) v.firstElement();
- LDAPUser user = new LDAPUser( userurl );
- resultList.add( user );
- }
return ( resultList.iterator() );
}
+ protected LDAPUser buildUser(Attributes attributes)
+ {
+ return new LDAPUser(attributes);
+ }
+
/**
* Saves a <code>JetspeedUser</code>'s attributes into permanent storage.
* The user's account is required to exist in the storage.
@@ -286,10 +304,17 @@
public void addUser(JetspeedUser user)
throws JetspeedSecurityException
{
+ if(accountExists(user))
+ {
+ throw new NotUniqueUserException("The account '" +
+ user.getUserName() + "' already exists");
+ }
+
String initialPassword = user.getPassword();
String encrypted = JetspeedSecurity.encryptPassword(initialPassword);
user.setPassword(encrypted);
((LDAPUser)user).update(true);
+
addDefaultPSML(user);
}
@@ -307,6 +332,7 @@
{
try
{
+
JetspeedSecurity.grantRole(user.getUserName(),
JetspeedSecurity.getRole(roles[ix]).getName());
}
@@ -332,6 +358,7 @@
throw new UserException("Failed to create profile for new user ", e);
}
}
+
/**
* Removes a <code>JetspeedUser</code> from the permanent store.
* The security service may optionally check the current user context
@@ -364,6 +391,7 @@
}
///////////////////////////////////////////////////////////////////////////
// Credentials Management
+
///////////////////////////////////////////////////////////////////////////
/**
@@ -373,8 +401,6 @@
* @param oldPassword the current password supplied by the user.
* @param newPassword the current password requested by the user.
* @exception UserException when the security provider has a general failure retrieving a user.
-
-
* @exception UnknownUserException when the security provider cannot match
* the principal identity to a user.
* @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
@@ -407,6 +433,7 @@
// before it is saved at session's expiry.
saveUser(user);
}
+
/**
* Forcibly sets new password for a User.
*
@@ -415,12 +442,15 @@
* would require administrative level access to the authenticating
* server / program.
*
- * @param user the user to change the password for.
- * @param password the new password.
- * @exception UserException when the security provider has a general failure retrieving a user.
+ * @param user the user to change the password for.
+ * @param password the new password.
+ *
+ * @exception UserException when the security provider has a general
+ * failure retrieving a user.
* @exception UnknownUserException when the security provider cannot match
* the principal identity to a user.
- * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
+ * @exception InsufficientPrivilegeException when the requestor is
+ * denied due to insufficient privilege
*/
public void forcePassword( JetspeedUser user, String password )
throws JetspeedSecurityException
@@ -443,14 +473,17 @@
/**
* This method provides client-side encryption of passwords.
*
- * If <code>secure.passwords</code> are enabled in JetspeedSecurity properties,
+ * If <code>secure.passwords</code> are enabled in
+ * JetspeedSecurity.properties,
* the password will be encrypted, if not, it will be returned unchanged.
* The <code>secure.passwords.algorithm</code> property can be used
* to chose which digest algorithm should be used for performing the
* encryption. <code>SHA</code> is used by default.
*
* @param password the password to process
+ *
* @return processed password
+ *
*/
public String encryptPassword( String password )
throws JetspeedSecurityException
@@ -529,13 +562,16 @@
*
* The login name is used for looking up the account.
*
- * @param user the user to be checked.
- * @param checkUniqueId make sure that we aren't overwriting another user with different id
- * @return true if the specified account exists
- * @throws UserException if there was a general db access error
+ * @param user The user to be checked.
+ * @param checkUniqueId Make sure that we aren't
+ * overwriting another user
+ * with different id.
+ *
+ * @return true If the specified account exists
+ *
+ * @throws UserException If there was a general db access error
*
*/
-
protected boolean accountExists( JetspeedUser user )
throws UserException
{
1.3 +0 -0 jakarta-jetspeed/src/java/org/apache/jetspeed/services/security/ldap/UnixCrypt.java
Index: UnixCrypt.java
===================================================================
RCS file: /home/cvs/jakarta-jetspeed/src/java/org/apache/jetspeed/services/security/ldap/UnixCrypt.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
1.3 +0 -0 jakarta-jetspeed/src/java/org/apache/jetspeed/util/Base64.java
Index: Base64.java
===================================================================
RCS file: /home/cvs/jakarta-jetspeed/src/java/org/apache/jetspeed/util/Base64.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--
To unsubscribe, e-mail: <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>