[ckan-changes] commit/ckan: 5 new changesets

Bitbucket commits-noreply at bitbucket.org
Tue May 24 22:32:35 UTC 2011


5 new changesets in ckan:

http://bitbucket.org/okfn/ckan/changeset/8e611386e33b/
changeset:   r3107:8e611386e33b
branch:      feature-1074-authz-wui
user:        John Lawrence Aspden
date:        2011-05-18 00:13:22
summary:     [authz][s]: changing authorization pages for both group and authorization group by copying the code from package.py
affected #:  4 files (10.9 KB)

--- a/ckan/controllers/authorization_group.py	Tue May 17 10:15:11 2011 +0100
+++ b/ckan/controllers/authorization_group.py	Tue May 17 23:13:22 2011 +0100
@@ -142,85 +142,214 @@
             h.redirect_to(action='read', id=c.authorization_group_name)
 
     def authz(self, id):
-        c.authorization_group = model.AuthorizationGroup.by_name(id)
-        if c.authorization_group is None:
+        authorization_group = model.AuthorizationGroup.by_name(id)
+        if authorization_group is None:
             abort(404, _('Group not found'))
-        c.authorization_group_name = c.authorization_group.name
-        
+
+        c.authorization_group_name = authorization_group.name
+
         c.authz_editable = self.authorizer.am_authorized(c, model.Action.EDIT_PERMISSIONS, 
-                                                         c.authorization_group)
+                                                         authorization_group)
+
         if not c.authz_editable:
-            abort(401, _('Not authorized to edit authorization for group'))
+            abort(401, gettext('User %r not authorized to edit %s authorizations') % (c.user, id))
 
-        if 'save' in request.params: # form posted
-            # needed because request is nested
-            # multidict which is read only
-            params = dict(request.params)
-            c.fs = ckan.forms.get_authz_fieldset('authorization_group_authz_fs').bind(
-                                                 c.authorization_group.roles, 
-                                                 data=params or None)
-            try:
-                self._update_authz(c.fs)
-            except ValidationException, error:
-                # TODO: sort this out 
-                # fs = error.args[0]
-                # return render('group/authz.html')
-                raise
-            # now do new roles
-            newrole_user_id = request.params.get('AuthorizationGroupRole--user_id')
-            newrole_authzgroup_id = request.params.get('AuthorizationGroupRole--authorized_group_id')
-            if newrole_user_id != '__null_value__' and newrole_authzgroup_id != '__null_value__':
-                c.message = _(u'Please select either a user or an authorization group, not both.')
-            elif newrole_user_id != '__null_value__':
-                user = model.Session.query(model.User).get(newrole_user_id)
-                # TODO: chech user is not None (should go in validation ...)
-                role = request.params.get('AuthorizationGroupRole--role')
-                newauthzgrouprole = model.AuthorizationGroupRole(user=user, 
-                        authorization_group=c.authorization_group, role=role)
-                # With FA no way to get new GroupRole back to set group attribute
-                # new_roles = ckan.forms.new_roles_fs.bind(model.GroupRole, data=params or None)
-                # new_roles.sync()
-                model.Session.commit()
-                model.Session.remove()
-                c.message = _(u'Added role \'%s\' for user \'%s\'') % (
-                    newauthzgrouprole.role,
-                    newauthzgrouprole.user.name)      
-            elif newrole_authzgroup_id != '__null_value__':
-                authzgroup = model.Session.query(model.AuthorizationGroup).get(newrole_authzgroup_id)
-                # TODO: chech user is not None (should go in validation ...)
-                role = request.params.get('AuthorizationGroupRole--role')
-                newauthzgrouprole = model.AuthorizationGroupRole(authorized_group=authzgroup, 
-                        authorization_group=c.authorization_group, role=role)
-                # With FA no way to get new GroupRole back to set group attribute
-                # new_roles = ckan.forms.new_roles_fs.bind(model.GroupRole, data=params or None)
-                # new_roles.sync()
-                model.Session.commit()
-                model.Session.remove()
-                c.message = _(u'Added role \'%s\' for authorization group \'%s\'') % (
-                    newauthzgrouprole.role,
-                    newauthzgrouprole.authorized_group.name)
-        elif 'role_to_delete' in request.params:
-            authzgrouprole_id = request.params['role_to_delete']
-            authzgrouprole = model.Session.query(model.AuthorizationGroupRole).get(authzgrouprole_id)
-            if authzgrouprole is None:
-                c.error = _(u'Error: No role found with that id')
+        #see package.py for comments
+        def get_userobjectroles():
+            authorization_group = model.AuthorizationGroup.by_name(id)
+            uors = model.Session.query(model.AuthorizationGroupRole).join('authorization_group').filter_by(name=authorization_group.name).all()
+            return uors
+
+        def action_save_form(users_or_authz_groups):
+            # The permissions grid has been saved
+            # which is a grid of checkboxes named user$role
+            rpi = request.params.items()
+
+            # The grid passes us a list of the users/roles that were displayed
+            submitted = [ a for (a,b) in rpi if (b == u'submitted')]
+            # and also those which were checked
+            checked = [ a for (a,b) in rpi if (b == u'on')]
+
+            # from which we can deduce true/false for each user/role combination
+            # that was displayed in the form
+            table_dict={}
+            for a in submitted:
+                table_dict[a]=False
+            for a in checked:
+                table_dict[a]=True
+
+            # now we'll split up the user$role strings to make a dictionary from 
+            # (user,role) to True/False, which tells us what we need to do.
+            new_user_role_dict={}
+            for (ur,val) in table_dict.items():
+                u,r = ur.split('$')
+                new_user_role_dict[(u,r)] = val
+               
+            # we get the current user/role assignments 
+            # and make a dictionary of them
+            current_uors = get_userobjectroles()
+
+            if users_or_authz_groups=='users':
+                current_users_roles = [( uor.user.name, uor.role) for uor in current_uors if uor.user]
+            elif users_or_authz_groups=='authz_groups':
+                current_users_roles = [( uor.authorized_group.name, uor.role) for uor in current_uors if uor.authorized_group]        
             else:
-                authzgrouprole.purge()
-                if authzgrouprole.user:
-                    c.message = _(u'Deleted role \'%s\' for user \'%s\'') % \
-                                (authzgrouprole.role, authzgrouprole.user.name)
-                elif authzgrouprole.authorized_group:
-                    c.message = _(u'Deleted role \'%s\' for authorization group \'%s\'') % \
-                                (authzgrouprole.role, authzgrouprole.authorized_group.name)
-                model.Session.commit()
+                assert False, "shouldn't be here"
 
