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

Bitbucket commits-noreply at bitbucket.org
Fri Aug 5 17:17:34 UTC 2011


6 new changesets in ckan:

http://bitbucket.org/okfn/ckan/changeset/f615cda012f9/
changeset:   f615cda012f9
branch:      feature-1253-authz-refactor
user:        amercader
date:        2011-08-02 18:27:01
summary:     [authz] Make check_access actually return something
affected #:  1 file (252 bytes)

--- a/ckan/logic/__init__.py	Tue Aug 02 13:19:21 2011 +0100
+++ b/ckan/logic/__init__.py	Tue Aug 02 17:27:01 2011 +0100
@@ -93,46 +93,42 @@
 
     log.debug('check access - user %r' % user)
     
-    #if action and data_dict and object_type != 'package_relationship':
     if action and data_dict:
 
         #if action != model.Action.READ and user in (model.PSEUDO_USER__VISITOR, ''):
-        #    # XXX Check the API key is valid at some point too!
-        #    log.debug("Valid API key needed to make changes")
+        #    # TODO Check the API key is valid at some point too!
+        #    log.debug('Valid API key needed to make changes')
         #    raise NotAuthorized
         logic_authorization = new_authz.is_authorized(action, context, data_dict)
 
-        '''
-        if not logic_authorization['success']:
-            if not new_authz.check_overridden(context, action, object_id, object_type):
-                return AttributeDict(logic_authorization)
-        '''
+        return logic_authorization
+
     elif not user:
-        log.debug("No valid API key provided.")
-        return AttributeDict(success=False, msg="No valid API key provided.")
-    log.debug("Access OK.")
+        log.debug('No valid API key provided.')
+        return AttributeDict(success=False, msg='No valid API key provided.')
+    log.debug('Access OK.')
     return AttributeDict(success=True)
 
 
 def check_access(entity, action, context):
-    model = context["model"]
-    user = context.get("user")
+    model = context['model']
+    user = context.get('user')
 
     log.debug('check access - user %r' % user)
     
     if action and entity and not isinstance(entity, model.PackageRelationship):
         if action != model.Action.READ and user in (model.PSEUDO_USER__VISITOR, ''):
-            log.debug("Valid API key needed to make changes")
+            log.debug('Valid API key needed to make changes')
             raise NotAuthorized
         
         am_authz = ckan.authz.Authorizer().is_authorized(user, action, entity)
         if not am_authz:
-            log.debug("User is not authorized to %s %s" % (action, entity))
+            log.debug('User is not authorized to %s %s' % (action, entity))
             raise NotAuthorized
     elif not user:
-        log.debug("No valid API key provided.")
+        log.debug('No valid API key provided.')
         raise NotAuthorized
-    log.debug("Access OK.")
+    log.debug('Access OK.')
     return True             
 
 _actions = {}


http://bitbucket.org/okfn/ckan/changeset/42f4d0776fc3/
changeset:   42f4d0776fc3
branch:      feature-1253-authz-refactor
user:        amercader
date:        2011-08-03 11:57:28
summary:     [authz] Move create action related authz
affected #:  2 files (1.3 KB)

--- a/ckan/logic/action/create.py	Tue Aug 02 17:27:01 2011 +0100
+++ b/ckan/logic/action/create.py	Wed Aug 03 10:57:28 2011 +0100
@@ -1,6 +1,6 @@
 import logging
 
-import ckan.authz
+import ckan.rating as ratings
 from ckan.plugins import (PluginImplementations,
                           IGroupController,
                           IPackageController)
@@ -30,8 +30,7 @@
 from ckan.lib.navl.dictization_functions import validate 
 from ckan.logic.action.update import (_update_package_relationship,
                                       package_error_summary,
-                                      group_error_summary,
-                                      check_group_auth)
+                                      group_error_summary)
 log = logging.getLogger(__name__)
 
 def package_create(context, data_dict):
@@ -43,8 +42,7 @@
     model.Session.remove()
     model.Session()._context = context
 
-    check_access_new("package_create",context,data_dict)
-    check_group_auth(context, data_dict)
+    check_access_new('package_create',context,data_dict)
 
     data, errors = validate(data_dict, schema, context)
 
@@ -88,9 +86,8 @@
     schema = context.get('schema') or default_create_package_schema()
     model.Session.remove()
     model.Session()._context = context
-
-    check_access(model.System(), model.Action.PACKAGE_CREATE, context)
-    check_group_auth(context, data_dict)
+    
+    check_access_new('package_create',context,data_dict)
 
     data, errors = validate(data_dict, schema, context)
 
@@ -101,6 +98,8 @@
         return data
 
 def resource_create(context, data_dict):
+    #TODO This doesn't actually do anything
+
     model = context['model']
     user = context['user']
 
@@ -126,11 +125,7 @@
     if not pkg2:
         return NotFound('Second package named in address was not found.')
 
-    am_authorized = ckan.authz.Authorizer().\
-                    authorized_package_relationship(\
-                    user, pkg1, pkg2, action=model.Action.EDIT)
-    if not am_authorized:
-        raise NotAuthorized
+    check_access_new('package_relationship_create', context, data_dict)
 
     ##FIXME should have schema
     comment = data_dict.get('comment', u'')
@@ -152,7 +147,7 @@
     user = context['user']
     schema = context.get('schema') or default_group_schema()
 
-    check_access(model.System(), model.Action.GROUP_CREATE, context)
+    check_access_new('group_create',context,data_dict)
 
     data, errors = validate(data_dict, schema, context)
 
@@ -202,15 +197,15 @@
             opts_err = _('Rating must be an integer value.')
         else:
             package = model.Package.get(package_ref)
-            if rating < ckan.rating.MIN_RATING or rating > ckan.rating.MAX_RATING:
-                opts_err = _('Rating must be between %i and %i.') % (ckan.rating.MIN_RATING, ckan.rating.MAX_RATING)
+            if rating < ratings.MIN_RATING or rating > ratings.MAX_RATING:
+                opts_err = _('Rating must be between %i and %i.') % (ratings.MIN_RATING, ratings.MAX_RATING)
             elif not package:
                 opts_err = _('Package with name %r does not exist.') % package_ref
     if opts_err:
         raise ValidationError(opts_err)
 
     user = model.User.by_name(user)
