[seam-commits] Seam SVN: r7699 - trunk/src/main/org/jboss/seam/security/management.

seam-commits at lists.jboss.org seam-commits at lists.jboss.org
Wed Mar 26 02:50:01 EDT 2008


Author: shane.bryzak at jboss.com
Date: 2008-03-26 02:50:01 -0400 (Wed, 26 Mar 2008)
New Revision: 7699

Added:
   trunk/src/main/org/jboss/seam/security/management/UserAction.java
Modified:
   trunk/src/main/org/jboss/seam/security/management/IdentityManager.java
   trunk/src/main/org/jboss/seam/security/management/IdentityStore.java
   trunk/src/main/org/jboss/seam/security/management/JpaIdentityStore.java
   trunk/src/main/org/jboss/seam/security/management/LdapIdentityStore.java
Log:
new user creation, more customisable, included UserAction in identity management API

Modified: trunk/src/main/org/jboss/seam/security/management/IdentityManager.java
===================================================================
--- trunk/src/main/org/jboss/seam/security/management/IdentityManager.java	2008-03-26 01:17:30 UTC (rev 7698)
+++ trunk/src/main/org/jboss/seam/security/management/IdentityManager.java	2008-03-26 06:50:01 UTC (rev 7699)
@@ -91,9 +91,14 @@
    
    public boolean createUser(String name, String password)
    {
+      return createUser(name, password, null, null);
+   }
+
+   public boolean createUser(String name, String password, String firstname, String lastname)
+   {
       Identity.instance().checkPermission(ACCOUNT_PERMISSION_NAME, PERMISSION_CREATE);
-      return userIdentityStore.createUser(name, password); 
-   }
+      return userIdentityStore.createUser(name, password, firstname, lastname); 
+   }   
    
    public boolean deleteUser(String name)
    {

Modified: trunk/src/main/org/jboss/seam/security/management/IdentityStore.java
===================================================================
--- trunk/src/main/org/jboss/seam/security/management/IdentityStore.java	2008-03-26 01:17:30 UTC (rev 7698)
+++ trunk/src/main/org/jboss/seam/security/management/IdentityStore.java	2008-03-26 06:50:01 UTC (rev 7699)
@@ -57,6 +57,7 @@
    boolean supportsFeature(int feature);
    
    boolean createUser(String username, String password);
+   boolean createUser(String username, String password, String firstname, String lastname);
    boolean deleteUser(String name);   
    boolean enableUser(String name);
    boolean disableUser(String name);   

Modified: trunk/src/main/org/jboss/seam/security/management/JpaIdentityStore.java
===================================================================
--- trunk/src/main/org/jboss/seam/security/management/JpaIdentityStore.java	2008-03-26 01:17:30 UTC (rev 7698)
+++ trunk/src/main/org/jboss/seam/security/management/JpaIdentityStore.java	2008-03-26 06:50:01 UTC (rev 7699)
@@ -2,6 +2,7 @@
 
 import static org.jboss.seam.ScopeType.APPLICATION;
 
+import java.lang.reflect.Field;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -45,6 +46,32 @@
    
    private Map<String,Set<String>> roleCache;
    
+   private Field firstNameField;
+   private Field lastNameField;
+   
+   private String firstNameFieldName;   
+   private String lastNameFieldName;
+   
+   public String getFirstNameField()
+   {
+      return firstNameFieldName;
+   }
+   
+   public void setFirstNameField(String firstNameFieldName)
+   {
+      this.firstNameFieldName = firstNameFieldName;
+   }
+   
+   public String getLastNameField()
+   {
+      return lastNameFieldName;
+   }
+   
+   public void setLastNameField(String lastNameFieldName)
+   {
+      this.lastNameFieldName = lastNameFieldName;
+   }
+   
    public int getFeatures()
    {
       return featureSet.getFeatures();
@@ -64,6 +91,32 @@
    public void init()
    {
       loadRoles();
+      
+      if (getFirstNameField() != null)
+      {
+         try
+         {
+            firstNameField = accountClass.getField(getFirstNameField());
+         }
+         catch (NoSuchFieldException ex)
+         {
+            throw new RuntimeException("First name field " + getFirstNameField() + " does not exist " +
+                  "in account class " + accountClass.getName(), ex);
+         }
+      }
+      
+      if (getLastNameField() != null)
+      {
+         try
+         {
+            lastNameField = accountClass.getField(getLastNameField());
+         }
+         catch (NoSuchFieldException ex)
+         {
+            throw new RuntimeException("Last name field " + getLastNameField() + " does not exist " +
+                  "in account class " + accountClass.getName(), ex);
+         }
+      }      
    }
    
    protected void loadRoles()
@@ -86,10 +139,24 @@
       }      
    }
    