-        # retrieve group again ...
-        c.authorization_group = model.AuthorizationGroup.by_name(id)
-        fs = ckan.forms.get_authz_fieldset('authorization_group_authz_fs')\
-                .bind(c.authorization_group.roles)
-        c.form = fs.render()
-        c.new_roles_form = \
-            ckan.forms.get_authz_fieldset('new_authorization_group_roles_fs').render()
+            current_user_role_dict={}
+            for (u,r) in current_users_roles:
+                current_user_role_dict[(u,r)]=True
+
+            # and now we can loop through our dictionary of desired states
+            # checking whether a change needs to be made, and if so making it
+
+            # Here we check whether someone is already assigned a role, in order
+            # to avoid assigning it twice, or attempting to delete it when it
+            # doesn't exist. Otherwise problems can occur.
+            if users_or_authz_groups=='users':
+                for ((u,r), val) in new_user_role_dict.items():
+                    if val:
+                        if not ((u,r) in current_user_role_dict):
+                            model.add_user_to_role(model.User.by_name(u),r,authorization_group)
+                    else:
+                        if ((u,r) in current_user_role_dict):
+                            model.remove_user_from_role(model.User.by_name(u),r,authorization_group)
+            elif users_or_authz_groups=='authz_groups':
+                for ((u,r), val) in new_user_role_dict.items():
+                    if val:
+                        if not ((u,r) in current_user_role_dict):
+                            model.add_authorization_group_to_role(model.AuthorizationGroup.by_name(u),r,authorization_group)
+                    else:
+                        if ((u,r) in current_user_role_dict):
+                            model.remove_authorization_group_from_role(model.AuthorizationGroup.by_name(u),r,authorization_group)
+            else:
+                assert False, "shouldn't be here"
+
+            # finally commit the change to the database
+            model.repo.commit_and_remove()
+            h.flash_success("Changes Saved")
+
+
+
+        def action_add_form(users_or_authz_groups):
+            # The user is attempting to set new roles for a named user
+            new_user = request.params.get('new_user_name')
+            # this is the list of roles whose boxes were ticked
+            checked_roles = [ a for (a,b) in request.params.items() if (b == u'on')]
+            # this is the list of all the roles that were in the submitted form
+            submitted_roles = [ a for (a,b) in request.params.items() if (b == u'submitted')]
+
+            # from this we can make a dictionary of the desired states
+            # i.e. true for the ticked boxes, false for the unticked
+            desired_roles = {}
+            for r in submitted_roles:
+                desired_roles[r]=False
+            for r in checked_roles:
+                desired_roles[r]=True
+
+            # again, in order to avoid either creating a role twice or deleting one which is
+            # non-existent, we need to get the users' current roles (if any)
+  
+            current_uors = get_userobjectroles()
+
+            if users_or_authz_groups=='users':
+                current_roles = [uor.role for uor in current_uors if ( uor.user and uor.user.name == new_user )]
+                user_object = model.User.by_name(new_user)
+                if user_object==None:
+                    # The submitted user does not exist. Bail with flash message
+                    h.flash_error('unknown user:' + str (new_user))
+                else:
+                    # Whenever our desired state is different from our current state, change it.
+                    for (r,val) in desired_roles.items():
+                        if val:
+                            if (r not in current_roles):
+                                model.add_user_to_role(user_object, r, authorization_group)
+                        else:
+                            if (r in current_roles):
+                                model.remove_user_from_role(user_object, r, authorization_group)
+                    h.flash_success("User Added")
+
+            elif users_or_authz_groups=='authz_groups':
+                current_roles = [uor.role for uor in current_uors if ( uor.authorized_group and uor.authorized_group.name == new_user )]
+                user_object = model.AuthorizationGroup.by_name(new_user)
+                if user_object==None:
+                    # The submitted user does not exist. Bail with flash message
+                    h.flash_error('unknown authorization group:' + str (new_user))
+                else:
+                    # Whenever our desired state is different from our current state, change it.
+                    for (r,val) in desired_roles.items():
+                        if val:
+                            if (r not in current_roles):
+                                model.add_authorization_group_to_role(user_object, r, authorization_group)
+                        else:
+                            if (r in current_roles):
+                                model.remove_authorization_group_from_role(user_object, r, authorization_group)
+                    h.flash_success("Authorization Group Added")
+
+            else:
+                assert False, "shouldn't be here"
+
+            # and finally commit all these changes to the database
+            model.repo.commit_and_remove()
+
+
+        # In the event of a post request, work out which of the four possible actions
+        # is to be done, and do it before displaying the page
+        if 'add' in request.POST:
+            action_add_form('users')
+
+        if 'authz_add' in request.POST:
+            action_add_form('authz_groups')
+
+        if 'save' in request.POST:
+            action_save_form('users')
+
+        if 'authz_save' in request.POST:
+            action_save_form('authz_groups')
+
+        # =================
+        # Display the page
+
+        # Find out all the possible roles. At the moment, any role can be
+        # associated with any object, so that's easy:
+        possible_roles = model.Role.get_all()
+
+        # get the list of users who have roles on this object, with their roles
+        uors = get_userobjectroles()
+
+        # uniquify and sort
+        users = sorted(list(set([uor.user.name for uor in uors if uor.user])))
+        authz_groups = sorted(list(set([uor.authorized_group.name for uor in uors if uor.authorized_group])))
+
+        # make a dictionary from (user, role) to True, False
+        users_roles = [( uor.user.name, uor.role) for uor in uors if uor.user]
+        user_role_dict={}
+        for u in users:
+            for r in possible_roles:
+                if (u,r) in users_roles:
+                    user_role_dict[(u,r)]=True
+                else:
+                    user_role_dict[(u,r)]=False
+
+        # and similarly make a dictionary from (authz_group, role) to True, False
+        authz_groups_roles = [( uor.authorized_group.name, uor.role) for uor in uors if uor.authorized_group]
+        authz_groups_role_dict={}
+        for u in authz_groups:
+            for r in possible_roles:
+                if (u,r) in authz_groups_roles:
+                    authz_groups_role_dict[(u,r)]=True
+                else:
+                    authz_groups_role_dict[(u,r)]=False
+
+        # pass these variables to the template for rendering
+        c.roles = possible_roles
+
+        c.users = users
+        c.user_role_dict = user_role_dict
+
+        c.authz_groups = authz_groups
+        c.authz_groups_role_dict = authz_groups_role_dict
+
         return render('authorization_group/authz.html')
 
     def _render_edit_form(self, fs):


--- a/ckan/controllers/group.py	Tue May 17 10:15:11 2011 +0100
+++ b/ckan/controllers/group.py	Tue May 17 23:13:22 2011 +0100
@@ -161,91 +161,222 @@
             h.redirect_to(action='read', id=c.groupname)
 
     def authz(self, id):
-        c.group = model.Group.get(id)
-        if c.group is None:
+        group = model.Group.get(id)
+        if group is None:
             abort(404, _('Group not found'))
-        
-        c.groupname = c.group.name
-        c.grouptitle = c.group.display_name
+        c.groupname = group.name
+        c.grouptitle = group.display_name
 
-        c.authz_editable = self.authorizer.am_authorized(c, model.Action.EDIT_PERMISSIONS, c.group)
+        c.authz_editable = self.authorizer.am_authorized(c, model.Action.EDIT_PERMISSIONS, group)
         if not c.authz_editable:
-            abort(401, _('Not authorized to edit authorization for group'))
+            abort(401, gettext('User %r not authorized to edit %s authorizations') % (c.user, id))
 
-        if 'save' in request.params: # form posted
-            # needed because request is nested
-            # multidict which is read only
-            params = dict(request.params)
-            c.fs = ckan.forms.get_authz_fieldset('group_authz_fs').bind(c.group.roles, data=params or None)
-            try:
-                self._update_authz(c.fs)
-            except ValidationException, error:
-                # TODO: sort this out 
-                # fs = error.args[0]
-                # return render('group/authz.html')
-                raise
-            # now do new roles
-            newrole_user_id = request.params.get('GroupRole--user_id')
-            newrole_authzgroup_id = request.params.get('GroupRole--authorized_group_id')
-            if newrole_user_id != '__null_value__' and newrole_authzgroup_id != '__null_value__':
-                c.message = _(u'Please select either a user or an authorization group, not both.')
-            elif newrole_user_id != '__null_value__':
-                user = model.Session.query(model.User).get(newrole_user_id)
-                # TODO: chech user is not None (should go in validation ...)
-                role = request.params.get('GroupRole--role')
-                newgrouprole = model.GroupRole(user=user, group=c.group,
-                        role=role)
-                # With FA no way to get new GroupRole back to set group attribute
-                # new_roles = ckan.forms.new_roles_fs.bind(model.GroupRole, data=params or None)
-                # new_roles.sync()
-                for extension in self.extensions:
-                    extension.authz_add_role(newgrouprole)
-                model.Session.commit()
-                model.Session.remove()
-                c.message = _(u'Added role \'%s\' for user \'%s\'') % (
-                    newgrouprole.role,
-                    newgrouprole.user.display_name)
-            elif newrole_authzgroup_id != '__null_value__':
-                authzgroup = model.Session.query(model.AuthorizationGroup).get(newrole_authzgroup_id)
-                # TODO: chech user is not None (should go in validation ...)
-                role = request.params.get('GroupRole--role')
-                newgrouprole = model.GroupRole(authorized_group=authzgroup, 
-                        group=c.group, role=role)
-                # With FA no way to get new GroupRole back to set group attribute
-                # new_roles = ckan.forms.new_roles_fs.bind(model.GroupRole, data=params or None)
-                # new_roles.sync()
-                for extension in self.extensions:
-                    extensions.authz_add_role(newgrouprole)
-                model.Session.commit()
-                model.Session.remove()
-                c.message = _(u'Added role \'%s\' for authorization group \'%s\'') % (
-                    newgrouprole.role,
-                    newgrouprole.authorized_group.name)
-        elif 'role_to_delete' in request.params:
-            grouprole_id = request.params['role_to_delete']
-            grouprole = model.Session.query(model.GroupRole).get(grouprole_id)
-            if grouprole is None:
-                c.error = _(u'Error: No role found with that id')
+
+        #see package.py for comments
+        def get_userobjectroles():
+            group = model.Group.get(id)
+            uors = model.Session.query(model.GroupRole).join('group').filter_by(name=group.name).all()
+            return uors
+
+        def action_save_form(users_or_authz_groups):
+            # The permissions grid has been saved
+            # which is a grid of checkboxes named user$role
+            rpi = request.params.items()
+
+            # The grid passes us a list of the users/roles that were displayed
+            submitted = [ a for (a,b) in rpi if (b == u'submitted')]
+            # and also those which were checked
+            checked = [ a for (a,b) in rpi if (b == u'on')]
+
+            # from which we can deduce true/false for each user/role combination
+            # that was displayed in the form
+            table_dict={}
+            for a in submitted:
+                table_dict[a]=False
+            for a in checked:
+                table_dict[a]=True
+
+            # now we'll split up the user$role strings to make a dictionary from 
+            # (user,role) to True/False, which tells us what we need to do.
+            new_user_role_dict={}
+            for (ur,val) in table_dict.items():
+                u,r = ur.split('$')
+                new_user_role_dict[(u,r)] = val
+               
+            # we get the current user/role assignments 
+            # and make a dictionary of them
+            current_uors = get_userobjectroles()
+
+            if users_or_authz_groups=='users':
+                current_users_roles = [( uor.user.name, uor.role) for uor in current_uors if uor.user]
+            elif users_or_authz_groups=='authz_groups':
+                current_users_roles = [( uor.authorized_group.name, uor.role) for uor in current_uors if uor.authorized_group]        
             else:
