[ckan-changes] commit/ckan: amercader: Preliminary draft wiht package_create

Bitbucket commits-noreply at bitbucket.org
Tue Aug 2 12:19:38 UTC 2011


1 new changeset in ckan:

http://bitbucket.org/okfn/ckan/changeset/dd5b7e78b030/
changeset:   dd5b7e78b030
branch:      feature-1253-authz-refactor
user:        amercader
date:        2011-08-02 14:19:21
summary:     Preliminary draft wiht package_create
affected #:  6 files (5.0 KB)

--- a/ckan/logic/__init__.py	Fri Jul 29 19:04:17 2011 +0200
+++ b/ckan/logic/__init__.py	Tue Aug 02 13:19:21 2011 +0100
@@ -1,9 +1,23 @@
 import logging
 import ckan.authz
+import ckan.new_authz as new_authz
 from ckan.lib.navl.dictization_functions import flatten_dict
 from ckan.plugins import PluginImplementations
 from ckan.plugins.interfaces import IActions
 
+class AttributeDict(dict):
+    def __getattr__(self, name):
+        try:
+            return self[name]
+        except KeyError:
+            raise AttributeError('No such attribute %r'%name)
+
+    def __setattr__(self, name, value):
+        raise AttributeError(
+            'You cannot set attributes of this object directly'
+        )
+
+
 class ActionError(Exception):
     def __init__(self, extra_msg=None):
         self.extra_msg = extra_msg
@@ -73,6 +87,33 @@
     flattented = flatten_dict(dict)
     return untuplize_dict(flattented)
 
+def check_access_new(action, context, data_dict):
+    model = context['model']
+    user = context.get('user')
+
+    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")
+        #    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)
+        '''
+    elif not user:
+        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")


--- a/ckan/logic/action/create.py	Fri Jul 29 19:04:17 2011 +0200
+++ b/ckan/logic/action/create.py	Tue Aug 02 13:19:21 2011 +0100
@@ -4,7 +4,9 @@
 from ckan.plugins import (PluginImplementations,
                           IGroupController,
                           IPackageController)
-from ckan.logic import NotFound, check_access, NotAuthorized, ValidationError
+from ckan.logic import NotFound, NotAuthorized, 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_to_api1,
                                                 package_to_api2,
@@ -41,7 +43,7 @@
     model.Session.remove()
     model.Session()._context = context
 
-    check_access(model.System(), model.Action.PACKAGE_CREATE, context)
+    check_access_new("package_create",context,data_dict)
     check_group_auth(context, data_dict)
 
     data, errors = validate(data_dict, schema, context)


--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/ckan/logic/auth/create.py	Tue Aug 02 13:19:21 2011 +0100
@@ -0,0 +1,28 @@
+#This will be check_access_old
+from ckan.logic import check_access
+
+def package_create(context, data_dict):
+    model = context['model']
+
+    return {'success':  check_access(model.System(), model.Action.PACKAGE_CREATE, context)}
+
+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'}
+
+def group_create(context, data_dict):
+    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+
+def rating_create(context, data_dict):
+    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+
+## Modifications for rest api
+
+def package_create_rest(context, data_dict):
+    return {'success': False, 'msg': 'Not implemented yet in the auth refactor'}
+
+def group_create_rest(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/new_authz.py	Tue Aug 02 13:19:21 2011 +0100
@@ -0,0 +1,58 @@
+from logging import getLogger
+from ckan.plugins import implements, SingletonPlugin
+from ckan.plugins import IAuthFunctions
+from ckan.plugins import PluginImplementations
+
+log = getLogger(__name__)
+
+# This is a private cache used by get_auth_function() and should never
+# be accessed directly
+_auth_functions = {}
+
+def is_authorized(action, context,data_dict=None):
+    auth_function = _get_auth_function(action)
+    if auth_function:
+        return auth_function(context, data_dict)
+    else:
+        return {'success': True}
+
+def _get_auth_function(action):
+    if _auth_functions:
+        return _auth_functions.get(action)
+    # Otherwise look in all the plugins to resolve all possible
+    # First get the default ones in the ckan/logic/auth directory
+    # Rather than writing them out in full will use __import__
+    # to load anything from ckan.auth that looks like it might
+    # be an authorisation function
+    for auth_module_name in ['get', 'create', 'update']:
+        module_path = 'ckan.logic.auth.'+auth_module_name
+        try:
+            module = __import__(module_path)
+        except ImportError,e:
+            log.debug('No auth module for action "%s"' % auth_module_name)
+            continue
+
+        for part in module_path.split('.')[1:]:
+            module = getattr(module, part)
+        for k, v in module.__dict__.items():
+            if not k.startswith('_'):
+                _auth_functions[k] = v
+    # Then overwrite them with any specific ones in the plugins:
+    resolved_auth_function_plugins = {}
+    fetched_auth_functions = {}
+    for plugin in PluginImplementations(IAuthFunctions):
+        for name, auth_function in plugin.get_auth_functions().items():
+            if name in resolved_auth_function_plugins:
+                raise Exception(
+                    'The auth function %r is already implemented in %r' % (
+                        name,
+                        resolved_auth_function_plugins[name]
+                    )
+                )
+            log.debug('Auth function %r was inserted', plugin.name)
+            resolved_auth_function_plugins[name] = plugin.name
+            fetched_auth_functions[name] = auth_function
+    # Use the updated ones in preference to the originals.
+    _auth_functions.update(fetched_auth_functions)
+    return _auth_functions.get(action)
+


--- a/ckan/plugins/interfaces.py	Fri Jul 29 19:04:17 2011 +0200
+++ b/ckan/plugins/interfaces.py	Tue Aug 02 13:19:21 2011 +0100
@@ -8,6 +8,7 @@
     'IGenshiStreamFilter', 'IRoutes',
     'IMapper', 'ISession',
     'IMiddleware',
+    'IAuthFunctions',
     'IDomainObjectModification', 'IGroupController', 
     'IPackageController', 'IPluginObserver',
     'IConfigurable', 'IConfigurer', 'IAuthorizer',
@@ -310,3 +311,14 @@
         Should return a dict, the keys being the name of the logic 
         function and the values being the functions themselves.
         """
+
+class IAuthFunctions(Interface):
+    """
+    Allow customisation of default Authorization implementation
+    """
+    def get_auth_functions(self):
+        """
+        Returns a dict of all the authorization functions which the
+        implementation overrides
+        """
+

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