Author: enorman
Date: Fri Mar 19 19:31:12 2010
New Revision: 925392

URL: http://svn.apache.org/viewvc?rev=925392&view=rev
Log:
SLING-1453 Provide AuthorizablePrivilegesInfo service to help user/group 
management scripts query what the current user is allowed to do

Added:
    
sling/trunk/bundles/jcr/jackrabbit-usermanager/src/main/java/org/apache/sling/jackrabbit/usermanager/AuthorizablePrivilegesInfo.java
   (with props)
    
sling/trunk/bundles/jcr/jackrabbit-usermanager/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/AuthorizablePrivilegesInfoImpl.java
   (with props)
    
sling/trunk/launchpad/testing/src/test/java/org/apache/sling/launchpad/webapp/integrationtest/userManager/PrivilegesInfoTest.java
   (with props)
    
sling/trunk/launchpad/testing/src/test/resources/integration-test/usermanager/
    
sling/trunk/launchpad/testing/src/test/resources/integration-test/usermanager/privileges-info.json.esp
Modified:
    sling/trunk/bundles/jcr/jackrabbit-usermanager/pom.xml
    
sling/trunk/launchpad/testing/src/test/java/org/apache/sling/launchpad/webapp/integrationtest/userManager/AbstractUserManagerTest.java

Modified: sling/trunk/bundles/jcr/jackrabbit-usermanager/pom.xml
URL: 
http://svn.apache.org/viewvc/sling/trunk/bundles/jcr/jackrabbit-usermanager/pom.xml?rev=925392&r1=925391&r2=925392&view=diff
==============================================================================
--- sling/trunk/bundles/jcr/jackrabbit-usermanager/pom.xml (original)
+++ sling/trunk/bundles/jcr/jackrabbit-usermanager/pom.xml Fri Mar 19 19:31:12 
2010
@@ -60,8 +60,11 @@
                 <extensions>true</extensions>
                 <configuration>
                     <instructions>
+                                               <Export-Package>
+                            
org.apache.sling.jackrabbit.usermanager;version=${pom.version},
+                                               </Export-Package>
                         <Private-Package>
-                            org.apache.sling.jackrabbit.usermanager.*
+                            org.apache.sling.jackrabbit.usermanager.impl.*
                         </Private-Package>
                     </instructions>
                 </configuration>

Added: 
sling/trunk/bundles/jcr/jackrabbit-usermanager/src/main/java/org/apache/sling/jackrabbit/usermanager/AuthorizablePrivilegesInfo.java
URL: 
http://svn.apache.org/viewvc/sling/trunk/bundles/jcr/jackrabbit-usermanager/src/main/java/org/apache/sling/jackrabbit/usermanager/AuthorizablePrivilegesInfo.java?rev=925392&view=auto
==============================================================================
--- 
sling/trunk/bundles/jcr/jackrabbit-usermanager/src/main/java/org/apache/sling/jackrabbit/usermanager/AuthorizablePrivilegesInfo.java
 (added)
+++ 
sling/trunk/bundles/jcr/jackrabbit-usermanager/src/main/java/org/apache/sling/jackrabbit/usermanager/AuthorizablePrivilegesInfo.java
 Fri Mar 19 19:31:12 2010
@@ -0,0 +1,58 @@
+package org.apache.sling.jackrabbit.usermanager;
+
+import javax.jcr.Session;
+
+public interface AuthorizablePrivilegesInfo {
+
+       /**
+        * Checks whether the current user has been granted privileges
+        * to add a new user.
+        *  
+        * @param jcrSession the JCR session of the current user
+        * @return true if the current user has the privileges, false otherwise
+        */
+       boolean canAddUser(Session jcrSession);
+
+       /**
+        * Checks whether the current user has been granted privileges
+        * to add a new group.
+        *  
+        * @param jcrSession the JCR session of the current user
+        * @return true if the current user has the privileges, false otherwise
+        */
+       boolean canAddGroup(Session jcrSession);
+       
+       /**
+        * Checks whether the current user has been granted privileges
+        * to update the properties of the specified user or group.
+        *  
+        * @param jcrSession the JCR session of the current user
+        * @param principalId the user or group id to check
+        * @return true if the current user has the privileges, false otherwise
+        */
+       boolean canUpdateProperties(Session jcrSession,
+                       String principalId);
+
+       /**
+        * Checks whether the current user has been granted privileges
+        * to remove the specified user or group.
+        *  
+        * @param jcrSession the JCR session of the current user
+        * @param principalId the user or group id to check
+        * @return true if the current user has the privileges, false otherwise
+        */
+       boolean canRemove(Session jcrSession,
+                       String principalId);
+       
+       /**
+        * Checks whether the current user has been granted privileges
+        * to update the membership of the specified group.
+        *  
+        * @param jcrSession the JCR session of the current user
+        * @param groupId the group id to check
+        * @return true if the current user has the privileges, false otherwise
+        */
+       boolean canUpdateGroupMembers(Session jcrSession,
+                       String groupId);
+
+}
\ No newline at end of file