-                for extension in self.extensions:
-                    extension.authz_remove_role(grouprole)
-                grouprole.purge()
-                if grouprole.user:
-                    c.message = _(u'Deleted role \'%s\' for user \'%s\'') % \
-                                (grouprole.role, grouprole.user.display_name)
-                elif grouprole.authorized_group:
-                    c.message = _(u'Deleted role \'%s\' for authorization group \'%s\'') % \
-                                (grouprole.role, grouprole.authorized_group.name)
-                model.Session.commit()
+                assert False, "shouldn't be here"
 
-        # retrieve group again ...
-        c.group = model.Group.get(id)
-        fs = ckan.forms.get_authz_fieldset('group_authz_fs').bind(c.group.roles)
-        c.form = fs.render()
-        c.new_roles_form = \
-            ckan.forms.get_authz_fieldset('new_group_roles_fs').render()
+            current_user_role_dict={}
+            for (u,r) in current_users_roles:
+                current_user_role_dict[(u,r)]=True
+
+            # and now we can loop through our dictionary of desired states
+            # checking whether a change needs to be made, and if so making it
+
+            # Here we check whether someone is already assigned a role, in order
+            # to avoid assigning it twice, or attempting to delete it when it
+            # doesn't exist. Otherwise problems can occur.
+            if users_or_authz_groups=='users':
+                for ((u,r), val) in new_user_role_dict.items():
+                    if val:
+                        if not ((u,r) in current_user_role_dict):
+                            model.add_user_to_role(model.User.by_name(u),r,group)
+                    else:
+                        if ((u,r) in current_user_role_dict):
+                            model.remove_user_from_role(model.User.by_name(u),r,group)
+            elif users_or_authz_groups=='authz_groups':
+                for ((u,r), val) in new_user_role_dict.items():
+                    if val:
+                        if not ((u,r) in current_user_role_dict):
+                            model.add_authorization_group_to_role(model.AuthorizationGroup.by_name(u),r,group)
+                    else:
+                        if ((u,r) in current_user_role_dict):
+                            model.remove_authorization_group_from_role(model.AuthorizationGroup.by_name(u),r,group)
+            else:
+                assert False, "shouldn't be here"
+
+
+            # finally commit the change to the database
+            model.repo.commit_and_remove()
+            h.flash_success("Changes Saved")
+
+
+
+        def action_add_form(users_or_authz_groups):
+            # The user is attempting to set new roles for a named user
+            new_user = request.params.get('new_user_name')
+            # this is the list of roles whose boxes were ticked
+            checked_roles = [ a for (a,b) in request.params.items() if (b == u'on')]
+            # this is the list of all the roles that were in the submitted form
+            submitted_roles = [ a for (a,b) in request.params.items() if (b == u'submitted')]
+
+            # from this we can make a dictionary of the desired states
+            # i.e. true for the ticked boxes, false for the unticked
+            desired_roles = {}
+            for r in submitted_roles:
+                desired_roles[r]=False
+            for r in checked_roles:
+                desired_roles[r]=True
+
+            # again, in order to avoid either creating a role twice or deleting one which is
+            # non-existent, we need to get the users' current roles (if any)
+  
+            current_uors = get_userobjectroles()
+
+            if users_or_authz_groups=='users':
+                current_roles = [uor.role for uor in current_uors if ( uor.user and uor.user.name == new_user )]
+                user_object = model.User.by_name(new_user)
+                if user_object==None:
+                    # The submitted user does not exist. Bail with flash message
+                    h.flash_error('unknown user:' + str (new_user))
+                else:
+                    # Whenever our desired state is different from our current state, change it.
+                    for (r,val) in desired_roles.items():
+                        if val:
+                            if (r not in current_roles):
+                                model.add_user_to_role(user_object, r, group)
+                        else:
+                            if (r in current_roles):
+                                model.remove_user_from_role(user_object, r, group)
+                    h.flash_success("User Added")
+
+            elif users_or_authz_groups=='authz_groups':
+                current_roles = [uor.role for uor in current_uors if ( uor.authorized_group and uor.authorized_group.name == new_user )]
+                user_object = model.AuthorizationGroup.by_name(new_user)
+                if user_object==None:
+                    # The submitted user does not exist. Bail with flash message
+                    h.flash_error('unknown authorization group:' + str (new_user))
+                else:
+                    # Whenever our desired state is different from our current state, change it.
+                    for (r,val) in desired_roles.items():
+                        if val:
+                            if (r not in current_roles):
+                                model.add_authorization_group_to_role(user_object, r, group)
+                        else:
+                            if (r in current_roles):
+                                model.remove_authorization_group_from_role(user_object, r, group)
+                    h.flash_success("Authorization Group Added")
+
+            else:
+                assert False, "shouldn't be here"
+
+            # and finally commit all these changes to the database
+            model.repo.commit_and_remove()
+
+
+        # In the event of a post request, work out which of the four possible actions
+        # is to be done, and do it before displaying the page
+        if 'add' in request.POST:
+            action_add_form('users')
+
+        if 'authz_add' in request.POST:
+            action_add_form('authz_groups')
+
+        if 'save' in request.POST:
+            action_save_form('users')
+
+        if 'authz_save' in request.POST:
+            action_save_form('authz_groups')
+
+        # =================
+        # Display the page
+
+        # Find out all the possible roles. At the moment, any role can be
+        # associated with any object, so that's easy:
+        possible_roles = model.Role.get_all()
+
+        # get the list of users who have roles on this object, with their roles
+        uors = get_userobjectroles()
+
+        # uniquify and sort
+        users = sorted(list(set([uor.user.name for uor in uors if uor.user])))
+        authz_groups = sorted(list(set([uor.authorized_group.name for uor in uors if uor.authorized_group])))
+
+        # make a dictionary from (user, role) to True, False
+        users_roles = [( uor.user.name, uor.role) for uor in uors if uor.user]
+        user_role_dict={}
+        for u in users:
+            for r in possible_roles:
+                if (u,r) in users_roles:
+                    user_role_dict[(u,r)]=True
+                else:
+                    user_role_dict[(u,r)]=False
+
+        # and similarly make a dictionary from (authz_group, role) to True, False
+        authz_groups_roles = [( uor.authorized_group.name, uor.role) for uor in uors if uor.authorized_group]
+        authz_groups_role_dict={}
+        for u in authz_groups:
+            for r in possible_roles:
+                if (u,r) in authz_groups_roles:
+                    authz_groups_role_dict[(u,r)]=True
+                else:
+                    authz_groups_role_dict[(u,r)]=False
+
+        # pass these variables to the template for rendering
+        c.roles = possible_roles
+
+        c.users = users
+        c.user_role_dict = user_role_dict
+
+        c.authz_groups = authz_groups
+        c.authz_groups_role_dict = authz_groups_role_dict
+
         return render('group/authz.html')
-        
+
+
+
+
+
+
+       
     def history(self, id):
         if 'diff' in request.params or 'selected1' in request.params:
             try:


--- a/ckan/templates/authorization_group/authz.html	Tue May 17 10:15:11 2011 +0100
+++ b/ckan/templates/authorization_group/authz.html	Tue May 17 23:13:22 2011 +0100
@@ -9,21 +9,41 @@
       Authorization for authorization group: ${c.authorization_group_name}
     </h2>
 
