Added a merge_params and check_access decorator
authorSverre Rabbelier <srabbelier@gmail.com>
Wed, 21 Jan 2009 16:12:01 +0000
changeset 873 cbb1d15ffe91
parent 872 70e0b6d8ff73
child 874 30e9629bf590
Added a merge_params and check_access decorator The merge_params decorator is very simple and takes self._params and merges it with params. It's main purpose is to explicitly mark the views in which it is intended that self._params is merged raw. The check_access decorator factors out the access checking process and passes args and kwargs to the access checking methods. Patch by: Sverre Rabbelier
app/soc/views/helper/decorators.py
--- a/app/soc/views/helper/decorators.py	Wed Jan 21 16:11:47 2009 +0000
+++ b/app/soc/views/helper/decorators.py	Wed Jan 21 16:12:01 2009 +0000
@@ -30,6 +30,12 @@
 
 from django import http
 
+from soc.logic import dicts
+
+
+class Error(Exception):
+  pass
+
 
 def view(func):
   """Decorator that insists that exceptions are handled by view.
@@ -48,4 +54,49 @@
       logging.exception('AssertionError')
       return http.HttpResponse('AssertionError')
 
-  return view_wrapper
\ No newline at end of file
+  return view_wrapper
+
+
+def merge_params(func):
+  """Decorator that merges 'params' with self._params
+  """
+
+  @wraps(func)
+  def wrapper(self, *args, **kwargs):
+    params = kwargs.get('params', {})
+    kwargs['params'] = dicts.merge(params, self._params)
+    return func(self, *args, **kwargs)
+
+  return wrapper
+
+
+def check_access(func):
+  """This decorator does access checks for the specified view method
+
+  The rights dictionary is extracted from 'params', or, if either 'params' or
+  'rights' do not exist, from self._params['rights'].
+  """
+
+  # Do not pollute helper.decorators with access specific imports
+  from soc.views import out_of_band
+  from soc.views import helper
+  from soc.views.helper import access
+
+  @wraps(func)
+  def wrapper(self, request, access_type, *args, **kwargs):
+    params = kwargs.get('params', {})
+
+    # Try to extract rights
+    if 'rights' in params:
+      rights = params['rights']
+    else:
+      rights = self._params['rights']
+
+    # Do the access check dance
+    try:
+      access.checkAccess(access_type, request, rights, args, kwargs)
+    except out_of_band.Error, error:
+      return helper.responses.errorResponse(error, request)
+    return func(self, request, access_type, *args, **kwargs)
+
+  return wrapper