-    ckan.rating.set_rating(user, package, rating_int)
+    ratings.set_rating(user, package, rating_int)
 
     package = model.Package.get(package_ref)
     ret_dict = {'rating average':package.get_average_rating(),
@@ -224,7 +219,7 @@
     user = context['user']
     schema = context.get('schema') or default_user_schema()
 
-    check_access(model.System(), model.Action.USER_CREATE, context)
+    check_access_new('user_create', context, data_dict)
 
     data, errors = validate(data_dict, schema, context)
 
@@ -251,8 +246,10 @@
 ## Modifications for rest api
 
 def package_create_rest(context, data_dict):
+    
+    api = context.get('api_version') or '1'
 
-    api = context.get('api_version') or '1'
+    check_access_new('package_create_rest', context, data_dict)
 
     dictized_package = package_api_to_dict(data_dict, context)
     dictized_after = package_create(context, dictized_package) 
@@ -272,6 +269,8 @@
 
     api = context.get('api_version') or '1'
 
+    check_access_new('group_create_rest', context, data_dict)
+
     dictized_group = group_api_to_dict(data_dict, context)
     dictized_after = group_create(context, dictized_group) 
 


--- a/ckan/logic/auth/create.py	Tue Aug 02 17:27:01 2011 +0100
+++ b/ckan/logic/auth/create.py	Wed Aug 03 10:57:28 2011 +0100
@@ -1,28 +1,79 @@
 #This will be check_access_old
 from ckan.logic import check_access
+from ckan.authz import Authorizer
 
-def package_create(context, data_dict):
+
+
+def package_create(context, data_dict=None):
     model = context['model']
 
-    return {'success':  check_access(model.System(), model.Action.PACKAGE_CREATE, context)}
+    success = (check_access(model.System(), model.Action.PACKAGE_CREATE, context) and
+               check_group_auth(context,data_dict))
+    return {'success':  success}
 
 def resource_create(context, data_dict):
     return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
 
 def package_relationship_create(context, data_dict):
-    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+    model = context['model']
+    user = context['user']
 
-def group_create(context, data_dict):
-    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+    id = data_dict['id']
+    id2 = data_dict['id2']
+    pkg1 = model.Package.get(id)
+    pkg2 = model.Package.get(id2)
+
+    authorized = Authorizer().\
+                    authorized_package_relationship(\
+                    user, pkg1, pkg2, action=model.Action.EDIT)
+
+    return {'success': authorized}
+
+def group_create(context, data_dict=None):
+    model = context['model']
+
+    return {'success':  check_access(model.System(), model.Action.GROUP_CREATE, context)}
 
 def rating_create(context, data_dict):
-    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+    # No authz check in the logic function
+    return {'success': True}
+
+def user_create(context, data_dict=None):
+    model = context['model']
+
+    return {'success': check_access(model.System(), model.Action.USER_CREATE, context)}
+
+def check_group_auth(context, data_dict):
+    model = context['model']
+    pkg = context.get("package")
+
+    ## hack as api does not allow groups
+    if context.get("allow_partial_update"):
+        return True
+
+    group_dicts = data_dict.get("groups", [])
+    groups = set()
+    for group_dict in group_dicts:
+        id = group_dict.get('id')
+        if not id:
+            continue
+        grp = model.Group.get(id)
+        if grp is None:
+            raise NotFound(_('Group was not found.'))
+        groups.add(grp)
+
+    if pkg:
+        groups = groups - set(pkg.groups)
+
+    for group in groups:
+        check_access(group, model.Action.EDIT, context)
+
+    return True
 
 ## Modifications for rest api
 
 def package_create_rest(context, data_dict):
-    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+    return package_create(context, data_dict)
 
 def group_create_rest(context, data_dict):
-    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
-
+    return group_create(context, data_dict)


http://bitbucket.org/okfn/ckan/changeset/95530af14b65/
changeset:   95530af14b65
branch:      feature-1253-authz-refactor
user:        amercader
date:        2011-08-03 18:38:27
summary:     [authz] Make new check_access function raise NotAuthorized. Update create, update and delete action related checks. TODO tests and get related checks.
affected #:  7 files (5.8 KB)

--- a/ckan/logic/__init__.py	Wed Aug 03 10:57:28 2011 +0100
+++ b/ckan/logic/__init__.py	Wed Aug 03 17:38:27 2011 +0100
@@ -1,4 +1,5 @@
 import logging
+from ckan.lib.base import _
 import ckan.authz
 import ckan.new_authz as new_authz
 from ckan.lib.navl.dictization_functions import flatten_dict
@@ -87,7 +88,7 @@
     flattented = flatten_dict(dict)
     return untuplize_dict(flattented)
 
-def check_access_new(action, context, data_dict):
+def check_access_new(action, context, data_dict=None):
     model = context['model']
     user = context.get('user')
 
@@ -100,14 +101,19 @@
         #    log.debug('Valid API key needed to make changes')
         #    raise NotAuthorized
         logic_authorization = new_authz.is_authorized(action, context, data_dict)
-
-        return logic_authorization
+        if not logic_authorization['success']:
+            msg = logic_authorization.get('msg','')
+            raise NotAuthorized(msg)
 
     elif not user:
-        log.debug('No valid API key provided.')
-        return AttributeDict(success=False, msg='No valid API key provided.')
+        msg = _('No valid API key provided.')
+        log.debug(msg)
+        raise NotAuthorized(msg)       
+        #return AttributeDict(success=False, msg='No valid API key provided.')
+
     log.debug('Access OK.')
-    return AttributeDict(success=True)
+    return True
+    #return AttributeDict(success=True)
 
 
 def check_access(entity, action, context):
@@ -119,15 +125,19 @@
     if action and entity and not isinstance(entity, model.PackageRelationship):
         if action != model.Action.READ and user in (model.PSEUDO_USER__VISITOR, ''):
             log.debug('Valid API key needed to make changes')
-            raise NotAuthorized
+            return False
+            #raise NotAuthorized
         
         am_authz = ckan.authz.Authorizer().is_authorized(user, action, entity)
         if not am_authz:
             log.debug('User is not authorized to %s %s' % (action, entity))
-            raise NotAuthorized
+            return False
+            #raise NotAuthorized
     elif not user:
         log.debug('No valid API key provided.')
-        raise NotAuthorized
+        return False
+        #raise NotAuthorized
+
     log.debug('Access OK.')
     return True             
 


--- a/ckan/logic/action/create.py	Wed Aug 03 10:57:28 2011 +0100
+++ b/ckan/logic/action/create.py	Wed Aug 03 17:38:27 2011 +0100
@@ -4,7 +4,7 @@
 from ckan.plugins import (PluginImplementations,
                           IGroupController,
                           IPackageController)
-from ckan.logic import NotFound, NotAuthorized, ValidationError
+from ckan.logic import NotFound, ValidationError
 # check_access will be renamed to check_access_old
 from ckan.logic import check_access_new, check_access
 from ckan.lib.base import _


--- a/ckan/logic/action/delete.py	Wed Aug 03 10:57:28 2011 +0100
+++ b/ckan/logic/action/delete.py	Wed Aug 03 17:38:27 2011 +0100
@@ -1,6 +1,8 @@
-from ckan.logic import NotFound, check_access, NotAuthorized
+from ckan.logic import NotFound
 from ckan.lib.base import _
-import ckan.authz
+# check_access will be renamed to check_access_old
+from ckan.logic import check_access_new, check_access
+
 from ckan.plugins import PluginImplementations, IGroupController, IPackageController
 
 
@@ -11,11 +13,12 @@
     id = context["id"]
 
     entity = model.Package.get(id)
-    check_access(entity, model.Action.PURGE, context)
 
     if entity is None:
         raise NotFound
-    
+
+    check_access_new('package_delete',context)
+
     rev = model.repo.new_revision()
     rev.author = user
     rev.message = _(u'REST API: Delete Package: %s') % entity.name
@@ -23,7 +26,7 @@
     for item in PluginImplementations(IPackageController):
         item.delete(entity)
     entity.delete()
-    model.repo.commit()        
+    model.repo.commit()
 
 
 def package_relationship_delete(context):
@@ -41,12 +44,7 @@
     if not pkg2:
         return NotFound('Second package named in address was not found.')
 
-    am_authorized = ckan.authz.Authorizer().\
-                    authorized_package_relationship(\
-                    user, pkg1, pkg2, action=model.Action.EDIT)
-
-    if not am_authorized:
-        raise NotAuthorized
+    check_access_new('package_relationship_delete', context)
 
     existing_rels = pkg1.get_relationships_with(pkg2, rel)
     if not existing_rels:
@@ -55,7 +53,8 @@
     relationship = existing_rels[0]
     revisioned_details = 'Package Relationship: %s %s %s' % (id, rel, id2)
 
-    check_access(relationship, model.Action.PURGE, context)
+    context['relationship'] = relationship
+    check_access_new('relationship_delete', context)
 
     rev = model.repo.new_revision()
     rev.author = user
@@ -77,7 +76,7 @@
 
     revisioned_details = 'Group: %s' % group.name
 
-    check_access(group, model.Action.PURGE, context)
+    check_access_new('group_delete', context)
 
     rev = model.repo.new_revision()
     rev.author = user


--- a/ckan/logic/action/update.py	Wed Aug 03 10:57:28 2011 +0100
+++ b/ckan/logic/action/update.py	Wed Aug 03 17:38:27 2011 +0100
@@ -2,9 +2,11 @@
 import re
 import datetime
 
-import ckan.authz
 from ckan.plugins import PluginImplementations, IGroupController, IPackageController
-from ckan.logic import NotFound, check_access, NotAuthorized, ValidationError
+from ckan.logic import NotFound, ValidationError
+# check_access will be renamed to check_access_old
+from ckan.logic import check_access_new, check_access
+
 from ckan.lib.base import _
 from ckan.lib.dictization.model_dictize import (package_dictize,
                                                 package_to_api1,
@@ -69,31 +71,6 @@
             error_summary[_(prettify(key))] = error[0]
     return error_summary
 
-def check_group_auth(context, data_dict):
-    model = context['model']
-    pkg = context.get("package")
-
-    ## hack as api does not allow groups
-    if context.get("allow_partial_update"):
-        return
-    
-    group_dicts = data_dict.get("groups", [])
-    groups = set()
-    for group_dict in group_dicts:
-        id = group_dict.get('id')
-        if not id:
-            continue
-        grp = model.Group.get(id)
-        if grp is None:
-            raise NotFound(_('Group was not found.'))
-        groups.add(grp)
-
-    if pkg:
-        groups = groups - set(pkg.groups)
-
-    for group in groups:
-        check_access(group, model.Action.EDIT, context)
-
 def _make_latest_rev_active(context, q):
 
     session = context['model'].Session
@@ -130,7 +107,7 @@
     id = data_dict["id"]
     pkg = model.Package.get(id)
 
-    check_access(pkg, model.Action.EDIT, context)
+    check_access_new('make_latest_pending_package_active', context, data_dict)
 
     #packages
     q = session.query(model.PackageRevision).filter_by(id=pkg.id)
@@ -188,7 +165,7 @@
     if not pkg:
         raise NotFound(_('No package found for this resource, cannot check auth.'))
 
-    check_access(pkg, model.Action.EDIT, context)
+    check_access_new('package_update', context, data_dict)
 
     data, errors = validate(data_dict, schema, context)
 
@@ -225,11 +202,10 @@
         raise NotFound(_('Package was not found.'))
     data_dict["id"] = pkg.id
 
-    check_access(pkg, model.Action.EDIT, context)
+    check_access_new('package_update', context, data_dict)
 
     data, errors = validate(data_dict, schema, context)
-
-    check_group_auth(context, data)
+    
 
     if errors:
         model.Session.rollback()
@@ -269,9 +245,11 @@
         raise NotFound(_('Package was not found.'))
     data_dict["id"] = pkg.id
 
-    check_access(pkg, model.Action.EDIT, context)
+    check_access_new('package_update', context, data_dict)
+
     data, errors = validate(data_dict, schema, context)
 
+
     if errors:
         model.Session.rollback()
         raise ValidationError(errors, package_error_summary(errors))
@@ -311,12 +289,7 @@
     if not pkg2:
         return NotFound('Second package named in address was not found.')
 
-    authorizer = ckan.authz.Authorizer()
-    am_authorized = authorizer.authorized_package_relationship(
-         user, pkg1, pkg2, action=model.Action.EDIT)
-
-    if not am_authorized:
-        raise NotAuthorized
+    check_access_new('package_relationship_update', context, data_dict)
 
     existing_rels = pkg1.get_relationships_with(pkg2, rel)
     if not existing_rels:
@@ -337,7 +310,7 @@
     if group is None:
         raise NotFound('Group was not found.')
 
-    check_access(group, model.Action.EDIT, context)
+    check_access_new('group_update', context, data_dict)
 
     data, errors = validate(data_dict, schema, context)
     if errors:
@@ -377,9 +350,7 @@
     if user_obj is None:
         raise NotFound('User was not found.')
 
-    if not (ckan.authz.Authorizer().is_sysadmin(unicode(user)) or user == user_obj.name) and \
-       not ('reset_key' in data_dict and data_dict['reset_key'] == user_obj.reset_key):
-        raise NotAuthorized( _('User %s not authorized to edit %s') % (str(user), id))
+    check_access_new('user_update', context, data_dict)
 
     data, errors = validate(data_dict, schema, context)
     if errors:
@@ -415,6 +386,7 @@
     if not pkg:
         raise NotFound
 
+
     if id and id != pkg.id:
         pkg_from_data = model.Package.get(id)
         if pkg_from_data != pkg:
@@ -425,8 +397,12 @@
     context["package"] = pkg
     context["allow_partial_update"] = True
     dictized_package = package_api_to_dict(data_dict, context)
+
+    check_access_new('package_update_rest', context, dictized_package)
+
     dictized_after = package_update(context, dictized_package)
 
+
     pkg = context['package']
 
     if api == '1':
@@ -444,11 +420,15 @@
     group = model.Group.get(id)
     context["group"] = group
     context["allow_partial_update"] = True
-    dictized_package = group_api_to_dict(data_dict, context)
-    dictized_after = group_update(context, dictized_package)
+    dictized_group = group_api_to_dict(data_dict, context)
+
+    check_access_new('group_update_rest', context, dictized_group)
+
+    dictized_after = group_update(context, dictized_group)
 
     group = context['group']
 
+
     if api == '1':
         group_dict = group_to_api1(group, context)
     else:


--- a/ckan/logic/auth/create.py	Wed Aug 03 10:57:28 2011 +0100
+++ b/ckan/logic/auth/create.py	Wed Aug 03 17:38:27 2011 +0100
@@ -1,15 +1,22 @@
 #This will be check_access_old
 from ckan.logic import check_access
 from ckan.authz import Authorizer
-
+from ckan.lib.base import _
 
 
 def package_create(context, data_dict=None):
     model = context['model']
+    user = context['user']
 
-    success = (check_access(model.System(), model.Action.PACKAGE_CREATE, context) and
-               check_group_auth(context,data_dict))
-    return {'success':  success}
+    check1 = check_access(model.System(), model.Action.PACKAGE_CREATE, context)
+    if not check1:
+        return {'success': False, 'msg': _('User %s not authorized to create packages') % str(user)}
+    else:
+        check2 = check_group_auth(context,data_dict)
+        if not check2:
+            return {'success': False, 'msg': _('User %s not authorized to edit these groups') % str(user)}
+
+    return {'success': True}
 
 def resource_create(context, data_dict):
     return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
@@ -26,13 +33,21 @@
     authorized = Authorizer().\
                     authorized_package_relationship(\
                     user, pkg1, pkg2, action=model.Action.EDIT)
-
-    return {'success': authorized}
+    
+    if not authorized:
+        return {'success': False, 'msg': _('User %s not authorized to edit these packages') % str(user)}
+    else:
+        return {'success': True}
 
 def group_create(context, data_dict=None):
     model = context['model']
-
-    return {'success':  check_access(model.System(), model.Action.GROUP_CREATE, context)}
+    user = context['user']
+   
+    authorized = check_access(model.System(), model.Action.GROUP_CREATE, context)
+    if not authorized:
+        return {'success': False, 'msg': _('User %s not authorized to create groups') % str(user)}
+    else:
+        return {'success': True}
 
 def rating_create(context, data_dict):
     # No authz check in the logic function
@@ -40,8 +55,13 @@
 
 def user_create(context, data_dict=None):
     model = context['model']
-
-    return {'success': check_access(model.System(), model.Action.USER_CREATE, context)}
+    user = context['user']
+   
+    authorized = check_access(model.System(), model.Action.USER_CREATE, context)
+    if not authorized:
+        return {'success': False, 'msg': _('User %s not authorized to create users') % str(user)}
+    else:
+        return {'success': True}
 
 def check_group_auth(context, data_dict):
     model = context['model']
@@ -66,7 +86,8 @@
         groups = groups - set(pkg.groups)
 
     for group in groups:
-        check_access(group, model.Action.EDIT, context)
+        if not check_access(group, model.Action.EDIT, context):
+            return False
 
     return True
 


--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/ckan/logic/auth/delete.py	Wed Aug 03 17:38:27 2011 +0100
@@ -0,0 +1,52 @@
+#This will be check_access_old
+from ckan.logic import check_access
+from ckan.logic.auth.create import package_relationship_create
+from ckan.authz import Authorizer
+from ckan.lib.base import _
+
+def package_delete(context, data_dict):
+    model = context['model']
+    user = context['user']
+    id = context['id']
+    pkg = model.Package.get(id)
+
+    #TODO: model.Action.CHANGE_STATE or model.Action.PURGE?
+    authorized = check_access(pkg, model.Action.PURGE, context)
+    if not authorized:
+        return {'success': False, 'msg': _('User %s not authorized to delete package %s') % (str(user),id)}
+    else:
+        return {'success': True}
+
+def package_relationship_delete(context, data_dict):
+    return package_relationship_create(context, data_dict)
+
+def relationship_delete(context, data_dict):
+    model = context['model']
+    user = context['user']
+    relationship = context['relationship']
+
+    authorized = check_access(realtionship, model.Action.PURGE, context)
+    if not authorized:
+        return {'success': False, 'msg': _('User %s not authorized to delete relationship %s') % (str(user),id)}
+    else:
+        return {'success': True}
+
+def group_delete(context, data_dict):
+    model = context['model']
+    user = context['user']
+    #group = context['group']
+    id = context['id']
+    pkg = model.Group.get(id)
+
+    authorized = check_access(group, model.Action.PURGE, context)
+    if not authorized:
+        return {'success': False, 'msg': _('User %s not authorized to delete group %s') % (str(user),id)}
+    else:
+        return {'success': True}
+
+def revision_undelete(context, data_dict):
+    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+
+def revision_delete(context, data_dict):
+    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+


--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/ckan/logic/auth/update.py	Wed Aug 03 17:38:27 2011 +0100
@@ -0,0 +1,61 @@
+#This will be check_access_old
+from ckan.logic import check_access
+from ckan.logic.auth.create import check_group_auth, package_relationship_create
+from ckan.authz import Authorizer
+from ckan.lib.base import _
+
+def make_latest_pending_package_active(context, data_dict):
+    return package_update(context, data_dict)
+
+def package_update(context, data_dict):
+    model = context['model']
+    user = context.get('user')
+    id = data_dict['id']
+    pkg = model.Package.get(id)
+
+    check1 = check_access(pkg, model.Action.EDIT, context)
+    if not check1:
+        return {'success': False, 'msg': _('User %s not authorized to edit package %s') % (str(user), pkg.id)}
+    else:
+        check2 = check_group_auth(context,data_dict)
+        if not check2:
+            return {'success': False, 'msg': _('User %s not authorized to edit these groups') % str(user)}
+
+    return {'success': True}
+
+def package_relationship_update(context, data_dict):
+    return package_relationship_create(context, data_dict)
+
+def group_update(context, data_dict):
+    model = context['model']
+    id = data_dict['id']
+    group = model.Group.get(id)
+    user = context['user']
+
+    authorized = check_access(group, model.Action.EDIT, context)
+    if not authorized:
+        return {'success': False, 'msg': _('User %s not authorized to edit group %s') % (str(user),id)}
+    else:
+        return {'success': True}
+
+def user_update(context, data_dict):
+    model = context['model']
+    user = context['user']
+    id = data_dict['id']
+    user_obj = model.User.get(id)
+
+    if not (Authorizer().is_sysadmin(unicode(user)) or user == user_obj.name) and \
+       not ('reset_key' in data_dict and data_dict['reset_key'] == user_obj.reset_key):
+        return {'success': False, 'msg': _('User %s not authorized to edit user %s') % (str(user), id)}
+
+    return {'success': True}
+
+
+## Modifications for rest api
+
+def package_update_rest(context, data_dict):
+    return package_update(context, data_dict)
+
+def group_update_rest(context, data_dict):
+    return group_update(context, data_dict)
+


http://bitbucket.org/okfn/ckan/changeset/de9e2294be84/
changeset:   de9e2294be84
branch:      feature-1253-authz-refactor
user:        amercader
date:        2011-08-05 13:09:51
summary:     [authz] Move show related checks
affected #:  2 files (4.6 KB)

--- a/ckan/logic/action/get.py	Wed Aug 03 17:38:27 2011 +0100
+++ b/ckan/logic/action/get.py	Fri Aug 05 12:09:51 2011 +0100
@@ -1,12 +1,12 @@
 from sqlalchemy.sql import select
 from sqlalchemy import or_, and_, func, desc
 
-from ckan.logic import NotFound, check_access
+from ckan.logic import NotFound
+from ckan.logic import check_access_new, check_access
 from ckan.plugins import (PluginImplementations,
                           IGroupController,
                           IPackageController)
-import ckan.authz
-
+from ckan.authz import Authorizer
 from ckan.lib.dictization import table_dictize
 from ckan.lib.dictization.model_dictize import (package_dictize,
                                                 resource_list_dictize,
@@ -30,7 +30,7 @@
     api = context.get("api_version", '1')
     ref_package_by = 'id' if api == '2' else 'name'
 
-    query = ckan.authz.Authorizer().authorized_query(user, model.Package)
+    query = Authorizer().authorized_query(user, model.Package)
     packages = query.all()
     return [getattr(p, ref_package_by) for p in packages]
 
@@ -39,7 +39,7 @@
     user = context["user"]
     limit = data_dict.get("limit")
 
-    q = ckan.authz.Authorizer().authorized_query(user, model.PackageRevision)
+    q = Authorizer().authorized_query(user, model.PackageRevision)
     q = q.filter(model.PackageRevision.state=='active')
     q = q.filter(model.PackageRevision.current==True)
 
@@ -52,7 +52,7 @@
         result_dict = table_dictize(package, context)
         res_rev = model.resource_revision_table
         resource_group = model.resource_group_table
-        q = select([res_rev], from_obj = res_rev.join(resource_group, 
+        q = select([res_rev], from_obj = res_rev.join(resource_group,
                    resource_group.c.id == res_rev.c.resource_group_id))
         q = q.where(resource_group.c.package_id == package.id)
         result = q.where(res_rev.c.current == True).execute()
@@ -64,7 +64,7 @@
                 result_dict['isopen'] = isopen
             except KeyError:
                 # TODO: create a log message this error?
-                result_dict['isopen'] = False 
+                result_dict['isopen'] = False
         else:
             result_dict['isopen'] = False
         package_list.append(result_dict)
@@ -82,7 +82,8 @@
     pkg = model.Package.get(id)
     if pkg is None:
         raise NotFound
-    check_access(pkg, model.Action.READ, context)
+
+    check_access_new('package_show',context, data_dict)
 
     revision_dicts = []
     for revision, object_revisions in pkg.all_related_revisions:
@@ -101,7 +102,7 @@
 
     all_fields = data_dict.get('all_fields',None)
 
-    query = ckan.authz.Authorizer().authorized_query(user, model.Group)
+    query = Authorizer().authorized_query(user, model.Group)
     query = query.order_by(model.Group.name.asc())
     query = query.order_by(model.Group.title.asc())
 
@@ -111,7 +112,7 @@
         group_list = [getattr(p, ref_group_by) for p in groups]
     else:
         group_list = group_list_dictize(groups,context)
-    
+
     return group_list
 
 def group_list_authz(context, data_dict):
@@ -119,7 +120,7 @@
     user = context['user']
     pkg = context.get('package')
 
-    query = ckan.authz.Authorizer().authorized_query(user, model.Group, model.Action.EDIT)
+    query = Authorizer().authorized_query(user, model.Group, model.Action.EDIT)
     groups = set(query.all())
     return dict((group.id, group.name) for group in groups)
 
@@ -128,7 +129,7 @@
     user = context['user']
     pkg = context.get('package')
 
-    query = ckan.authz.Authorizer().authorized_query(user, model.Group, model.Action.EDIT)
+    query = Authorizer().authorized_query(user, model.Group, model.Action.EDIT)
     groups = set(query.all())
 
     if pkg:
@@ -142,7 +143,8 @@
     group = model.Group.get(id)
     if group is None:
         raise NotFound
-    check_access(group, model.Action.READ, context)
+
+    check_access_new('group_show',context, data_dict)
 
     revision_dicts = []
     for revision, object_revisions in group.all_related_revisions:
@@ -180,8 +182,8 @@
                   username=user)
         tags = query.results
     else:
-        tags = model.Session.query(model.Tag).all() 
-    
+        tags = model.Session.query(model.Tag).all()
+
     tag_list = []
     if all_fields:
         for tag in tags:
@@ -247,15 +249,15 @@
     if rel == 'relationships':
         rel = None
 
-    relationships = ckan.authz.Authorizer().\
+    relationships = Authorizer().\
                     authorized_package_relationships(\
                     user, pkg1, pkg2, rel, model.Action.READ)
 
     if rel and not relationships:
         raise NotFound('Relationship "%s %s %s" not found.'
                                  % (id, rel, id2))
-    
-    relationship_dicts = [rel.as_dict(pkg1, ref_package_by=ref_package_by) 
+
+    relationship_dicts = [rel.as_dict(pkg1, ref_package_by=ref_package_by)
                           for rel in relationships]
 
     return relationship_dicts
@@ -272,7 +274,8 @@
 
     if pkg is None:
         raise NotFound
-    check_access(pkg, model.Action.READ, context)
+
+    check_access_new('package_show',context, data_dict)
 
     package_dict = package_dictize(pkg, context)
 
@@ -309,7 +312,7 @@
     if group is None:
         raise NotFound
 
-    check_access(group, model.Action.READ, context)
+    check_access_new('group_show',context, data_dict)
 
     group_dict = group_dictize(group, context)
 
@@ -332,6 +335,8 @@
     if tag is None:
         raise NotFound
 
+    check_access_new('tag_show',context, data_dict)
+
     tag_dict = tag_dictize(tag,context)
     extended_packages = []
     for package in tag_dict['packages']:
@@ -344,24 +349,27 @@
 def user_show(context, data_dict):
     '''Shows user details'''
     model = context['model']
+    user = context['user']
 
     id = data_dict.get('id',None)
     provided_user = data_dict.get('user_obj',None)
     if id:
-        user = model.User.get(id)
-        context['user_obj'] = user
-        if user is None:
+        user_obj = model.User.get(id)
+        context['user_obj'] = user_obj
+        if user_obj is None:
             raise NotFound
     elif provided_user:
-        context['user_obj'] = user = provided_user
+        context['user_obj'] = user_obj = provided_user
     else:
         raise NotFound
 
-    user_dict = user_dictize(user,context)
+    check_access_new('user_show',context, data_dict)
+
+    user_dict = user_dictize(user_obj,context)
 
     revisions_q = model.Session.query(model.Revision
-            ).filter_by(author=user.name)
-    
+            ).filter_by(author=user_obj.name)
+
     revisions_list = []
     for revision in revisions_q.limit(20).all():
         revision_dict = revision_show(context,{'id':revision.id})
@@ -374,6 +382,8 @@
 
 def package_show_rest(context, data_dict):
 
+    check_access_new('package_show_rest',context, data_dict)
+
     package_show(context, data_dict)
 
     api = context.get('api_version') or '1'
@@ -388,6 +398,8 @@
 
 def group_show_rest(context, data_dict):
 
+    check_access_new('group_show_rest',context, data_dict)
+
     group_show(context, data_dict)
     api = context.get('api_version') or '1'
     group = context['group']
@@ -401,6 +413,8 @@
 
 def tag_show_rest(context, data_dict):
 
+    check_access_new('tag_show_rest',context, data_dict)
+
     tag_show(context, data_dict)
     api = context.get('api_version') or '1'
     tag = context['tag']
@@ -422,7 +436,7 @@
     like_q = u"%s%%" % q
 
     #TODO: Auth
-    pkg_query = ckan.authz.Authorizer().authorized_query(user, model.Package)
+    pkg_query = Authorizer().authorized_query(user, model.Package)
     pkg_query = session.query(model.Package) \
                     .filter(or_(model.Package.name.ilike(like_q),
                                 model.Package.title.ilike(like_q)))
@@ -511,6 +525,8 @@
     session = context['session']
     user = context['user']
 
+    check_access_new('package_search', context, data_dict)
+
     q=data_dict.get('q','')
     fields=data_dict.get('fields',[])
     facet_by=data_dict.get('facet_by',[])
@@ -530,7 +546,7 @@
               filter_by_openness=filter_by_openness,
               filter_by_downloadable=filter_by_downloadable,
               username=user)
-    
+
     results = []
     for package in query.results:
         result_dict = table_dictize(package, context)


--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/ckan/logic/auth/get.py	Fri Aug 05 12:09:51 2011 +0100
@@ -0,0 +1,135 @@
+#This will be check_access_old
+from ckan.logic import check_access, NotFound
+from ckan.authz import Authorizer
+from ckan.lib.base import _
+
+
+
+def site_read(context, data_dict):
+    """\
+    This function should be deprecated. It is only here because we couldn't
+    get hold of Friedrich to ask what it was for.
+
+    ./ckan/controllers/api.py
+    """
+    return {'success': True}
+
+def package_search(context, data_dict):
+    """\
+    Everyone can search by default
+    """
+    return {'success': True}
+
+def package_list(context, data_dict):
+    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+
+def current_package_list_with_resources(context, data_dict):
+    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+
+def revision_list(context, data_dict):
+    """\
+    from controller/revision __before__
+    if not self.authorizer.am_authorized(c, model.Action.SITE_READ, model.System): abort
+    -> In our new model everyone can read the revison list
+    """
+    return {'success': True}
+
+def revision_diff(context, data_dict):
+    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+
+def group_revision_list(context, data_dict):
+    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+
+def package_revision_list(context, data_dict):
+    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+
+def group_list(context, data_dict):
+    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+
+def group_list_authz(context, data_dict):
+    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+
+def group_list_availible(context, data_dict):
+    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+
+def licence_list(context, data_dict):
+    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+
+def tag_list(context, data_dict):
+    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+
+def package_relationship_list(context, data_dict):
+    model = context['model']
+    user = context['user']
+
+    id = data_dict['id']
+    id2 = data_dict['id2']
+    pkg1 = model.Package.get(id)
+    pkg2 = model.Package.get(id2)
+
+    authorized = Authorizer().\
+                    authorized_package_relationship(\
+                    user, pkg1, pkg2, action=model.Action.READ)
+    
+    if not authorized:
+        return {'success': False, 'msg': _('User %s not authorized to read these packages') % str(user)}
+    else:
+        return {'success': True}
+
+def package_show(context, data_dict):
+    model = context['model']
+    user = context['user']
+    if not 'package' in context:
+        id = data_dict.get('id',None)
+        package = model.Package.get(id)
+        if not package:
+            raise NotFound
+    else:
+        package = context['package']
+
+    authorized =  check_access(package, model.Action.READ, context)
+    if not authorized:
+        return {'success': False, 'msg': _('User %s not authorized to read package %s') % (str(user),package.id)}
+    else:
+        return {'success': True}
+
+def revision_show(context, data_dict):
+    # No authz check in the logic function
+    return {'success': True}
+
+def group_show(context, data_dict):
+    model = context['model']
+    user = context['user']
+    if not 'group' in context:
+        id = data_dict.get('id',None)
+        group = model.Group.get(id)
+        if not group:
+            raise NotFound
+    else:
+        group = context['group']
+
+    authorized =  check_access(group, model.Action.READ, context)
+    if not authorized:
+        return {'success': False, 'msg': _('User %s not authorized to read group %s') % (str(user),group.id)}
+    else:
+        return {'success': True}
+
+def tag_show(context, data_dict):
+    # No authz check in the logic function
+    return {'success': True}
+
+def user_show(context, data_dict):
+    # By default, user details can be read by anyone, but some properties like
+    # the API key are stripped at the action level if not not logged in.
+    return {'success': True}
+
+## Modifications for rest api
+
+def package_show_rest(context, data_dict):
+    return package_show(context, data_dict)
+
+def group_show_rest(context, data_dict):
+    return group_show(context, data_dict)
+
+def tag_show_rest(context, data_dict):
+    return tag_show(context, data_dict)


http://bitbucket.org/okfn/ckan/changeset/b4f2620c79ea/
changeset:   b4f2620c79ea
branch:      feature-1253-authz-refactor
user:        amercader
date:        2011-08-05 13:27:14
summary:     Make sure API key is only used if sysadmin or same user
affected #:  2 files (1.1 KB)

--- a/ckan/logic/action/get.py	Fri Aug 05 12:09:51 2011 +0100
+++ b/ckan/logic/action/get.py	Fri Aug 05 12:27:14 2011 +0100
@@ -367,6 +367,11 @@
 
     user_dict = user_dictize(user_obj,context)
 
+    if not (Authorizer().is_sysadmin(unicode(user)) or user == user_obj.name):
+        # If not sysadmin or the same user, strip sensible info
+        del user_dict['apikey']
+        del user_dict['reset_key']
+
     revisions_q = model.Session.query(model.Revision
             ).filter_by(author=user_obj.name)
 


--- a/ckan/tests/functional/api/test_action.py	Fri Aug 05 12:09:51 2011 +0100
+++ b/ckan/tests/functional/api/test_action.py	Fri Aug 05 12:27:14 2011 +0100
@@ -108,6 +108,7 @@
         assert not 'apikey' in res_obj['result'][0]
 
     def test_05_user_show(self):
+        # Anonymous request
         postparams = '%s=1' % json.dumps({'id':'annafan'})
         res = self.app.post('/api/action/user_show', params=postparams)
         res_obj = json.loads(res.body)
@@ -116,12 +117,33 @@
         result = res_obj['result']
         assert result['name'] == 'annafan'
         assert result['about'] == 'I love reading Annakarenina. My site: <a href="http://anna.com">anna.com</a>'
-        assert 'apikey' in result
         assert 'activity' in result
         assert 'created' in result
         assert 'display_name' in result
         assert 'number_administered_packages' in result
         assert 'number_of_edits' in result
+        assert not 'apikey' in result
+        assert not 'reset_key' in result
+
+        # Same user can see his api key
+        res = self.app.post('/api/action/user_show', params=postparams,
+                            extra_environ={'Authorization': str(self.normal_user.apikey)})
+
+        res_obj = json.loads(res.body)
+        result = res_obj['result']
+        assert result['name'] == 'annafan'
+        assert 'apikey' in result
+        assert 'reset_key' in result
+
+        # Sysadmin user can see everyone's api key
+        res = self.app.post('/api/action/user_show', params=postparams,
+                            extra_environ={'Authorization': str(self.sysadmin_user.apikey)})
+
+        res_obj = json.loads(res.body)
+        result = res_obj['result']
+        assert result['name'] == 'annafan'
+        assert 'apikey' in result
+        assert 'reset_key' in result
 
     def test_06_tag_list(self):
         postparams = '%s=1' % json.dumps({})


http://bitbucket.org/okfn/ckan/changeset/83eb5f1fd31e/
changeset:   83eb5f1fd31e
branch:      feature-1253-authz-refactor
user:        amercader
date:        2011-08-05 19:17:13
summary:     [authz] Move listings checks. Some tests still failing.
affected #:  4 files (1.8 KB)

--- a/ckan/logic/__init__.py	Fri Aug 05 12:27:14 2011 +0100
+++ b/ckan/logic/__init__.py	Fri Aug 05 18:17:13 2011 +0100
@@ -104,13 +104,14 @@
         if not logic_authorization['success']:
             msg = logic_authorization.get('msg','')
             raise NotAuthorized(msg)
-
+    #TODO: Is this really necessary?
+    '''
     elif not user:
         msg = _('No valid API key provided.')
         log.debug(msg)
         raise NotAuthorized(msg)       
         #return AttributeDict(success=False, msg='No valid API key provided.')
-
+    '''
     log.debug('Access OK.')
     return True
     #return AttributeDict(success=True)


--- a/ckan/logic/action/get.py	Fri Aug 05 12:27:14 2011 +0100
+++ b/ckan/logic/action/get.py	Fri Aug 05 18:17:13 2011 +0100
@@ -24,13 +24,19 @@
 from ckan.lib.search import query_for
 
 def package_list(context, data_dict):
-    '''Lists the package by name'''
+    '''Lists packages by name or id'''
+
     model = context["model"]
     user = context["user"]
     api = context.get("api_version", '1')
     ref_package_by = 'id' if api == '2' else 'name'
+    
+    check_access_new('package_list', context, data_dict)
 
-    query = Authorizer().authorized_query(user, model.Package)
+    query = model.Session.query(model.PackageRevision)
+    query = query.filter(model.PackageRevision.state=='active')
+    query = query.filter(model.PackageRevision.current==True)
+
     packages = query.all()
     return [getattr(p, ref_package_by) for p in packages]
 
@@ -39,23 +45,25 @@
     user = context["user"]
     limit = data_dict.get("limit")
 
-    q = Authorizer().authorized_query(user, model.PackageRevision)
-    q = q.filter(model.PackageRevision.state=='active')
-    q = q.filter(model.PackageRevision.current==True)
+    check_access_new('current_package_list_with_resources', context, data_dict)
 
-    q = q.order_by(model.package_revision_table.c.revision_timestamp.desc())
+    query = model.Session.query(model.PackageRevision)
+    query = query.filter(model.PackageRevision.state=='active')
+    query = query.filter(model.PackageRevision.current==True)
+
+    query = query.order_by(model.package_revision_table.c.revision_timestamp.desc())
     if limit:
-        q = q.limit(limit)
-    pack_rev = q.all()
+        query = query.limit(limit)
+    pack_rev = query.all()
     package_list = []
     for package in pack_rev:
         result_dict = table_dictize(package, context)
         res_rev = model.resource_revision_table
         resource_group = model.resource_group_table
-        q = select([res_rev], from_obj = res_rev.join(resource_group,
+        query = select([res_rev], from_obj = res_rev.join(resource_group,
                    resource_group.c.id == res_rev.c.resource_group_id))
-        q = q.where(resource_group.c.package_id == package.id)
-        result = q.where(res_rev.c.current == True).execute()
+        query = query.where(resource_group.c.package_id == package.id)
+        result = query.where(res_rev.c.current == True).execute()
         result_dict["resources"] = resource_list_dictize(result, context)
         license_id = result_dict['license_id']
         if license_id:
@@ -72,7 +80,10 @@
 
 def revision_list(context, data_dict):
 
-    model = context["model"]
+    model = context['model']
+
+    check_access_new('revision_list', context, data_dict)
+
     revs = model.Session.query(model.Revision).all()
     return [rev.id for rev in revs]
 
@@ -83,7 +94,7 @@
     if pkg is None:
         raise NotFound
 
-    check_access_new('package_show',context, data_dict)
+    check_access_new('package_revision_list',context, data_dict)
 
     revision_dicts = []
     for revision, object_revisions in pkg.all_related_revisions:
@@ -101,11 +112,17 @@
     ref_group_by = 'id' if api == '2' else 'name';
 
     all_fields = data_dict.get('all_fields',None)
+   
+    check_access_new('group_list',context, data_dict)
 
-    query = Authorizer().authorized_query(user, model.Group)
+    # We need Groups for group_list_dictize
+    query = model.Session.query(model.Group).join(model.GroupRevision)
+    query = query.filter(model.GroupRevision.state=='active')
+    query = query.filter(model.GroupRevision.current==True)
     query = query.order_by(model.Group.name.asc())
     query = query.order_by(model.Group.title.asc())
 
+
     groups = query.all()
 
     if not all_fields:
@@ -118,9 +135,13 @@
 def group_list_authz(context, data_dict):
     model = context['model']
     user = context['user']
-    pkg = context.get('package')
 
-    query = Authorizer().authorized_query(user, model.Group, model.Action.EDIT)
+    check_access_new('group_list_authz',context, data_dict)
+
+    query = model.Session.query(model.GroupRevision)
+    query = query.filter(model.GroupRevision.state=='active')
+    query = query.filter(model.GroupRevision.current==True)
+
     groups = set(query.all())
     return dict((group.id, group.name) for group in groups)
 
@@ -129,7 +150,12 @@
     user = context['user']
     pkg = context.get('package')
 
-    query = Authorizer().authorized_query(user, model.Group, model.Action.EDIT)
+    check_access_new('group_list_available',context, data_dict)
+
+    query = model.Session.query(model.GroupRevision)
+    query = query.filter(model.GroupRevision.state=='active')
+    query = query.filter(model.GroupRevision.current==True)
+
     groups = set(query.all())
 
     if pkg:
@@ -144,7 +170,7 @@
     if group is None:
         raise NotFound
 
-    check_access_new('group_show',context, data_dict)
+    check_access_new('group_revision_list',context, data_dict)
 
     revision_dicts = []
     for revision, object_revisions in group.all_related_revisions:
@@ -155,6 +181,9 @@
 
 def licence_list(context, data_dict):
     model = context["model"]
+
+    check_access_new('licence_list',context, data_dict)
+
     license_register = model.Package.get_license_register()
     licenses = license_register.values()
     licences = [l.as_dict() for l in licenses]
@@ -168,6 +197,8 @@
 
     all_fields = data_dict.get('all_fields',None)
 
+    check_access_new('tag_list',context, data_dict)
+
     q = data_dict.get('q','')
     if q:
         limit = data_dict.get('limit',25)
@@ -199,6 +230,8 @@
     model = context['model']
     user = context['user']
 
+    check_access_new('user_list',context, data_dict)
+
     q = data_dict.get('q','')
     order_by = data_dict.get('order_by','name')
 
@@ -249,6 +282,9 @@
     if rel == 'relationships':
         rel = None
 
+    check_access_new('package_relationships_list',context, data_dict)
+    
+    # TODO: How to handle this object level authz?
     relationships = Authorizer().\
                     authorized_package_relationships(\
                     user, pkg1, pkg2, rel, model.Action.READ)
@@ -433,6 +469,7 @@
 
 def package_autocomplete(context, data_dict):
     '''Returns packages containing the provided string'''
+
     model = context['model']
     session = context['session']
     user = context['user']
@@ -440,26 +477,31 @@
 
     like_q = u"%s%%" % q
 
-    #TODO: Auth
-    pkg_query = Authorizer().authorized_query(user, model.Package)
-    pkg_query = session.query(model.Package) \
-                    .filter(or_(model.Package.name.ilike(like_q),
-                                model.Package.title.ilike(like_q)))
-    pkg_query = pkg_query.limit(10)
+    check_access_new('package_autocomplete', context, data_dict)
+
+    query = model.Session.query(model.PackageRevision)
+    query = query.filter(model.PackageRevision.state=='active')
+    query = query.filter(model.PackageRevision.current==True)
+    query = query.filter(or_(model.PackageRevision.name.ilike(like_q),
+                                model.PackageRevision.title.ilike(like_q)))
+    query = query.limit(10)
 
     pkg_list = []
-    for package in pkg_query:
-        result_dict = table_dictize(package, context)
+    for package in query:
+        result_dict = {'name':package.name,'title':package.title}
         pkg_list.append(result_dict)
 
     return pkg_list
 
 def tag_autocomplete(context, data_dict):
     '''Returns tags containing the provided string'''
+
     model = context['model']
     session = context['session']
     user = context['user']
 
+    check_access_new('tag_autocomplete', context, data_dict)
+
     q = data_dict.get('q',None)
     if not q:
         return []
@@ -482,6 +524,8 @@
     session = context['session']
     user = context['user']
 
+    check_access_new('format_autocomplete', context, data_dict)
+
     q = data_dict.get('q', None)
     if not q:
         return []
@@ -511,6 +555,8 @@
     if not q:
         return []
 
+    check_access_new('user_autocomplete', context, data_dict)
+
     limit = data_dict.get('limit',20)
 
     query = model.User.search(q).limit(limit)


--- a/ckan/logic/auth/get.py	Fri Aug 05 12:27:14 2011 +0100
+++ b/ckan/logic/auth/get.py	Fri Aug 05 18:17:13 2011 +0100
@@ -15,16 +15,15 @@
     return {'success': True}
 
 def package_search(context, data_dict):
-    """\
-    Everyone can search by default
-    """
+    # Everyone can search by default
     return {'success': True}
 
 def package_list(context, data_dict):
-    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+    # List of all active packages are visible by default
+    return {'success': True}
 
 def current_package_list_with_resources(context, data_dict):
-    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+    return package_list(context, data_dict)
 
 def revision_list(context, data_dict):
     """\
@@ -32,31 +31,36 @@
     if not self.authorizer.am_authorized(c, model.Action.SITE_READ, model.System): abort
     -> In our new model everyone can read the revison list
     """
+    # In our new model everyone can read the revison list
     return {'success': True}
 
-def revision_diff(context, data_dict):
-    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
-
 def group_revision_list(context, data_dict):
-    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+    return group_show(context, data_dict)
 
 def package_revision_list(context, data_dict):
-    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+    return package_show(context, data_dict)
 
 def group_list(context, data_dict):
-    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+    # List of all active groups is visible by default
+    return {'success': True}
 
 def group_list_authz(context, data_dict):
-    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+    return group_list(context, data_dict)
 
-def group_list_availible(context, data_dict):
-    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+def group_list_available(context, data_dict):
+    return group_list(context, data_dict)
 
 def licence_list(context, data_dict):
-    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+    # Licences list is visible by default
+    return {'success': True}
 
 def tag_list(context, data_dict):
-    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+    # Tags list is visible by default
+    return {'success': True}
+
+def user_list(context, data_dict):
+    # Users list is visible by default
+    return {'success': True}
 
 def package_relationship_list(context, data_dict):
     model = context['model']
@@ -70,7 +74,7 @@
     authorized = Authorizer().\
                     authorized_package_relationship(\
                     user, pkg1, pkg2, action=model.Action.READ)
-    
+
     if not authorized:
         return {'success': False, 'msg': _('User %s not authorized to read these packages') % str(user)}
     else:
@@ -123,6 +127,21 @@
     # the API key are stripped at the action level if not not logged in.
     return {'success': True}
 
+def package_autocomplete(context, data_dict):
+    return package_list(context, data_dict)
+
+def group_autocomplete(context, data_dict):
+    return group_list(context, data_dict)
+
+def tag_autocomplete(context, data_dict):
+    return tag_list(context, data_dict)
+
+def user_autocomplete(context, data_dict):
+    return user_list(context, data_dict)
+
+def format_autocomplete(context, data_dict):
+    return {'success': True}
+
 ## Modifications for rest api
 
 def package_show_rest(context, data_dict):


--- a/ckan/tests/functional/api/test_action.py	Fri Aug 05 12:27:14 2011 +0100
+++ b/ckan/tests/functional/api/test_action.py	Fri Aug 05 18:17:13 2011 +0100
@@ -36,16 +36,17 @@
         res = self.app.post('/api/action/package_list', params=postparams)
         assert_dicts_equal_ignoring_ordering(
             json.loads(res.body),
-            {"help": "Lists the package by name",
+            {"help": "Lists packages by name or id",
              "success": True,
              "result": ["annakarenina", "warandpeace"]})
         
     def test_02_package_autocomplete(self):
-        postparams = '%s=1' % json.dumps({'q':'a'})
+        postparams = '%s=1' % json.dumps({'q':'war'})
         res = self.app.post('/api/action/package_autocomplete', params=postparams)
         res_obj = json.loads(res.body)
         assert res_obj['success'] == True
-        assert res_obj['result'][0]['name'] == 'annakarenina'
+        pprint(res_obj['result'][0]['name'])
+        assert res_obj['result'][0]['name'] == 'warandpeace'
 
     def test_03_create_update_package(self):

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