-    <p py:if="c.message">${c.message}</p>
 
-    <form id="group-authz" action="" method="post">
-      <h3>Update Existing Roles</h3>
-      <table>
-      ${h.literal(c.form)}
-      </table>
+    <h2>Update Existing Roles</h2>
 
-      <h3>Create New User or Authorization Group Roles</h3>
-      ${h.literal(c.new_roles_form)}
-      
-      <br/>
+    <form id="theform" method="POST">
+      ${authz_form_table('theform', c.roles, c.users, c.user_role_dict)}
+      <button type="submit" name="save">
+        Save
+      </button>
+    </form>
 
-      ${h.submit('save', _('Save'))}
+    <h2>Add Roles for Any User</h2>
+
+    <form id="addform" method="POST">
+      ${authz_add_table(c.roles)}
+      <button type="submit" name="add"> Add </button></form>
+
+    <hr/>
+
+    <h2>Existing Roles for Authorization Groups</h2>
+
+    <form id="authzgroup_form" method="POST">
+      ${authz_form_group_table('authzgroup_form', c.roles, c.authz_groups, c.authz_groups_role_dict)}
+      <button type="submit" name="authz_save">
+        Save
+      </button>
+    </form>
+
+    <h2>Add Roles for Any Authorization Group</h2>
+
+    <form id="authzgroup_addform" method="POST">
+      ${authz_add_group_table(c.roles)}
+      <button type="submit" name="authz_add"> Add </button>
+    </form>
+
   </div><xi:include href="layout.html" />


--- a/ckan/templates/group/authz.html	Tue May 17 10:15:11 2011 +0100
+++ b/ckan/templates/group/authz.html	Tue May 17 23:13:22 2011 +0100
@@ -9,21 +9,40 @@
       Authorization for group: ${c.grouptitle or c.groupname}
     </h2>
 
-    <p py:if="c.message">${c.message}</p>
+    <h2>Update Existing Roles</h2>
 
-    <form id="group-authz" action="" method="post">
-      <h3>Update Existing Roles</h3>
-      <table>
-      ${h.literal(c.form)}
-      </table>
+    <form id="theform" method="POST">
+      ${authz_form_table('theform', c.roles, c.users, c.user_role_dict)}
+      <button type="submit" name="save">
+        Save
+      </button>
+    </form>
 
-      <h3>Create New User Roles</h3>
-      ${h.literal(c.new_roles_form)}
-        
-      <br/>
+    <h2>Add Roles for Any User</h2>
 
-      ${h.submit('save', _('Save'))}
+    <form id="addform" method="POST">
+      ${authz_add_table(c.roles)}
+      <button type="submit" name="add"> Add </button></form>
+
+    <hr/>
+
+    <h2>Existing Roles for Authorization Groups</h2>
+
+    <form id="authzgroup_form" method="POST">
+      ${authz_form_group_table('authzgroup_form', c.roles, c.authz_groups, c.authz_groups_role_dict)}
+      <button type="submit" name="authz_save">
+        Save
+      </button>
+    </form>
+
+    <h2>Add Roles for Any Authorization Group</h2>
+
+    <form id="authzgroup_addform" method="POST">
+      ${authz_add_group_table(c.roles)}
+      <button type="submit" name="authz_add"> Add </button>
+    </form>
+
   </div><xi:include href="layout.html" />


http://bitbucket.org/okfn/ckan/changeset/c662e38c86fa/
changeset:   r3108:c662e38c86fa
branch:      feature-1074-authz-wui
user:        John Lawrence Aspden
date:        2011-05-18 02:19:38
summary:     [authz][s]: waypoint. attempt to create one set of tests for all authz pages
guarding against cut-and-paste type errors in the main code like accidentally modifying the wrong thing.
affected #:  1 file (14.8 KB)