-   public boolean createUser(String username, String password)
+   private void setFieldValue(Field field, Object instance, Object value) throws Exception
    {
+      boolean accessible = field.isAccessible();
       try
       {
+         field.setAccessible(true);
+         field.set(instance, value);
+      }
+      finally
+      {
+         field.setAccessible(accessible);
+      }
+   }
+   
+   public boolean createUser(String username, String password, String firstname, String lastname)
+   {
+      try
+      {
          if (accountClass == null)
          {
             throw new IdentityManagementException("Could not create account, accountClass not set");
@@ -104,6 +171,9 @@
          account.setAccountType(UserAccount.AccountType.user);
          account.setUsername(username);
          
+         if (firstNameField != null) setFieldValue(firstNameField, account, firstname);         
+         if (lastNameField != null) setFieldValue(lastNameField, account, lastname);
+         
          if (password == null)
          {
             account.setEnabled(false);
@@ -130,9 +200,14 @@
          {
             throw new IdentityManagementException("Could not create account", ex);
          }
-      }
+      }      
    }
    
+   public boolean createUser(String username, String password)
+   {
+      return createUser(username, password, null, null);
+   }
+   
    public boolean deleteUser(String name)
    {
       UserAccount account = validateAccount(name);

Modified: trunk/src/main/org/jboss/seam/security/management/LdapIdentityStore.java
===================================================================
--- trunk/src/main/org/jboss/seam/security/management/LdapIdentityStore.java	2008-03-26 01:17:30 UTC (rev 7698)
+++ trunk/src/main/org/jboss/seam/security/management/LdapIdentityStore.java	2008-03-26 06:50:01 UTC (rev 7699)
@@ -51,15 +51,30 @@
    
    private String userRoleAttribute = "roles";
    
-   private boolean roleAttributeIsDN = true;   
+   private boolean roleAttributeIsDN = true;
    
+   private String userNameAttribute = "uid";
+   
+   private String userPasswordAttribute = "userPassword";
+   
+   private String firstNameAttribute = null;
+   
+   private String lastNameAttribute = "sn";
+   
+   private String fullNameAttribute = "cn";
+   
    private String roleNameAttribute = "cn";
    
    private String objectClassAttribute = "objectClass";
    
-   private String roleObjectClass = "organizationalRole";
+   private String[] roleObjectClasses = { "organizationalRole" };
    
-   private String userObjectClass = "person";
+   private String[] userObjectClasses = { "person", "uidObject" };
+   
+   /**
+    * Time limit for LDAP searches, in milliseconds
+    */
+   private int searchTimeLimit = 10000;
       
    public String getServerAddress()
    {
@@ -171,6 +186,56 @@
       this.roleNameAttribute = roleNameAttribute;
    }
    
+   public String getUserNameAttribute()
+   {
+      return userNameAttribute;
+   }
+   
+   public void setUserNameAttribute(String userNameAttribute)
+   {
+      this.userNameAttribute = userNameAttribute;
+   }
+   
+   public String getUserPasswordAttribute()
+   {
+      return userPasswordAttribute;
+   }
+   
+   public void setUserPasswordAttribute(String userPasswordAttribute)
+   {
+      this.userPasswordAttribute = userPasswordAttribute;
+   }
+   
+   public String getFirstNameAttribute()
+   {
+      return firstNameAttribute;
+   }
+   
+   public void setFirstNameAttribute(String firstNameAttribute)
+   {
+      this.firstNameAttribute = firstNameAttribute;
+   }
+   
+   public String getLastNameAttribute()
+   {
+      return lastNameAttribute;
+   }
+   
+   public void setLastNameAttribute(String lastNameAttribute)
+   {
+      this.lastNameAttribute = lastNameAttribute;
+   }
+   
+   public String getFullNameAttribute()
+   {
+      return fullNameAttribute;
+   }
+   
+   public void setFullNameAttribute(String fullNameAttribute)
+   {
+      this.fullNameAttribute = fullNameAttribute;
+   }
+   
    public String getObjectClassAttribute()
    {
       return objectClassAttribute;
@@ -181,26 +246,36 @@
       this.objectClassAttribute = objectClassAttribute;
    }
    
-   public String getRoleObjectClass()
+   public String[] getRoleObjectClasses()
    {
-      return roleObjectClass;
+      return roleObjectClasses;
    }
    
-   public void setRoleObjectClass(String roleObjectClass)
+   public void setRoleObjectClass(String[] roleObjectClasses)
    {
-      this.roleObjectClass = roleObjectClass;
+      this.roleObjectClasses = roleObjectClasses;
    }
    
-   public String getUserObjectClass()
+   public String[] getUserObjectClasses()
    {
-      return userObjectClass;
+      return userObjectClasses;
    }
    
-   public void setUserObjectClass(String userObjectClass)
+   public void setUserObjectClasses(String[] userObjectClasses)
    {
-      this.userObjectClass = userObjectClass;
+      this.userObjectClasses = userObjectClasses;
    }
    
+   public int getSearchTimeLimit()
+   {
+      return searchTimeLimit;
+   }
+   
+   public void setSearchTimeLimit(int searchTimeLimit)
+   {
+      this.searchTimeLimit = searchTimeLimit;
+   }
+   
    public int getFeatures()
    {
       return featureSet.getFeatures();
@@ -277,7 +352,10 @@
          Attributes roleAttribs = new BasicAttributes();
          
          BasicAttribute roleClass = new BasicAttribute(getObjectClassAttribute());
-         roleClass.add(getRoleObjectClass());
+         for (String objectClass : getRoleObjectClasses())
+         {
+            roleClass.add(objectClass);
+         }
          
          BasicAttribute roleName = new BasicAttribute(getRoleNameAttribute());
          roleName.add(role);
@@ -295,11 +373,67 @@
          throw new IdentityManagementException("Failed to create role", ex);
       }
    }
+   
+   public boolean createUser(String username, String password, String firstname, String lastname)
+   {
+      InitialLdapContext ctx = null;      
+      try
+      {
+         ctx = initialiseContext();
+         
+         Attributes userAttribs = new BasicAttributes();
+         
+         BasicAttribute userClass = new BasicAttribute(getObjectClassAttribute());
+         for (String objectClass : getUserObjectClasses())
+         {
+            userClass.add(objectClass);
+         }
+         
+         BasicAttribute usernameAttrib = new BasicAttribute(getUserNameAttribute());
+         usernameAttrib.add(username);
+         
+         BasicAttribute passwordAttrib = new BasicAttribute(getUserPasswordAttribute());
+         passwordAttrib.add(PasswordHash.generateHash(password));
+         
+         userAttribs.put(userClass);
+         userAttribs.put(usernameAttrib);
+         userAttribs.put(passwordAttrib);
+         
+         if (getFirstNameAttribute() != null && firstname != null)
+         {
+            BasicAttribute firstNameAttrib = new BasicAttribute(getFirstNameAttribute());
+            firstNameAttrib.add(firstname);
+            userAttribs.put(firstNameAttrib);
+         }
+         
+         if (getLastNameAttribute() != null && lastname != null)
+         {
+            BasicAttribute lastNameAttrib = new BasicAttribute(getLastNameAttribute());
+            lastNameAttrib.add(lastname);
+            userAttribs.put(lastNameAttrib);
+         }
+         
+         if (getFullNameAttribute() != null && firstname != null && lastname != null)
+         {
+            BasicAttribute fullNameAttrib = new BasicAttribute(getFullNameAttribute());
+            fullNameAttrib.add(firstname + " " + lastname);
+            userAttribs.put(fullNameAttrib);
+         }
+         
+         String userDN = String.format("%s=%s,%s", getUserNameAttribute(), username, getUserContextDN() );          
+         ctx.createSubcontext(userDN, userAttribs);
+         
+         return true;
+      }
+      catch (NamingException ex)
+      {
+         throw new IdentityManagementException("Failed to create user", ex);
+      }      
+   }
 
    public boolean createUser(String username, String password) 
    {
-      // TODO Auto-generated method stub
-      return false;
+      return createUser(username, password, null, null);
    }
 
    public boolean deleteRole(String role) 
@@ -336,9 +470,8 @@
          controls.setReturningAttributes(roleAttr);
          controls.setTimeLimit(searchTimeLimit);
          
-         // TODO make these configurable
          String roleFilter = "(&(" + getObjectClassAttribute() + "={0})(" + getRoleNameAttribute() + "={1}))";
-         Object[] filterArgs = { getRoleObjectClass(), role};
+         Object[] filterArgs = { getRoleObjectClasses(), role};
          
          NamingEnumeration answer = ctx.search(getRoleContextDN(), roleFilter, filterArgs, controls);
          while (answer.hasMore())
@@ -418,18 +551,17 @@
       {
          ctx = initialiseContext();
                   
-         String userFilter = "(uid={0})";
+         String userFilter = "(" + getUserNameAttribute() + "={0})";
                   
          // TODO make configurable
          int searchScope = SearchControls.SUBTREE_SCOPE;
-         int searchTimeLimit = 10000;
          
          String[] roleAttr = { getUserRoleAttribute() };
                   
          SearchControls controls = new SearchControls();
          controls.setSearchScope(searchScope);
          controls.setReturningAttributes(roleAttr);
-         controls.setTimeLimit(searchTimeLimit);
+         controls.setTimeLimit(getSearchTimeLimit());
          Object[] filterArgs = {name};
          
          NamingEnumeration answer = ctx.search(getUserContextDN(), userFilter, filterArgs, controls);
@@ -438,38 +570,41 @@
             SearchResult sr = (SearchResult) answer.next();
             Attributes attrs = sr.getAttributes();
             Attribute roles = attrs.get( getUserRoleAttribute() );
-            for (int r = 0; r < roles.size(); r++)
+            if (roles != null)
             {
-               Object value = roles.get(r);
-               String roleName = null;
-               if (getRoleAttributeIsDN() == true)
+               for (int r = 0; r < roles.size(); r++)
                {
-                  String roleDN = value.toString();
-                  String[] returnAttribute = {getRoleNameAttribute()};
-                  try
+                  Object value = roles.get(r);
+                  String roleName = null;
+                  if (getRoleAttributeIsDN() == true)
                   {
-                     Attributes result2 = ctx.getAttributes(roleDN, returnAttribute);
-                     Attribute roles2 = result2.get(getRoleNameAttribute());
-                     if( roles2 != null )
+                     String roleDN = value.toString();
+                     String[] returnAttribute = {getRoleNameAttribute()};
+                     try
                      {
-                        for(int m = 0; m < roles2.size(); m ++)
+                        Attributes result2 = ctx.getAttributes(roleDN, returnAttribute);
+                        Attribute roles2 = result2.get(getRoleNameAttribute());
+                        if( roles2 != null )
                         {
-                           roleName = (String) roles2.get(m);
-                           userRoles.add(roleName);
+                           for(int m = 0; m < roles2.size(); m ++)
+                           {
+                              roleName = (String) roles2.get(m);
+                              userRoles.add(roleName);
+                           }
                         }
                      }
+                     catch (NamingException ex)
+                     {
+                        throw new IdentityManagementException("Failed to query roles", ex);
+                     }
                   }
-                  catch (NamingException ex)
+                  else
                   {
-                     throw new IdentityManagementException("Failed to query roles", ex);
+                     // The role attribute value is the role name
+                     roleName = value.toString();
+                     userRoles.add(roleName);
                   }
                }
-               else
-               {
-                  // The role attribute value is the role name
-                  roleName = value.toString();
-                  userRoles.add(roleName);
-               }
             }
          }
          answer.close();                     
@@ -521,19 +656,29 @@
          
          // TODO make configurable
          int searchScope = SearchControls.SUBTREE_SCOPE;
-         int searchTimeLimit = 10000;
          
          String[] roleAttr = { getRoleNameAttribute() };
                            
          SearchControls controls = new SearchControls();
          controls.setSearchScope(searchScope);
          controls.setReturningAttributes(roleAttr);
-         controls.setTimeLimit(searchTimeLimit);
+         controls.setTimeLimit(getSearchTimeLimit());
          
-         String roleFilter = "(" + getObjectClassAttribute() + "={0})";
-         Object[] filterArgs = { getRoleObjectClass() };
+         StringBuilder roleFilter = new StringBuilder();
          
-         NamingEnumeration answer = ctx.search( getRoleContextDN(), roleFilter, filterArgs, controls);
+         Object[] filterArgs = new Object[getRoleObjectClasses().length];
+         for (int i = 0; i < getRoleObjectClasses().length; i++)
+         {
+            roleFilter.append("(");
+            roleFilter.append(getObjectClassAttribute());
+            roleFilter.append("={");
+            roleFilter.append(i);
+            roleFilter.append("})");
+            filterArgs[i] = getRoleObjectClasses()[i];
+         }         
+         
+         NamingEnumeration answer = ctx.search( getRoleContextDN(), roleFilter.toString(), 
+               filterArgs, controls);
          while (answer.hasMore())
          {
             SearchResult sr = (SearchResult) answer.next();
@@ -577,27 +722,33 @@
          
          // TODO make configurable
          int searchScope = SearchControls.SUBTREE_SCOPE;
-         int searchTimeLimit = 10000;
          
-         // TODO make configurable
-         String userAttrName = "uid";
-         String[] userAttr = {userAttrName};
+         String[] userAttr = {getUserNameAttribute()};
                            
          SearchControls controls = new SearchControls();
          controls.setSearchScope(searchScope);
          controls.setReturningAttributes(userAttr);
-         controls.setTimeLimit(searchTimeLimit);
+         controls.setTimeLimit(getSearchTimeLimit());
+                  
+         StringBuilder userFilter = new StringBuilder();
          
-         // TODO make these configurable
-         String userFilter = "(" + getObjectClassAttribute() + "={0})";
-         Object[] filterArgs = { getUserObjectClass() };
+         Object[] filterArgs = new Object[getUserObjectClasses().length];
+         for (int i = 0; i < getUserObjectClasses().length; i++)
+         {
+            userFilter.append("(");
+            userFilter.append(getObjectClassAttribute());
+            userFilter.append("={");
+            userFilter.append(i);
+            userFilter.append("})");
+            filterArgs[i] = getUserObjectClasses()[i];
+         }            
          
-         NamingEnumeration answer = ctx.search(getUserContextDN(), userFilter, filterArgs, controls);
+         NamingEnumeration answer = ctx.search(getUserContextDN(), userFilter.toString(), filterArgs, controls);
          while (answer.hasMore())
          {
             SearchResult sr = (SearchResult) answer.next();
             Attributes attrs = sr.getAttributes();
-            Attribute user = attrs.get(userAttrName);
+            Attribute user = attrs.get(getUserNameAttribute());
             
             for (int i = 0; i < user.size(); i++)
             {

Added: trunk/src/main/org/jboss/seam/security/management/UserAction.java
===================================================================
--- trunk/src/main/org/jboss/seam/security/management/UserAction.java	                        (rev 0)
+++ trunk/src/main/org/jboss/seam/security/management/UserAction.java	2008-03-26 06:50:01 UTC (rev 7699)
@@ -0,0 +1,211 @@
+package org.jboss.seam.security.management;
+
+import static org.jboss.seam.ScopeType.CONVERSATION;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.jboss.seam.annotations.Begin;
+import org.jboss.seam.annotations.In;
+import org.jboss.seam.annotations.Name;
+import org.jboss.seam.annotations.Scope;
+import org.jboss.seam.core.Conversation;
+import org.jboss.seam.faces.FacesMessages;
+import org.jboss.seam.security.management.IdentityManager;
+
+/**
+ * A conversation-scoped component for creating and managing user accounts
+ * 
+ * @author Shane Bryzak
+ */
+ at Name("org.jboss.seam.security.userAction")
+ at Scope(CONVERSATION)
+public class UserAction
+{
+   private String firstname;
+   private String lastname;
+   private String username;
+   private String password;
+   private String confirm;
+   private List<String> roles;
+   private boolean enabled;
+   
+   private boolean newUserFlag;   
+   
+   @In IdentityManager identityManager;
+      
+   @Begin
+   public void createUser()
+   {
+      roles = new ArrayList<String>();
+      newUserFlag = true;
+   }
+   
+   @Begin
+   public void editUser(String username)
+   {      
+      this.username = username;
+      roles = identityManager.getGrantedRoles(username);
+      enabled = identityManager.isUserEnabled(username);
+      newUserFlag = false;
+   }
+      
+   public String save()
+   {
+      if (newUserFlag)
+      {
+         return saveNewUser();
+      }
+      else
+      {
+         return saveExistingUser();
+      }
+   }
+   
+   private String saveNewUser()
+   {      
+      if (!password.equals(confirm))
+      {
+         FacesMessages.instance().addToControl("password", "Passwords do not match");
+         return "failure";
+      }
+      
+      boolean success = identityManager.createUser(username, password, firstname, lastname);
+      
+      if (success)
+      {
+         for (String role : roles)
+         {
+            identityManager.grantRole(username, role);
+         }
+         
+         if (!enabled)
+         {
+            identityManager.disableUser(username);   
+         }
+         
+         Conversation.instance().end();
+         
+         return "success";
+      }
+      
+      return "failure";      
+   }
+   
+   private String saveExistingUser()
+   {
+      // Check if a new password has been entered
+      if (password != null && !"".equals(password))
+      {
+         if (!password.equals(confirm))
+         {
+            FacesMessages.instance().addToControl("password", "Passwords do not match");
+            return "failure";
+         }
+         else
+         {
+            identityManager.changePassword(username, password);
+         }
+      }
+      
+      List<String> grantedRoles = identityManager.getGrantedRoles(username);
+      
+      if (grantedRoles != null)
+      {
+         for (String role : grantedRoles)
+         {
+            if (!roles.contains(role)) identityManager.revokeRole(username, role);
+         }
+      }
+      
+      for (String role : roles)
+      {
+         if (grantedRoles == null || !grantedRoles.contains(role)) 
+         {
+            identityManager.grantRole(username, role);
+         }
+      }
+      
+      if (enabled)
+      {
+         identityManager.enableUser(username);
+      }
+      else
+      {
+         identityManager.disableUser(username);
+      }
+         
+      Conversation.instance().end();
+      return "success";
+   }
+   
+   public String getFirstname()
+   {
+      return firstname;
+   }
+   
+   public void setFirstname(String firstname)
+   {
+      this.firstname = firstname;
+   }
+   
+   public String getLastname()
+   {
+      return lastname;
+   }
+   
+   public void setLastname(String lastname)
+   {
+      this.lastname = lastname;
+   }
+   
+   public String getUsername()
+   {
+      return username;
+   }
+   
+   public void setUsername(String username)
+   {
+      this.username = username;
+   }
+   
+   public String getPassword()
+   {
+      return password;
+   }
+   
+   public void setPassword(String password)
+   {
+      this.password = password;
+   }
+   
+   public String getConfirm()
+   {
+      return confirm;
+   }
+   
+   public void setConfirm(String confirm)
+   {
+      this.confirm = confirm;
+   }
+   
+   public List<String> getRoles()
+   {
+      return roles;
+   }
+   
+   public void setRoles(List<String> roles)
+   {
+      this.roles = roles;
+   }
+   
+   public boolean isEnabled()
+   {
+      return enabled;
+   }
+   
+   public void setEnabled(boolean enabled)
+   {
+      this.enabled = enabled;
+   }
+}
\ No newline at end of file




More information about the seam-commits mailing list