Propchange: 
sling/trunk/bundles/jcr/jackrabbit-usermanager/src/main/java/org/apache/sling/jackrabbit/usermanager/AuthorizablePrivilegesInfo.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: 
sling/trunk/bundles/jcr/jackrabbit-usermanager/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/AuthorizablePrivilegesInfoImpl.java
URL: 
http://svn.apache.org/viewvc/sling/trunk/bundles/jcr/jackrabbit-usermanager/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/AuthorizablePrivilegesInfoImpl.java?rev=925392&view=auto
==============================================================================
--- 
sling/trunk/bundles/jcr/jackrabbit-usermanager/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/AuthorizablePrivilegesInfoImpl.java
 (added)
+++ 
sling/trunk/bundles/jcr/jackrabbit-usermanager/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/AuthorizablePrivilegesInfoImpl.java
 Fri Mar 19 19:31:12 2010
@@ -0,0 +1,306 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.jackrabbit.usermanager.impl;
+
+import java.io.UnsupportedEncodingException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.util.Dictionary;
+
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
+import org.apache.jackrabbit.api.security.user.Authorizable;
+import org.apache.jackrabbit.api.security.user.Group;
+import org.apache.jackrabbit.api.security.user.User;
+import org.apache.jackrabbit.api.security.user.UserManager;
+import org.apache.sling.commons.osgi.OsgiUtil;
+import org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo;
+import org.apache.sling.jcr.base.util.AccessControlUtil;
+import org.osgi.service.component.ComponentContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Helper class to assist in the usage of access control of users/groups from 
scripts.
+ * 
+ * The default access control policy defined by this provider has the following
+ * characteristics:
+ * <ul>
+ * <li>everybody has READ permission to all items,</li>
+ *
+ * <li>every known user is allowed to modify it's own properties except for
+ * her/his group membership,</li>
+ *
+ * <li>members of the 'User administrator' group are allowed to create, modify
+ * and remove users,</li>
+ *
+ * <li>members of the 'Group administrator' group are allowed to create, modify
+ * and remove groups,</li>
+ *
+ * <li>group membership can only be edited by members of the 'Group 
administrator'
+ * and the 'User administrator' group.</li>
+ * </ul>
+ * 
+ * @scr.component immediate="true" metatype="no"
+ * @scr.service
+ *
+ * @scr.property name="service.description" value="User/Group Privileges 
Information"
+ * @scr.property name="service.vendor" value="The Apache Software Foundation"
+ */
+public class AuthorizablePrivilegesInfoImpl implements 
AuthorizablePrivilegesInfo {
+
+    /** default log */
+    private final Logger log = LoggerFactory.getLogger(getClass());
+
+    /**
+     * The name of the configuration parameter providing the 
+     * 'User administrator' group name.
+     *
+     * @scr.property valueRef="DEFAULT_USER_ADMIN_GROUP_NAME"
+     */
+    private static final String PAR_USER_ADMIN_GROUP_NAME = 
"user.admin.group.name";
+
+    /**
+     * The default 'User administrator' group name
+     *
+     * @see #PAR_USER_ADMIN_GROUP_NAME
+     */
+    private static final String DEFAULT_USER_ADMIN_GROUP_NAME = "UserAdmin";
+ 
+    private String userAdminGroupName = DEFAULT_USER_ADMIN_GROUP_NAME;
+
+    /**
+     * The name of the configuration parameter providing the 
+     * 'Group administrator' group name.
+     *
+     * @scr.property valueRef="DEFAULT_GROUP_ADMIN_GROUP_NAME"
+     */
+    private static final String PAR_GROUP_ADMIN_GROUP_NAME = 
"group.admin.group.name";
+
+    /**
+     * The default 'User administrator' group name
+     *
+     * @see #PAR_GROUP_ADMIN_GROUP_NAME
+     */
+    private static final String DEFAULT_GROUP_ADMIN_GROUP_NAME = "GroupAdmin";
+ 
+    private String groupAdminGroupName = DEFAULT_GROUP_ADMIN_GROUP_NAME;
+    
+    
+       /* (non-Javadoc)
+        * @see 
org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo#canAddGroup(javax.jcr.Session)
+        */
+       public boolean canAddGroup(Session jcrSession) {
+               try {
+                       UserManager userManager = 
AccessControlUtil.getUserManager(jcrSession);
+                       Authorizable currentUser = 
userManager.getAuthorizable(jcrSession.getUserID());
+
+                       if (((User)currentUser).isAdmin()) {
+                               return true; //admin user has full control
+                       }
+                       
+                       //check if the user is a member of the 'Group 
administrator' group
+                       Authorizable groupAdmin = 
userManager.getAuthorizable(this.groupAdminGroupName);
+                       if (groupAdmin instanceof Group) {
+                               boolean isMember = 
((Group)groupAdmin).isMember(currentUser);
+                               if (isMember) {
+                                       return true;
+                               }
+                       }
+               } catch (RepositoryException e) {
+                       log.warn("Failed to determine if {} can add a new 
group", jcrSession.getUserID());
+               }
+               return false;
+       }
+
+       /* (non-Javadoc)
+        * @see 
org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo#canAddUser(javax.jcr.Session)
+        */
+       public boolean canAddUser(Session jcrSession) {
+               try {
+                       UserManager userManager = 
AccessControlUtil.getUserManager(jcrSession);
+                       Authorizable currentUser = 
userManager.getAuthorizable(jcrSession.getUserID());
+
+                       if (((User)currentUser).isAdmin()) {
+                               return true; //admin user has full control
+                       }
+                       
+                       //check if the user is a member of the 'User 
administrator' group
+                       Authorizable userAdmin = 
userManager.getAuthorizable(this.userAdminGroupName);
+                       if (userAdmin instanceof Group) {
+                               boolean isMember = 
((Group)userAdmin).isMember(currentUser);
+                               if (isMember) {
+                                       return true;
+                               }
+                       }
+               } catch (RepositoryException e) {
+                       log.warn("Failed to determine if {} can add a new 
user", jcrSession.getUserID());
+               }
+               return false;
+       }
+
+       /* (non-Javadoc)
+        * @see 
org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo#canRemove(javax.jcr.Session,
 java.lang.String)
+        */
+       public boolean canRemove(Session jcrSession, String principalId) {
+               try {
+                       UserManager userManager = 
AccessControlUtil.getUserManager(jcrSession);
+                       Authorizable currentUser = 
userManager.getAuthorizable(jcrSession.getUserID());
+
+                       if (((User)currentUser).isAdmin()) {
+                               return true; //admin user has full control
+                       }
+
+                       Authorizable authorizable = 
userManager.getAuthorizable(principalId);
+                       if (authorizable instanceof User) {
+                               //check if the user is a member of the 'User 
administrator' group
+                               Authorizable userAdmin = 
userManager.getAuthorizable(this.userAdminGroupName);
+                               if (userAdmin instanceof Group) {
+                                       boolean isMember = 
((Group)userAdmin).isMember(currentUser);
+                                       if (isMember) {
+                                               return true;
+                                       }
+                               }
+                       } else if (authorizable instanceof Group) {
+                               //check if the user is a member of the 'Group 
administrator' group
+                               Authorizable groupAdmin = 
userManager.getAuthorizable(this.groupAdminGroupName);
+                               if (groupAdmin instanceof Group) {
+                                       boolean isMember = 
((Group)groupAdmin).isMember(currentUser);
+                                       if (isMember) {
+                                               return true;
+                                       }
+                               }
+                       }
+               } catch (RepositoryException e) {
+                       log.warn("Failed to determine if {} can remove 
authorizable {}", jcrSession.getUserID(), principalId);
+               }
+               return false;
+       }
+
+       /* (non-Javadoc)
+        * @see 
org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo#canUpdateGroupMembers(javax.jcr.Session,
 java.lang.String)
+        */
+       public boolean canUpdateGroupMembers(Session jcrSession, String 
groupId) {
+               try {
+                       UserManager userManager = 
AccessControlUtil.getUserManager(jcrSession);
+                       Authorizable currentUser = 
userManager.getAuthorizable(jcrSession.getUserID());
+
+                       if (((User)currentUser).isAdmin()) {
+                               return true; //admin user has full control
+                       }
+
+                       Authorizable authorizable = 
userManager.getAuthorizable(groupId);
+                       if (authorizable instanceof Group) {
+                               //check if the user is a member of the 'Group 
administrator' group
+                               Authorizable groupAdmin = 
userManager.getAuthorizable(this.groupAdminGroupName);
+                               if (groupAdmin instanceof Group) {
+                                       boolean isMember = 
((Group)groupAdmin).isMember(currentUser);
+                                       if (isMember) {
+                                               return true;
+                                       }
+                               }
+                               
+                               //check if the user is a member of the 'User 
administrator' group
+                               Authorizable userAdmin = 
userManager.getAuthorizable(this.userAdminGroupName);
+                               if (userAdmin instanceof Group) {
+                                       boolean isMember = 
((Group)userAdmin).isMember(currentUser);
+                                       if (isMember) {
+                                               return true;
+                                       }
+                               }
+                       }
+               } catch (RepositoryException e) {
+                       log.warn("Failed to determine if {} can remove 
authorizable {}", jcrSession.getUserID(), groupId);
+               }
+               return false;
+       }
+
+       /* (non-Javadoc)
+        * @see 
org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo#canUpdateProperties(javax.jcr.Session,
 java.lang.String)
+        */
+       public boolean canUpdateProperties(Session jcrSession, String 
principalId) {
+               try {
+                       if (jcrSession.getUserID().equals(principalId)) {
+                               //user is allowed to update it's own properties
+                               return true;
+                       }
+                       
+                       UserManager userManager = 
AccessControlUtil.getUserManager(jcrSession);
+                       Authorizable currentUser = 
userManager.getAuthorizable(jcrSession.getUserID());
+
+                       if (((User)currentUser).isAdmin()) {
+                               return true; //admin user has full control
+                       }
+
+                       Authorizable authorizable = 
userManager.getAuthorizable(principalId);
+                       if (authorizable instanceof User) {
+                               //check if the user is a member of the 'User 
administrator' group
+                               Authorizable userAdmin = 
userManager.getAuthorizable(this.userAdminGroupName);
+                               if (userAdmin instanceof Group) {
+                                       boolean isMember = 
((Group)userAdmin).isMember(currentUser);
+                                       if (isMember) {
+                                               return true;
+                                       }
+                               }
+                       } else if (authorizable instanceof Group) {
+                               //check if the user is a member of the 'Group 
administrator' group
+                               Authorizable groupAdmin = 
userManager.getAuthorizable(this.groupAdminGroupName);
+                               if (groupAdmin instanceof Group) {
+                                       boolean isMember = 
((Group)groupAdmin).isMember(currentUser);
+                                       if (isMember) {
+                                               return true;
+                                       }
+                               }
+                       }
+               } catch (RepositoryException e) {
+                       log.warn("Failed to determine if {} can remove 
authorizable {}", jcrSession.getUserID(), principalId);
+               }
+               return false;
+       }
+
+
+       // ---------- SCR Integration 
----------------------------------------------
+
+    /**
+     * Called by SCR to activate the component.
+     *
+     * @throws InvalidKeyException
+     * @throws NoSuchAlgorithmException
+     * @throws IllegalStateException
+     * @throws UnsupportedEncodingException
+     */
+    protected void activate(ComponentContext componentContext)
+            throws InvalidKeyException, NoSuchAlgorithmException,
+            IllegalStateException, UnsupportedEncodingException {
+
+        Dictionary<?, ?> properties = componentContext.getProperties();
+
+        this.userAdminGroupName = 
OsgiUtil.toString(properties.get(PAR_USER_ADMIN_GROUP_NAME),
+                       DEFAULT_USER_ADMIN_GROUP_NAME);
+        log.info("User Admin Group Name {}", this.userAdminGroupName);
+
+        this.groupAdminGroupName = 
OsgiUtil.toString(properties.get(PAR_GROUP_ADMIN_GROUP_NAME), 
+                       DEFAULT_GROUP_ADMIN_GROUP_NAME);
+        log.info("Group Admin Group Name {}", this.groupAdminGroupName);
+    }
+
+    protected void deactivate(ComponentContext componentContext) {
+       this.userAdminGroupName = DEFAULT_USER_ADMIN_GROUP_NAME;
+       this.groupAdminGroupName = DEFAULT_GROUP_ADMIN_GROUP_NAME;
+    }
+}

Propchange: 
sling/trunk/bundles/jcr/jackrabbit-usermanager/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/AuthorizablePrivilegesInfoImpl.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: 
sling/trunk/launchpad/testing/src/test/java/org/apache/sling/launchpad/webapp/integrationtest/userManager/AbstractUserManagerTest.java
URL: 
http://svn.apache.org/viewvc/sling/trunk/launchpad/testing/src/test/java/org/apache/sling/launchpad/webapp/integrationtest/userManager/AbstractUserManagerTest.java?rev=925392&r1=925391&r2=925392&view=diff
==============================================================================
--- 
sling/trunk/launchpad/testing/src/test/java/org/apache/sling/launchpad/webapp/integrationtest/userManager/AbstractUserManagerTest.java
 (original)
+++ 
sling/trunk/launchpad/testing/src/test/java/org/apache/sling/launchpad/webapp/integrationtest/userManager/AbstractUserManagerTest.java
 Fri Mar 19 19:31:12 2010
@@ -16,6 +16,15 @@
  */
 package org.apache.sling.launchpad.webapp.integrationtest.userManager;
 
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.httpclient.Credentials;
+import org.apache.commons.httpclient.NameValuePair;
+import org.apache.commons.httpclient.UsernamePasswordCredentials;
 import 
org.apache.sling.launchpad.webapp.integrationtest.AbstractAuthenticatedTest;
 
 /**
@@ -23,4 +32,50 @@ import org.apache.sling.launchpad.webapp
  */
 public abstract class AbstractUserManagerTest extends 
AbstractAuthenticatedTest {
 
+       /**
+        * Helper to assist adding a user to a group
+        * @param testUserId the user
+        * @param testGroupId the group
+        */
+       protected void addUserToGroup(String testUserId, String testGroupId) 
throws IOException {
+        String postUrl = HTTP_BASE_URL + "/system/userManager/group/" + 
testGroupId + ".update.html";
+
+               List<NameValuePair> postParams = new ArrayList<NameValuePair>();
+               postParams.add(new NameValuePair(":member", testUserId));
+               
+               Credentials creds = new UsernamePasswordCredentials("admin", 
"admin");
+               assertAuthenticatedPostStatus(creds, postUrl, 
HttpServletResponse.SC_OK, postParams, null);
+       }
+
+       /**
+        * Helper to assist removing a user from a group
+        * @param testUserId the user
+        * @param testGroupId the group
+        */
+       protected void removeUserFromGroup(String testUserId, String 
testGroupId) throws IOException {
+        String postUrl = HTTP_BASE_URL + "/system/userManager/group/" + 
testGroupId + ".update.html";
+
+               List<NameValuePair> postParams = new ArrayList<NameValuePair>();
+               postParams.add(new NameValuePair(":mem...@delete", testUserId));
+               
+               Credentials creds = new UsernamePasswordCredentials("admin", 
"admin");
+               assertAuthenticatedPostStatus(creds, postUrl, 
HttpServletResponse.SC_OK, postParams, null);
+       }
+
+       /**
+        * Add test user to the 'UserAdmin' group
+        * @param testUserId the user
+        */
+       protected void addUserToUserAdminGroup(String testUserId) throws 
IOException {
+               addUserToGroup(testUserId, "UserAdmin");
+       }
+
+       /**
+        * Add test user to the 'GroupAdmin' group
+        * @param testUserId the user
+        */
+       protected void addUserToGroupAdminGroup(String testUserId) throws 
IOException {
+               addUserToGroup(testUserId, "GroupAdmin");
+       }
+       
 }

Added: 
sling/trunk/launchpad/testing/src/test/java/org/apache/sling/launchpad/webapp/integrationtest/userManager/PrivilegesInfoTest.java
URL: 
http://svn.apache.org/viewvc/sling/trunk/launchpad/testing/src/test/java/org/apache/sling/launchpad/webapp/integrationtest/userManager/PrivilegesInfoTest.java?rev=925392&view=auto
==============================================================================
--- 
sling/trunk/launchpad/testing/src/test/java/org/apache/sling/launchpad/webapp/integrationtest/userManager/PrivilegesInfoTest.java
 (added)
+++ 
sling/trunk/launchpad/testing/src/test/java/org/apache/sling/launchpad/webapp/integrationtest/userManager/PrivilegesInfoTest.java
 Fri Mar 19 19:31:12 2010
@@ -0,0 +1,371 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.launchpad.webapp.integrationtest.userManager;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.httpclient.Credentials;
+import org.apache.commons.httpclient.NameValuePair;
+import org.apache.commons.httpclient.UsernamePasswordCredentials;
+import org.apache.sling.commons.json.JSONException;
+import org.apache.sling.commons.json.JSONObject;
+
+/**
+ * Tests for the PrivilegesInfo Script Helper
+ */
+public class PrivilegesInfoTest extends AbstractUserManagerTest {
+       
+       String testUserId = null;
+       String testUserId2 = null;
+       String testGroupId = null;
+       String testFolderUrl = null;
+    Set<String> toDelete = new HashSet<String>();
+       
+       @Override
+       protected void setUp() throws Exception {
+               super.setUp();
+
+        // Script for server-side PrivilegeInfo calculations
+        String scriptPath = "/apps/sling/servlet/default";
+        testClient.mkdirs(WEBDAV_BASE_URL, scriptPath);
+        toDelete.add(uploadTestScript(scriptPath,
+                                       "usermanager/privileges-info.json.esp",
+                                       "privileges-info.json.esp"));
+       }
+
+       @Override
+       protected void tearDown() throws Exception {
+               super.tearDown();
+
+               Credentials creds = new UsernamePasswordCredentials("admin", 
"admin");
+
+               if (testFolderUrl != null) {
+                       //remove the test user if it exists.
+                       String postUrl = testFolderUrl;
+                       List<NameValuePair> postParams = new 
ArrayList<NameValuePair>();
+                       postParams.add(new NameValuePair(":operation", 
"delete"));
+                       assertAuthenticatedPostStatus(creds, postUrl, 
HttpServletResponse.SC_OK, postParams, null);
+               }
+               if (testGroupId != null) {
+                       //remove the test user if it exists.
+                       String postUrl = HTTP_BASE_URL + 
"/system/userManager/group/" + testGroupId + ".delete.html";
+                       List<NameValuePair> postParams = new 
ArrayList<NameValuePair>();
+                       assertAuthenticatedPostStatus(creds, postUrl, 
HttpServletResponse.SC_OK, postParams, null);
+               }
+               if (testUserId != null) {
+                       //remove the test user if it exists.
+                       String postUrl = HTTP_BASE_URL + 
"/system/userManager/user/" + testUserId + ".delete.html";
+                       List<NameValuePair> postParams = new 
ArrayList<NameValuePair>();
+                       assertAuthenticatedPostStatus(creds, postUrl, 
HttpServletResponse.SC_OK, postParams, null);
+               }
+               if (testUserId2 != null) {
+                       //remove the test user if it exists.
+                       String postUrl = HTTP_BASE_URL + 
"/system/userManager/user/" + testUserId2 + ".delete.html";
+                       List<NameValuePair> postParams = new 
ArrayList<NameValuePair>();
+                       assertAuthenticatedPostStatus(creds, postUrl, 
HttpServletResponse.SC_OK, postParams, null);
+               }
+               
+        for(String script : toDelete) {
+            testClient.delete(script);
+        }
+       }
+       
+       
+       /**
+        * Checks whether the current user has been granted privileges
+        * to add a new user.
+        */
+       public void testCanAddUser() throws JSONException, IOException {
+               testUserId = createTestUser();
+
+               String getUrl = HTTP_BASE_URL + "/system/userManager/user/" + 
testUserId + ".privileges-info.json";
+
+               //fetch the JSON for the test page to verify the settings.
+               Credentials testUserCreds = new 
UsernamePasswordCredentials(testUserId, "testPwd");
+
+               String json = getAuthenticatedContent(testUserCreds, getUrl, 
CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
+               assertNotNull(json);
+               JSONObject jsonObj = new JSONObject(json);
+               
+               assertEquals(false, jsonObj.getBoolean("canAddUser"));
+               
+               //now add the user to the 'User Admin' group.
+               addUserToUserAdminGroup(testUserId);
+               
+               //fetch the JSON again
+               String json2 = getAuthenticatedContent(testUserCreds, getUrl, 
CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
+               assertNotNull(json2);
+               JSONObject jsonObj2 = new JSONObject(json2);
+               
+               assertEquals(true, jsonObj2.getBoolean("canAddUser"));
+       }
+
+       /**
+        * Checks whether the current user has been granted privileges
+        * to add a new group.
+        */
+       public void testCanAddGroup() throws IOException, JSONException {
+               testUserId = createTestUser();
+
+               String getUrl = HTTP_BASE_URL + "/system/userManager/user/" + 
testUserId + ".privileges-info.json";
+
+               //fetch the JSON for the test page to verify the settings.
+               Credentials testUserCreds = new 
UsernamePasswordCredentials(testUserId, "testPwd");
+
+               String json = getAuthenticatedContent(testUserCreds, getUrl, 
CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
+               assertNotNull(json);
+               JSONObject jsonObj = new JSONObject(json);
+               
+               assertEquals(false, jsonObj.getBoolean("canAddGroup"));
+               
+               //now add the user to the 'Group Admin' group.
+               addUserToGroupAdminGroup(testUserId);
+               
+               //fetch the JSON again
+               String json2 = getAuthenticatedContent(testUserCreds, getUrl, 
CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
+               assertNotNull(json2);
+               JSONObject jsonObj2 = new JSONObject(json2);
+               
+               assertEquals(true, jsonObj2.getBoolean("canAddGroup"));
+       }
+       
+       /**
+        * Checks whether the current user has been granted privileges
+        * to update the properties of the specified user.
+        */
+       public void testCanUpdateUserProperties() throws IOException, 
JSONException {
+               testUserId = createTestUser();
+
+               //1. verify user can update thier own properties
+               String getUrl = HTTP_BASE_URL + "/system/userManager/user/" + 
testUserId + ".privileges-info.json";
+
+               //fetch the JSON for the test page to verify the settings.
+               Credentials testUserCreds = new 
UsernamePasswordCredentials(testUserId, "testPwd");
+
+               String json = getAuthenticatedContent(testUserCreds, getUrl, 
CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
+               assertNotNull(json);
+               JSONObject jsonObj = new JSONObject(json);
+               
+               //user can update their own properties
+               assertEquals(true, jsonObj.getBoolean("canUpdateProperties"));
+               
+               
+               //2. now try another user 
+               testUserId2 = createTestUser();
+
+               //fetch the JSON for the test page to verify the settings.
+               Credentials testUser2Creds = new 
UsernamePasswordCredentials(testUserId2, "testPwd");
+
+               String json2 = getAuthenticatedContent(testUser2Creds, getUrl, 
CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
+               assertNotNull(json2);
+               JSONObject jsonObj2 = new JSONObject(json2);
+               
+               //user can not update other users properties
+               assertEquals(false, jsonObj2.getBoolean("canUpdateProperties"));
+               
+               
+               //3. now add the user to the 'User Admin' group.
+               addUserToUserAdminGroup(testUserId2);
+               
+               //fetch the JSON again
+               String json3 = getAuthenticatedContent(testUser2Creds, getUrl, 
CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
+               assertNotNull(json3);
+               JSONObject jsonObj3 = new JSONObject(json3);
+               
+               //user in 'User Admin' group can update the properties of other 
users
+               assertEquals(true, jsonObj3.getBoolean("canUpdateProperties"));
+       }
+
+       /**
+        * Checks whether the current user has been granted privileges
+        * to update the properties of the specified group.
+        */
+       public void testCanUpdateGroupProperties() throws IOException, 
JSONException {
+               testGroupId = createTestGroup();
+               testUserId = createTestUser();
+
+               //1. Verify non admin user can not update group properties
+               String getUrl = HTTP_BASE_URL + "/system/userManager/group/" + 
testGroupId + ".privileges-info.json";
+
+               //fetch the JSON for the test page to verify the settings.
+               Credentials testUserCreds = new 
UsernamePasswordCredentials(testUserId, "testPwd");
+
+               String json = getAuthenticatedContent(testUserCreds, getUrl, 
CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
+               assertNotNull(json);
+               JSONObject jsonObj = new JSONObject(json);
+               
+               //normal user can not update group properties
+               assertEquals(false, jsonObj.getBoolean("canUpdateProperties"));
+               
+
+               //2. now add the user to the 'Group Admin' group.
+               addUserToGroupAdminGroup(testUserId);
+               
+               //fetch the JSON again
+               String json2 = getAuthenticatedContent(testUserCreds, getUrl, 
CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
+               assertNotNull(json2);
+               JSONObject jsonObj2 = new JSONObject(json2);
+               
+               //user in 'Group Admin' group can update the properties of 
groups
+               assertEquals(true, jsonObj2.getBoolean("canUpdateProperties"));
+       }
+       
+       /**
+        * Checks whether the current user has been granted privileges
+        * to remove the specified user.
+        */
+       public void testCanRemoveUser() throws IOException, JSONException {
+               testUserId = createTestUser();
+
+               //1. verify user can not remove themselves
+               String getUrl = HTTP_BASE_URL + "/system/userManager/user/" + 
testUserId + ".privileges-info.json";
+
+               //fetch the JSON for the test page to verify the settings.
+               Credentials testUserCreds = new 
UsernamePasswordCredentials(testUserId, "testPwd");
+
+               String json = getAuthenticatedContent(testUserCreds, getUrl, 
CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
+               assertNotNull(json);
+               JSONObject jsonObj = new JSONObject(json);
+               
+               //user can not remove themselves
+               assertEquals(false, jsonObj.getBoolean("canRemove"));
+               
+               
+               //2. now try another user 
+               testUserId2 = createTestUser();
+
+               //fetch the JSON for the test page to verify the settings.
+               Credentials testUser2Creds = new 
UsernamePasswordCredentials(testUserId2, "testPwd");
+
+               String json2 = getAuthenticatedContent(testUser2Creds, getUrl, 
CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
+               assertNotNull(json2);
+               JSONObject jsonObj2 = new JSONObject(json2);
+               
+               //user can not delete other users
+               assertEquals(false, jsonObj2.getBoolean("canRemove"));
+               
+               
+               //3. now add the user to the 'User Admin' group.
+               addUserToUserAdminGroup(testUserId2);
+               
+               //fetch the JSON again
+               String json3 = getAuthenticatedContent(testUser2Creds, getUrl, 
CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
+               assertNotNull(json3);
+               JSONObject jsonObj3 = new JSONObject(json3);
+               
+               //user in 'User Admin' group can remove other users
+               assertEquals(true, jsonObj3.getBoolean("canRemove"));
+       }
+
+       /**
+        * Checks whether the current user has been granted privileges
+        * to remove the specified group.
+        */
+       public void testCanRemoveGroup() throws IOException, JSONException {
+               testGroupId = createTestGroup();
+               testUserId = createTestUser();
+
+               //1. Verify non admin user can not remove group
+               String getUrl = HTTP_BASE_URL + "/system/userManager/group/" + 
testGroupId + ".privileges-info.json";
+
+               //fetch the JSON for the test page to verify the settings.
+               Credentials testUserCreds = new 
UsernamePasswordCredentials(testUserId, "testPwd");
+
+               String json = getAuthenticatedContent(testUserCreds, getUrl, 
CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
+               assertNotNull(json);
+               JSONObject jsonObj = new JSONObject(json);
+               
+               //normal user can not remove group
+               assertEquals(false, jsonObj.getBoolean("canRemove"));
+               
+
+               //2. now add the user to the 'Group Admin' group.
+               addUserToGroupAdminGroup(testUserId);
+               
+               //fetch the JSON again
+               String json2 = getAuthenticatedContent(testUserCreds, getUrl, 
CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
+               assertNotNull(json2);
+               JSONObject jsonObj2 = new JSONObject(json2);
+               
+               //user in 'Group Admin' group can update the properties of 
groups
+               assertEquals(true, jsonObj2.getBoolean("canRemove"));
+       }
+       
+       /**
+        * Checks whether the current user has been granted privileges
+        * to update the membership of the specified group.
+        */
+       public void testCanUpdateGroupMembers() throws IOException, 
JSONException {
+               testGroupId = createTestGroup();
+               testUserId = createTestUser();
+
+               //1. Verify non admin user can not update group membership
+               String getUrl = HTTP_BASE_URL + "/system/userManager/group/" + 
testGroupId + ".privileges-info.json";
+
+               //fetch the JSON for the test page to verify the settings.
+               Credentials testUserCreds = new 
UsernamePasswordCredentials(testUserId, "testPwd");
+
+               String json = getAuthenticatedContent(testUserCreds, getUrl, 
CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
+               assertNotNull(json);
+               JSONObject jsonObj = new JSONObject(json);
+               
+               //normal user can not remove group
+               assertEquals(false, 
jsonObj.getBoolean("canUpdateGroupMembers"));
+               
+
+               //2. now add the user to the 'Group Admin' group.
+               addUserToGroupAdminGroup(testUserId);
+               
+               //fetch the JSON again
+               String json2 = getAuthenticatedContent(testUserCreds, getUrl, 
CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
+               assertNotNull(json2);
+               JSONObject jsonObj2 = new JSONObject(json2);
+               
+               //user in 'Group Admin' group can update the membership of 
groups
+               assertEquals(true, 
jsonObj2.getBoolean("canUpdateGroupMembers"));
+               
+               
+               //3. remove user from the 'Group Admin' group
+               removeUserFromGroup(testUserId, "GroupAdmin");
+       
+               //fetch the JSON again
+               String json3 = getAuthenticatedContent(testUserCreds, getUrl, 
CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
+               assertNotNull(json3);
+               JSONObject jsonObj3 = new JSONObject(json3);
+               
+               //user not in 'Group Admin' group can not update the membership 
of groups
+               assertEquals(false, 
jsonObj3.getBoolean("canUpdateGroupMembers"));
+               
+               
+               //4. add user to the 'User Admin' group
+               addUserToUserAdminGroup(testUserId);
+
+               //fetch the JSON again
+               String json4 = getAuthenticatedContent(testUserCreds, getUrl, 
CONTENT_TYPE_JSON, null, HttpServletResponse.SC_OK);
+               assertNotNull(json4);
+               JSONObject jsonObj4 = new JSONObject(json4);
+               
+               //user in 'User Admin' group can update the membership of groups
+               assertEquals(true, 
jsonObj4.getBoolean("canUpdateGroupMembers"));
+       }
+}

Propchange: 
sling/trunk/launchpad/testing/src/test/java/org/apache/sling/launchpad/webapp/integrationtest/userManager/PrivilegesInfoTest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: 
sling/trunk/launchpad/testing/src/test/resources/integration-test/usermanager/privileges-info.json.esp
URL: 
http://svn.apache.org/viewvc/sling/trunk/launchpad/testing/src/test/resources/integration-test/usermanager/privileges-info.json.esp?rev=925392&view=auto
==============================================================================
--- 
sling/trunk/launchpad/testing/src/test/resources/integration-test/usermanager/privileges-info.json.esp
 (added)
+++ 
sling/trunk/launchpad/testing/src/test/resources/integration-test/usermanager/privileges-info.json.esp
 Fri Mar 19 19:31:12 2010
@@ -0,0 +1,11 @@
+{
+<% 
+   var privilegesInfo = 
sling.getService(Packages.org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo);
+   var authorizable = 
resource.adaptTo(Packages.org.apache.jackrabbit.api.security.user.Authorizable);
+%>
+       "canAddUser" : <%=privilegesInfo.canAddUser(currentSession)%>,
+       "canAddGroup" : <%=privilegesInfo.canAddGroup(currentSession)%>,
+       "canUpdateProperties" : 
<%=privilegesInfo.canUpdateProperties(currentSession, authorizable.getID())%>,
+       "canRemove" : <%=privilegesInfo.canRemove(currentSession, 
authorizable.getID())%>,
+       "canUpdateGroupMembers" : 
<%=privilegesInfo.canUpdateGroupMembers(currentSession, authorizable.getID())%>
+}


Reply via email to