--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/ckan/tests/functional/test_edit_authz.py	Wed May 18 01:19:38 2011 +0100
@@ -0,0 +1,365 @@
+import ckan.model as model
+from ckan.tests import *
+from ckan.lib.base import *
+import ckan.authz as authz
+
+
+def check_and_set_checkbox(theform, user, role, should_be, set_to):
+   '''Given an authz form, find the checkbox associated with the strings user and role,
+   assert that it's in the state 'should_be', and set it to 'set_to' '''
+   user_role_string = '%s$%s' % (user, role)
+   checkboxes = [x for x in theform.fields[user_role_string] \
+                                   if x.__class__.__name__ == 'Checkbox']
+
+   assert(len(checkboxes)==1), \
+        "there should only be one checkbox for %s/%s" % (user, role)
+   checkbox = checkboxes[0]
+
+   #checkbox should be unticked
+   assert checkbox.checked==should_be, \
+                 "%s/%s checkbox in unexpected state" % (user, role)
+
+   #tick or untick the box and return the form
+   checkbox.checked=set_to
+   return theform
+
+
+class TestEditAuthz(TestController):
+    @classmethod
+    def setup_class(self):
+        # for the authorization editing tests we set up test data so:
+        # three users, sysadmin , administrator, and another
+        # one authzgroup, one group, one package
+        # and administrator is admin on all three
+        model.repo.init_db()
+        model.repo.new_revision()
+        
+        self.sysadmin = 'sysadmin'
+        sysadmin_user = model.User(name=unicode(self.sysadmin))
+        self.admin = 'administrator'
+        admin_user = model.User(name=unicode(self.admin))
+        self.another = 'another'
+        another_user = model.User(name=unicode(self.another))
+        self.authzgroup = 'authzgroup'
+        authzgroup = model.AuthorizationGroup(name=unicode(self.authzgroup))
+        self.group = 'group'
+        group = model.Group(name=unicode(self.group))
+
+        for obj in sysadmin_user, admin_user, another_user, authzgroup, group:
+            model.Session.add(obj)
+
+        model.add_user_to_role(sysadmin_user, model.Role.ADMIN, model.System())
+        model.repo.new_revision()
+
+        self.pkg = u'package'
+        pkg = model.Package(name=self.pkg)
+        model.Session.add(pkg)
+
+        admin_user = model.User.by_name(unicode(self.admin))
+        assert admin_user
+
+        # setup all three authorization objects to have logged in and visitor as editors, and the admin as admin
+        model.setup_user_roles(pkg, ['editor'], ['editor'], [admin_user])
+        model.setup_user_roles(authzgroup, ['editor'], ['editor'], [admin_user])
+        model.setup_user_roles(group, ['editor'], ['editor'], [admin_user])
+
+        model.repo.commit_and_remove()
+
+    @classmethod
+    def teardown_class(self):
+        model.repo.rebuild_db()
+
+    def test_access_to_authz(self):
+        for (c,i) in [('package', self.pkg),('group', self.group),('authorization_group', self.authzgroup)]:
+            offset = url_for(controller=c, action='authz', id=i)
+
+            # attempt to access the authz pages without credentials should result in getting redirected to the login page
+            res = self.app.get(offset, status=[302])
+            res = res.follow()
+            assert res.request.url.startswith('/user/login')
+
+            # for an ordinary user, it should result in access denied
+            # which is weird, because in the app proper he'd get redirected too.
+            # it behaves differently in the test setup, but this is a known strangeness.
+            res = self.app.get(offset, status=[401], extra_environ={'REMOTE_USER':self.another})
+
+            # going there as the package administrator or system administrator should be fine
+            for u in [self.admin,self.sysadmin]:
+                res = self.app.get(offset, status=[200], extra_environ={'REMOTE_USER':u})
+                # the name of the object should appear in the page
+                assert i in res
+                assert "Authorization for" in res
+
+
+    def roles_list(self, authzobj):
+        list = [ (r.user.name, r.role) for r in authzobj.roles if r.user]
+        list.extend([(r.authorized_group.name, r.role) for r in authzobj.roles if r.authorized_group])
+        return list
+
+    def package_roles(self):
+        return self.roles_list(model.Package.by_name(self.pkg))
+
+    def group_roles(self):
+        return self.roles_list(model.Group.by_name(self.group))
+
+    def authzgroup_roles(self):
+        return self.roles_list(model.AuthorizationGroup.by_name(self.authzgroup))
+
+    def test_2_read_ok(self):
+        for (c,i,m) in [('package', self.pkg, self.package_roles),\
+                        ('group', self.group, self.group_roles),\
+                        ('authorization_group', self.authzgroup, self.authzgroup_roles)]:
+            offset = url_for(controller=c, action='authz', id=i)
+            res = self.app.get(offset, extra_environ={'REMOTE_USER': self.admin})
+            assert i in res
+            assert "Authorization for" in res
+
+            # all the package's users and roles should appear in tables
+            assert '<tr' in res
+            for (user,role) in m():
+                assert user in res
+                assert role in res
+
+
+    def assert_roles_to_be(self, actual_roles_list, expected_roles_list):
+        ok = ( len(actual_roles_list) == len(expected_roles_list) )
+        for r in actual_roles_list:
+           if not r in expected_roles_list:
+               ok = False
+        if not ok:
+           print "expected roles: ", expected_roles_list
+           print "actual roles: ", actual_roles_list
+           assert False, "roles not as expected"
+
+
+    def change_roles(self, user):
+
+        normal_roles=[('administrator', 'admin'),
+                      ('visitor', 'editor'),
+                      ('logged_in', 'editor')]
+
+        changed_roles=[('administrator', 'admin'),
+                       ('visitor', 'editor'),
+                       ('visitor', 'reader'),
+                       ('logged_in', 'admin')]
+
+
+        for (c,i,var,const1,const2) in [('package', self.pkg, self.package_roles, self.group_roles, self.authzgroup_roles),\
+                        ('group', self.group, self.group_roles, self.package_roles, self.authzgroup_roles),\
+                        ('authorization_group', self.authzgroup, self.authzgroup_roles, self.package_roles, self.group_roles)]:
+
+            # load authz page
+            offset = url_for(controller=c, action='authz', id=i)
+            res = self.app.get(offset, extra_environ={'REMOTE_USER':user})
+            assert i in res
+
+            self.assert_roles_to_be(var(), normal_roles)
+            self.assert_roles_to_be(const1(), normal_roles)
+            self.assert_roles_to_be(const2(), normal_roles)
+
+            #admin makes visitor a reader and logged in an admin
+            form = res.forms['theform']
+            check_and_set_checkbox(form, u'visitor', u'reader', False, True)
+            check_and_set_checkbox(form, u'logged_in', u'admin', False, True)
+            check_and_set_checkbox(form, u'visitor', u'editor', True, True)
+            check_and_set_checkbox(form, u'logged_in', u'editor', True, False)
+
+            res = form.submit('save', extra_environ={'REMOTE_USER': user})
+
+            # ensure db was changed
+            self.assert_roles_to_be(var(), changed_roles)
+            self.assert_roles_to_be(const1(), normal_roles)
+            self.assert_roles_to_be(const2(), normal_roles)
+
+            # ensure rerender of form is changed
+            offset = url_for(controller=c, action='authz', id=i)
+            res = self.app.get(offset, extra_environ={'REMOTE_USER':user})
+            assert i in res
+
+            # check that the checkbox states are what we think they should be
+            # and put things back how they were.
+            form = res.forms['theform']
+            check_and_set_checkbox(form, u'visitor', u'reader', True, False)
+            check_and_set_checkbox(form, u'logged_in', u'admin', True, False)
+            check_and_set_checkbox(form, u'visitor', u'editor', True, True)
+            check_and_set_checkbox(form, u'logged_in', u'editor', False, True)
+            res = form.submit('save', extra_environ={'REMOTE_USER': user})
+
+            # ensure db was changed
+            self.assert_roles_to_be(var(), normal_roles)
+            self.assert_roles_to_be(const1(), normal_roles)
+            self.assert_roles_to_be(const2(), normal_roles)
+
+
+
+    def test_3_admin_changes_role(self):
+        self.change_roles(self.admin)
+
+    def test_3_sysadmin_changes_role(self):
+        self.change_roles(self.sysadmin)
+
+    def delete_role_as(self,user):
+        # get the authz page, check that visitor's in there
+        # remove visitor's role on the package
+        # re-get the page and make sure that visitor's not in there at all
+        offset = url_for(controller='package', action='authz', id=self.pkgname)
+        res = self.app.get(offset, extra_environ={'REMOTE_USER':user})
+        assert self.pkgname in res
+
+        self.assert_package_roles_to_be([
+           ('madeup-administrator', 'admin'),
+           ('visitor', 'editor'),
+           ('logged_in', 'editor')])
+
+        assert 'visitor' in res
+        assert 'madeup-administrator' in res
+        assert 'logged_in' in res
+
+        #admin removes visitor's only role
+        form = res.forms['theform']
+        check_and_set_checkbox(form, u'visitor', u'editor', True, False)
+        res = form.submit('save', extra_environ={'REMOTE_USER': user})
+
+        # ensure db was changed
+        self.assert_package_roles_to_be([
+           ('madeup-administrator', 'admin'),
+           ('logged_in', 'editor')])
+
+        # ensure rerender of form is changed
+        offset = url_for(controller='package', action='authz', id=self.pkgname)
+        res = self.app.get(offset, extra_environ={'REMOTE_USER':user})
+        assert self.pkgname in res
+
+        assert 'visitor' not in res
+        assert 'madeup-administrator' in res
+        assert 'logged_in' in res
+
+        # check that the checkbox states are what we think they should be
+        form = res.forms['theform']
+        check_and_set_checkbox(form, u'logged_in', u'editor', True, True)
+        check_and_set_checkbox(form, u'madeup-administrator', u'admin', True, True)
+
+        # now we should add visitor back in, let's make him a reader
+        form = res.forms['addform']
+        form.fields['new_user_name'][0].value='visitor'
+        checkbox = [x for x in form.fields['reader'] \
+                      if x.__class__.__name__ == 'Checkbox'][0]
+        # check it's currently unticked
+        assert checkbox.checked == False
+        # tick it and submit
+        checkbox.checked=True
+        res = form.submit('add', extra_environ={'REMOTE_USER':user})
+        assert "User Added" in res, "don't see flash message"
+
+       # check that the page contains strings for everyone
+        assert 'visitor' in res
+        assert 'madeup-administrator' in res
+        assert 'logged_in' in res
+
+        # check that the roles in the db are back to normal
+        self.assert_package_roles_to_be([
+           ('madeup-administrator', 'admin'),
+           ('visitor', 'reader'),
+           ('logged_in', 'editor')])
+
+        # now change him back to being an editor
+        form = res.forms['theform']
+        check_and_set_checkbox(form, u'visitor', u'reader', True, False)
+        check_and_set_checkbox(form, u'visitor', u'editor', False, True)
+        res = form.submit('save', extra_environ={'REMOTE_USER': user})
+ 
+        # check that the page contains strings for everyone
+        assert 'visitor' in res
+        assert 'madeup-administrator' in res
+        assert 'logged_in' in res
+
+        # check that the roles in the db are back to normal
+        self.assert_package_roles_to_be([
+           ('madeup-administrator', 'admin'),
+           ('visitor', 'editor'),
+           ('logged_in', 'editor')])
+
+
+    def test_4_admin_deletes_role(self):
+        self.delete_role_as(self.admin)
+
+    def test_4_sysadmin_deletes_role(self):
+        self.delete_role_as(self.sysadmin)
+
+
+    def test_5_add_change_delete_authzgroup(self):
+        user=self.admin
+
+        # get the authz page, check that authzgroup isn't in there
+        offset = url_for(controller='package', action='authz', id=self.pkgname)
+        res = self.app.get(offset, extra_environ={'REMOTE_USER':user})
+        assert self.pkgname in res
+
+        # check the state of the database
+        self.assert_package_roles_to_be([
+           ('madeup-administrator', 'admin'),
+           ('visitor', 'editor'),
+           ('logged_in', 'editor')])
+
+        # and that corresponding user strings are in the authz page
+        assert 'visitor' in res
+        assert 'madeup-administrator' in res
+        assert 'logged_in' in res
+        assert 'madeup-authzgroup' not in res
+
+        # add madeup-authzgroup as an admin
+        form = res.forms['authzgroup_addform']
+        form.fields['new_user_name'][0].value='madeup-authzgroup'
+        checkbox = [x for x in form.fields['admin'] \
+                      if x.__class__.__name__ == 'Checkbox'][0]
+        # check the checkbox is currently unticked
+        assert checkbox.checked == False
+        # tick it and submit
+        checkbox.checked=True
+        res = form.submit('authz_add', extra_environ={'REMOTE_USER':user})
+        assert "Authorization Group Added" in res, "don't see flash message"
+
+        # examine the new page for user names/authzgroup names
+        assert 'visitor' in res
+        assert 'madeup-administrator' in res
+        assert 'logged_in' in res
+        assert 'madeup-authzgroup' in res
+
+        # and ensure that the database has changed as expected
+        self.assert_package_roles_to_be([
+           ('madeup-authzgroup', 'admin'),
+           ('madeup-administrator', 'admin'),
+           ('visitor', 'editor'),
+           ('logged_in', 'editor')])
+
+        # check that the checkbox states are what we think they should be
+        # and change madeup-authzgroup from admin to editor
+        form = res.forms['authzgroup_form']
+        check_and_set_checkbox(form, u'madeup-authzgroup', u'editor', False, True)
+        check_and_set_checkbox(form, u'madeup-authzgroup', u'admin', True, False)
+        res = form.submit('authz_save', extra_environ={'REMOTE_USER': user})
+
+        #check database has changed.
+        self.assert_package_roles_to_be([
+           ('madeup-authzgroup', 'editor'),
+           ('madeup-administrator', 'admin'),
+           ('visitor', 'editor'),
+           ('logged_in', 'editor')])
+
+        # now remove madeup-authzgroup entirely
+        form = res.forms['authzgroup_form']
+        check_and_set_checkbox(form, u'madeup-authzgroup', u'editor', True, False)
+        check_and_set_checkbox(form, u'madeup-authzgroup', u'admin', False, False)
+        res = form.submit('authz_save', extra_environ={'REMOTE_USER': user})
+
+        #check database is back to normal
+        self.assert_package_roles_to_be([
+           ('madeup-administrator', 'admin'),
+           ('visitor', 'editor'),
+           ('logged_in', 'editor')])
+
+        # and that page contains only the expected strings
+        assert 'visitor' in res
+        assert 'madeup-administrator' in res
+        assert 'logged_in' in res
+        assert 'madeup-authzgroup' not in res


http://bitbucket.org/okfn/ckan/changeset/e7e733358ad5/
changeset:   r3109:e7e733358ad5
branch:      feature-1074-authz-wui
user:        John Lawrence Aspden
date:        2011-05-24 23:48:49
summary:     [authz][s]: comments, fix test 3
affected #:  1 file (1.1 KB)

--- a/ckan/tests/functional/test_edit_authz.py	Wed May 18 01:19:38 2011 +0100
+++ b/ckan/tests/functional/test_edit_authz.py	Tue May 24 22:48:49 2011 +0100
@@ -70,6 +70,7 @@
         model.repo.rebuild_db()
 
     def test_access_to_authz(self):
+        #for each of the three authz pages, check that the access permissions work correctly
         for (c,i) in [('package', self.pkg),('group', self.group),('authorization_group', self.authzgroup)]:
             offset = url_for(controller=c, action='authz', id=i)
 
@@ -92,10 +93,12 @@
 
 
     def roles_list(self, authzobj):
+        # get a list of username/roles for a given authorizable object
         list = [ (r.user.name, r.role) for r in authzobj.roles if r.user]
         list.extend([(r.authorized_group.name, r.role) for r in authzobj.roles if r.authorized_group])
         return list
 
+    # get the users/roles for the specific objects created in our test data
     def package_roles(self):
         return self.roles_list(model.Package.by_name(self.pkg))
 
@@ -105,6 +108,7 @@
     def authzgroup_roles(self):
         return self.roles_list(model.AuthorizationGroup.by_name(self.authzgroup))
 
+    # check that the authz page for each object contains certain key strings
     def test_2_read_ok(self):
         for (c,i,m) in [('package', self.pkg, self.package_roles),\
                         ('group', self.group, self.group_roles),\
@@ -122,6 +126,8 @@
 
 
     def assert_roles_to_be(self, actual_roles_list, expected_roles_list):
+        # given an actual and an expected list of user/roles, assert that they're as expected, 
+        # modulo ordering.
         ok = ( len(actual_roles_list) == len(expected_roles_list) )
         for r in actual_roles_list:
            if not r in expected_roles_list:
@@ -132,6 +138,9 @@
            assert False, "roles not as expected"
 
 
+    # check that when we change one role and add another, that both the checkbox states and the database
+    # change as we expect them to, and that the roles on the other objects don't get changed by accident.
+    # this should guard against certain errors which might be introduced by copy and pasting the controller code.
     def change_roles(self, user):
 
         normal_roles=[('administrator', 'admin'),
@@ -143,7 +152,8 @@
                        ('visitor', 'reader'),
                        ('logged_in', 'admin')]
 
-
+        # loop variables here are the controller string, the name of the object we're changing, and three functions, 
+        # the first fn gets the roles which we'd like to change, and the other two get the roles which we'd like to stay the same.
         for (c,i,var,const1,const2) in [('package', self.pkg, self.package_roles, self.group_roles, self.authzgroup_roles),\
                         ('group', self.group, self.group_roles, self.package_roles, self.authzgroup_roles),\
                         ('authorization_group', self.authzgroup, self.authzgroup_roles, self.package_roles, self.group_roles)]:
@@ -191,7 +201,7 @@
             self.assert_roles_to_be(const2(), normal_roles)
 
 
-
+    # do the change roles both as package/group/authzgroup admin, and also as sysadmin.
     def test_3_admin_changes_role(self):
         self.change_roles(self.admin)
 
@@ -202,17 +212,17 @@
         # get the authz page, check that visitor's in there
         # remove visitor's role on the package
         # re-get the page and make sure that visitor's not in there at all
-        offset = url_for(controller='package', action='authz', id=self.pkgname)
+        offset = url_for(controller='package', action='authz', id=self.pkg)
         res = self.app.get(offset, extra_environ={'REMOTE_USER':user})
-        assert self.pkgname in res
+        assert self.pkg in res
 
-        self.assert_package_roles_to_be([
-           ('madeup-administrator', 'admin'),
+        self.assert_roles_to_be(self.package_roles(), [
+           ('administrator', 'admin'),
            ('visitor', 'editor'),
            ('logged_in', 'editor')])
 
         assert 'visitor' in res
-        assert 'madeup-administrator' in res
+        assert 'administrator' in res
         assert 'logged_in' in res
 
         #admin removes visitor's only role
@@ -221,23 +231,23 @@
         res = form.submit('save', extra_environ={'REMOTE_USER': user})
 
         # ensure db was changed
-        self.assert_package_roles_to_be([
-           ('madeup-administrator', 'admin'),
+        self.assert_roles_to_be(self.package_roles(), [
+           ('administrator', 'admin'),
            ('logged_in', 'editor')])
 
         # ensure rerender of form is changed
-        offset = url_for(controller='package', action='authz', id=self.pkgname)
+        offset = url_for(controller='package', action='authz', id=self.pkg)
         res = self.app.get(offset, extra_environ={'REMOTE_USER':user})
-        assert self.pkgname in res
+        assert self.pkg in res
 
         assert 'visitor' not in res
-        assert 'madeup-administrator' in res
+        assert 'administrator' in res
         assert 'logged_in' in res
 
         # check that the checkbox states are what we think they should be
         form = res.forms['theform']
         check_and_set_checkbox(form, u'logged_in', u'editor', True, True)
-        check_and_set_checkbox(form, u'madeup-administrator', u'admin', True, True)
+        check_and_set_checkbox(form, u'administrator', u'admin', True, True)
 
         # now we should add visitor back in, let's make him a reader
         form = res.forms['addform']
@@ -253,12 +263,12 @@
 
        # check that the page contains strings for everyone
         assert 'visitor' in res
-        assert 'madeup-administrator' in res
+        assert 'administrator' in res
         assert 'logged_in' in res
 
         # check that the roles in the db are back to normal
-        self.assert_package_roles_to_be([
-           ('madeup-administrator', 'admin'),
+        self.assert_roles_to_be(self.package_roles(), [
+           ('administrator', 'admin'),
            ('visitor', 'reader'),
            ('logged_in', 'editor')])
 
@@ -270,12 +280,12 @@
  
         # check that the page contains strings for everyone
         assert 'visitor' in res
-        assert 'madeup-administrator' in res
+        assert 'administrator' in res
         assert 'logged_in' in res
 
         # check that the roles in the db are back to normal
-        self.assert_package_roles_to_be([
-           ('madeup-administrator', 'admin'),
+        self.assert_roles_to_be(self.package_roles(), [
+           ('administrator', 'admin'),
            ('visitor', 'editor'),
            ('logged_in', 'editor')])
 


http://bitbucket.org/okfn/ckan/changeset/b6a4c9f448dc/
changeset:   r3110:b6a4c9f448dc
branch:      feature-1074-authz-wui
user:        John Lawrence Aspden
date:        2011-05-25 00:01:39
summary:     [authz][s]: generalize test4 to test all three types of authz object
affected #:  1 file (1.2 KB)

--- a/ckan/tests/functional/test_edit_authz.py	Tue May 24 22:48:49 2011 +0100
+++ b/ckan/tests/functional/test_edit_authz.py	Tue May 24 23:01:39 2011 +0100
@@ -209,85 +209,102 @@
         self.change_roles(self.sysadmin)
 
     def delete_role_as(self,user):
-        # get the authz page, check that visitor's in there
-        # remove visitor's role on the package
-        # re-get the page and make sure that visitor's not in there at all
-        offset = url_for(controller='package', action='authz', id=self.pkg)
-        res = self.app.get(offset, extra_environ={'REMOTE_USER':user})
-        assert self.pkg in res
 
-        self.assert_roles_to_be(self.package_roles(), [
-           ('administrator', 'admin'),
-           ('visitor', 'editor'),
-           ('logged_in', 'editor')])
+        normal_roles=[('administrator', 'admin'),
+                      ('visitor', 'editor'),
+                      ('logged_in', 'editor')]
 
-        assert 'visitor' in res
-        assert 'administrator' in res
-        assert 'logged_in' in res
+        changed_roles=[('administrator', 'admin'),
+                       ('logged_in', 'editor')]
 
-        #admin removes visitor's only role
-        form = res.forms['theform']
-        check_and_set_checkbox(form, u'visitor', u'editor', True, False)
-        res = form.submit('save', extra_environ={'REMOTE_USER': user})
+        changed_roles2=[('administrator', 'admin'),
+                        ('visitor', 'reader'),
+                        ('logged_in', 'editor')]
 
-        # ensure db was changed
-        self.assert_roles_to_be(self.package_roles(), [
-           ('administrator', 'admin'),
-           ('logged_in', 'editor')])
 
-        # ensure rerender of form is changed
-        offset = url_for(controller='package', action='authz', id=self.pkg)
-        res = self.app.get(offset, extra_environ={'REMOTE_USER':user})
-        assert self.pkg in res
+        # loop variables here are the controller string, the name of the object we're changing, and three functions, 
+        # the first fn gets the roles which we'd like to change, and the other two get the roles which we'd like to stay the same.
+        for (c,i,var,const1,const2) in [('package', self.pkg, self.package_roles, self.group_roles, self.authzgroup_roles),\
+                        ('group', self.group, self.group_roles, self.package_roles, self.authzgroup_roles),\
+                        ('authorization_group', self.authzgroup, self.authzgroup_roles, self.package_roles, self.group_roles)]:
 
-        assert 'visitor' not in res
-        assert 'administrator' in res
-        assert 'logged_in' in res
+           # get the authz page, check that visitor's in there
+           # remove visitor's role on the package
+           # re-get the page and make sure that visitor's not in there at all
+           offset = url_for(controller=c, action='authz', id=i)
+           res = self.app.get(offset, extra_environ={'REMOTE_USER':user})
+           assert self.pkg in res
 
-        # check that the checkbox states are what we think they should be
-        form = res.forms['theform']
-        check_and_set_checkbox(form, u'logged_in', u'editor', True, True)
-        check_and_set_checkbox(form, u'administrator', u'admin', True, True)
+           self.assert_roles_to_be(var(), normal_roles)
+           self.assert_roles_to_be(const1(), normal_roles)
+           self.assert_roles_to_be(const2(), normal_roles)
 
-        # now we should add visitor back in, let's make him a reader
-        form = res.forms['addform']
-        form.fields['new_user_name'][0].value='visitor'
-        checkbox = [x for x in form.fields['reader'] \
-                      if x.__class__.__name__ == 'Checkbox'][0]
-        # check it's currently unticked
-        assert checkbox.checked == False
-        # tick it and submit
-        checkbox.checked=True
-        res = form.submit('add', extra_environ={'REMOTE_USER':user})
-        assert "User Added" in res, "don't see flash message"
+           assert 'visitor' in res
+           assert 'administrator' in res
+           assert 'logged_in' in res
 
-       # check that the page contains strings for everyone
-        assert 'visitor' in res
-        assert 'administrator' in res
-        assert 'logged_in' in res
+           #admin removes visitor's only role
+           form = res.forms['theform']
+           check_and_set_checkbox(form, u'visitor', u'editor', True, False)
+           res = form.submit('save', extra_environ={'REMOTE_USER': user})
 
-        # check that the roles in the db are back to normal
-        self.assert_roles_to_be(self.package_roles(), [
-           ('administrator', 'admin'),
-           ('visitor', 'reader'),
-           ('logged_in', 'editor')])
+           # ensure db was changed
+           self.assert_roles_to_be(var(), changed_roles)
+           self.assert_roles_to_be(const1(), normal_roles)
+           self.assert_roles_to_be(const2(), normal_roles)
 
-        # now change him back to being an editor
-        form = res.forms['theform']
-        check_and_set_checkbox(form, u'visitor', u'reader', True, False)
-        check_and_set_checkbox(form, u'visitor', u'editor', False, True)
-        res = form.submit('save', extra_environ={'REMOTE_USER': user})
- 
-        # check that the page contains strings for everyone
-        assert 'visitor' in res
-        assert 'administrator' in res
-        assert 'logged_in' in res
+           # ensure rerender of form is changed
+           offset = url_for(controller=c, action='authz', id=i)
+           res = self.app.get(offset, extra_environ={'REMOTE_USER':user})
+           assert self.pkg in res
 
-        # check that the roles in the db are back to normal
-        self.assert_roles_to_be(self.package_roles(), [
-           ('administrator', 'admin'),
-           ('visitor', 'editor'),
-           ('logged_in', 'editor')])
+           assert 'visitor' not in res
+           assert 'administrator' in res
+           assert 'logged_in' in res
+
+           # check that the checkbox states are what we think they should be
+           form = res.forms['theform']
+           check_and_set_checkbox(form, u'logged_in', u'editor', True, True)
+           check_and_set_checkbox(form, u'administrator', u'admin', True, True)
+
+           # now we should add visitor back in, let's make him a reader
+           form = res.forms['addform']
+           form.fields['new_user_name'][0].value='visitor'
+           checkbox = [x for x in form.fields['reader'] \
+                         if x.__class__.__name__ == 'Checkbox'][0]
+           # check it's currently unticked
+           assert checkbox.checked == False
+           # tick it and submit
+           checkbox.checked=True
+           res = form.submit('add', extra_environ={'REMOTE_USER':user})
+           assert "User Added" in res, "don't see flash message"
+
+           # check that the page contains strings for everyone
+           assert 'visitor' in res
+           assert 'administrator' in res
+           assert 'logged_in' in res
+
+           # check that the roles in the db are back to normal
+           self.assert_roles_to_be(var(), changed_roles2)
+           self.assert_roles_to_be(const1(), normal_roles)
+           self.assert_roles_to_be(const2(), normal_roles)
+
+           # now change him back to being an editor
+           form = res.forms['theform']
+           check_and_set_checkbox(form, u'visitor', u'reader', True, False)
+           check_and_set_checkbox(form, u'visitor', u'editor', False, True)
+           res = form.submit('save', extra_environ={'REMOTE_USER': user})
+
+           # check that the page contains strings for everyone
+           assert 'visitor' in res
+           assert 'administrator' in res
+           assert 'logged_in' in res
+
+           # check that the roles in the db are back to normal
+           self.assert_roles_to_be(var(), normal_roles)
+           self.assert_roles_to_be(const1(), normal_roles)
+           self.assert_roles_to_be(const2(), normal_roles)
+
 
 
     def test_4_admin_deletes_role(self):


http://bitbucket.org/okfn/ckan/changeset/3d0d8f4ff947/
changeset:   r3111:3d0d8f4ff947
branch:      feature-1074-authz-wui
user:        John Lawrence Aspden
date:        2011-05-25 00:32:01
summary:     [authz][s]: change authzgroup test to be in similar cross-validating form to the others
affected #:  1 file (1.5 KB)

--- a/ckan/tests/functional/test_edit_authz.py	Tue May 24 23:01:39 2011 +0100
+++ b/ckan/tests/functional/test_edit_authz.py	Tue May 24 23:32:01 2011 +0100
@@ -31,6 +31,7 @@
         # three users, sysadmin , administrator, and another
         # one authzgroup, one group, one package
         # and administrator is admin on all three
+        # one extra authzgroup, authzgroup2, with no permissions to start with
         model.repo.init_db()
         model.repo.new_revision()
         
@@ -44,8 +45,11 @@
         authzgroup = model.AuthorizationGroup(name=unicode(self.authzgroup))
         self.group = 'group'
         group = model.Group(name=unicode(self.group))
+        self.authzgroup2 = 'authzgroup2'
+        authzgroup2 = model.AuthorizationGroup(name=unicode(self.authzgroup2))
 
-        for obj in sysadmin_user, admin_user, another_user, authzgroup, group:
+
+        for obj in sysadmin_user, admin_user, another_user, authzgroup, group, authzgroup2:
             model.Session.add(obj)
 
         model.add_user_to_role(sysadmin_user, model.Role.ADMIN, model.System())
@@ -314,79 +318,101 @@
         self.delete_role_as(self.sysadmin)
 
 
-    def test_5_add_change_delete_authzgroup(self):
-        user=self.admin
+    # now a version of the above tests dealing with permissions assigned to authzgroups 
+    # (as opposed to on authzgroups)
+    def add_change_delete_authzgroup_as(self, user):
 
-        # get the authz page, check that authzgroup isn't in there
-        offset = url_for(controller='package', action='authz', id=self.pkgname)
-        res = self.app.get(offset, extra_environ={'REMOTE_USER':user})
-        assert self.pkgname in res
+        normal_roles=[('administrator', 'admin'),
+                      ('visitor', 'editor'),
+                      ('logged_in', 'editor')]
 
-        # check the state of the database
-        self.assert_package_roles_to_be([
-           ('madeup-administrator', 'admin'),
-           ('visitor', 'editor'),
-           ('logged_in', 'editor')])
+        changed_roles=[('authzgroup2', 'admin'),
+                       ('administrator', 'admin'),
+                       ('visitor', 'editor'),
+                       ('logged_in', 'editor')]
 
-        # and that corresponding user strings are in the authz page
-        assert 'visitor' in res
-        assert 'madeup-administrator' in res
-        assert 'logged_in' in res
-        assert 'madeup-authzgroup' not in res
+        changed_roles_2=[('authzgroup2', 'editor'),
+                         ('administrator', 'admin'),
+                         ('visitor', 'editor'),
+                         ('logged_in', 'editor')]
 
-        # add madeup-authzgroup as an admin
-        form = res.forms['authzgroup_addform']
-        form.fields['new_user_name'][0].value='madeup-authzgroup'
-        checkbox = [x for x in form.fields['admin'] \
-                      if x.__class__.__name__ == 'Checkbox'][0]
-        # check the checkbox is currently unticked
-        assert checkbox.checked == False
-        # tick it and submit
-        checkbox.checked=True
-        res = form.submit('authz_add', extra_environ={'REMOTE_USER':user})
-        assert "Authorization Group Added" in res, "don't see flash message"
+        for (c,i,var,const1,const2) in [('package', self.pkg, self.package_roles, self.group_roles, self.authzgroup_roles),\
+                        ('group', self.group, self.group_roles, self.package_roles, self.authzgroup_roles),\
+                        ('authorization_group', self.authzgroup, self.authzgroup_roles, self.package_roles, self.group_roles)]:
 
-        # examine the new page for user names/authzgroup names
-        assert 'visitor' in res
-        assert 'madeup-administrator' in res
-        assert 'logged_in' in res
-        assert 'madeup-authzgroup' in res
+           # get the authz page, check that it contains the object name
+           offset = url_for(controller=c, action='authz', id=i)
+           res = self.app.get(offset, extra_environ={'REMOTE_USER':user})
+           assert i in res
 
-        # and ensure that the database has changed as expected
-        self.assert_package_roles_to_be([
-           ('madeup-authzgroup', 'admin'),
-           ('madeup-administrator', 'admin'),
-           ('visitor', 'editor'),
-           ('logged_in', 'editor')])
+           # check the state of the database
+           self.assert_roles_to_be(var(), normal_roles)
+           self.assert_roles_to_be(const1(), normal_roles)
+           self.assert_roles_to_be(const2(), normal_roles)
 
-        # check that the checkbox states are what we think they should be
-        # and change madeup-authzgroup from admin to editor
-        form = res.forms['authzgroup_form']
-        check_and_set_checkbox(form, u'madeup-authzgroup', u'editor', False, True)
-        check_and_set_checkbox(form, u'madeup-authzgroup', u'admin', True, False)
-        res = form.submit('authz_save', extra_environ={'REMOTE_USER': user})
+           # and that corresponding user strings are in the authz page
+           # particularly that authzgroup2 isn't there (yet)
+           assert 'visitor' in res
+           assert 'administrator' in res
+           assert 'logged_in' in res
+           assert 'authzgroup2' not in res
+ 
+           # add authzgroup2 as an admin
+           form = res.forms['authzgroup_addform']
+           form.fields['new_user_name'][0].value='authzgroup2'
+           checkbox = [x for x in form.fields['admin'] \
+                         if x.__class__.__name__ == 'Checkbox'][0]
+           # check the checkbox is currently unticked
+           assert checkbox.checked == False
+           # tick it and submit
+           checkbox.checked=True
+           res = form.submit('authz_add', extra_environ={'REMOTE_USER':user})
+           assert "Authorization Group Added" in res, "don't see flash message"
 
-        #check database has changed.
-        self.assert_package_roles_to_be([
-           ('madeup-authzgroup', 'editor'),
-           ('madeup-administrator', 'admin'),
-           ('visitor', 'editor'),
-           ('logged_in', 'editor')])
+           # examine the new page for user names/authzgroup names
+           assert 'visitor' in res
+           assert 'administrator' in res
+           assert 'logged_in' in res
+           assert 'authzgroup2' in res
 
-        # now remove madeup-authzgroup entirely
-        form = res.forms['authzgroup_form']
-        check_and_set_checkbox(form, u'madeup-authzgroup', u'editor', True, False)
-        check_and_set_checkbox(form, u'madeup-authzgroup', u'admin', False, False)
-        res = form.submit('authz_save', extra_environ={'REMOTE_USER': user})
+           # and ensure that the database has changed as expected
+           self.assert_roles_to_be(var(), changed_roles)
+           self.assert_roles_to_be(const1(), normal_roles)
+           self.assert_roles_to_be(const2(), normal_roles)
+ 
+           # check that the checkbox states are what we think they should be
+           # and change authzgroup2 from admin to editor
+           form = res.forms['authzgroup_form']
+           check_and_set_checkbox(form, u'authzgroup2', u'editor', False, True)
+           check_and_set_checkbox(form, u'authzgroup2', u'admin', True, False)
+           res = form.submit('authz_save', extra_environ={'REMOTE_USER': user})
 
-        #check database is back to normal
-        self.assert_package_roles_to_be([
-           ('madeup-administrator', 'admin'),
-           ('visitor', 'editor'),
-           ('logged_in', 'editor')])
+           #check database has changed.
+           self.assert_roles_to_be(var(), changed_roles_2)
+           self.assert_roles_to_be(const1(), normal_roles)
+           self.assert_roles_to_be(const2(), normal_roles)
 
-        # and that page contains only the expected strings
-        assert 'visitor' in res
-        assert 'madeup-administrator' in res
-        assert 'logged_in' in res
-        assert 'madeup-authzgroup' not in res
+
+           # now remove authzgroup2 entirely
+           form = res.forms['authzgroup_form']
+           check_and_set_checkbox(form, u'authzgroup2', u'editor', True, False)
+           check_and_set_checkbox(form, u'authzgroup2', u'admin', False, False)
+           res = form.submit('authz_save', extra_environ={'REMOTE_USER': user})
+
+           #check database is back to normal
+           self.assert_roles_to_be(var(), normal_roles)
+           self.assert_roles_to_be(const1(), normal_roles)
+           self.assert_roles_to_be(const2(), normal_roles)
+
+           # and that page contains only the expected strings
+           assert 'visitor' in res
+           assert 'administrator' in res
+           assert 'logged_in' in res
+           assert 'authzgroup2' not in res
+
+
+    def test_5_admin_changes_adds_deletes_authzgroup(self):
+        self.add_change_delete_authzgroup_as(self.admin)
+
+    def test_5_sysadmin_changes_adds_deletes_authzgroup(self):
+        self.add_change_delete_authzgroup_as(self.sysadmin)

Repository URL: https://bitbucket.org/okfn/ckan/

--

This is a commit notification from bitbucket.org. You are receiving
this because you have the service enabled, addressing the recipient of
this email.




More information about the ckan-changes mailing list