daily pastebin goal
81%
SHARE
TWEET

Untitled

a guest Dec 1st, 2012 41 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from functools import wraps
  2. from django.db.models import Model, get_model
  3. from django.db.models.base import ModelBase
  4. from django.db.models.query import QuerySet
  5. from django.shortcuts import get_object_or_404
  6.  
  7. from guardian.exceptions import GuardianError
  8.  
  9. from tastypie import http
  10. from tastypie.exceptions import ImmediateHttpResponse
  11.  
  12.  
  13. def permission_required(perm, lookup_variables=None, **kwargs):
  14.     """
  15.    Decorator for views that checks whether a user has a particular permission
  16.    enabled.
  17.  
  18.    Optionally, instances for which check should be made may be passed as an
  19.    second argument or as a tuple parameters.
  20.  
  21.    :param accept_global_perms: if set to ``True``, then *object level
  22.    permission* would be required **only if user does NOT have global
  23.    permission** for target *model*. If turned on, makes this decorator
  24.    like an extension over standard
  25.    ``django.contrib.admin.decorators.permission_required`` as it would
  26.    check for global permissions first. Defaults to ``False``.
  27.    :param check_static: if set to ``Model``, the permissions will be
  28.    checked in calling to Model.static_has_perms() instead of calling to
  29.    has_perms(). Defaults to ``None``.
  30.  
  31.    Examples::
  32.  
  33.    @permission_required('join', (Agora, 'id', 'id'))
  34.    def join(self, request):
  35.    agora = get_object_or_404(Agora, id=id)
  36.    agora.members.append(request.user)
  37.    return self.success()
  38.  
  39.    @permission_required('create', check_static=Agora)
  40.    def obj_create(self, bundle, request=None, **kwargs):
  41.    user = get_object_or_404(User, username=username)
  42.    return user.get_absolute_url()
  43.  
  44.    """
  45.     accept_global_perms = kwargs.pop('accept_global_perms', False)
  46.     check_static = kwargs.pop('check_static', None)
  47.  
  48.     if check_static:
  49.         lookup_variables = [check_static]
  50.  
  51.     # Check if perm is given as string in order not to decorate
  52.     # view function itself which makes debugging harder
  53.     if not isinstance(perm, basestring):
  54.         raise GuardianError("First argument must be in format: "
  55.             "'app_label.codename or a callable which return similar string'")
  56.  
  57.     def decorator(view_func):
  58.         def wrapped(*args, **kwargs):
  59.             # if more than one parameter is passed to the decorator we try to
  60.             # fetch object for which check would be made
  61.             obj = None
  62.             request = kwargs.pop('request', None)
  63.             if lookup_variables:
  64.                 model, lookups = lookup_variables[0], lookup_variables[1:]
  65.                 # Parse model
  66.                 if isinstance(model, basestring):
  67.                     splitted = model.split('.')
  68.                     if len(splitted) != 2:
  69.                         raise GuardianError("If model should be looked up from "
  70.                             "string it needs format: 'app_label.ModelClass'")
  71.                     model = get_model(*splitted)
  72.                 elif issubclass(model.__class__, (Model, ModelBase, QuerySet)):
  73.                     pass
  74.                 else:
  75.                     raise GuardianError("First lookup argument must always be "
  76.                         "a model, string pointing at app/model or queryset. "
  77.                         "Given: %s (type: %s)" % (model, type(model)))
  78.                 # Parse lookups
  79.                 if len(lookups) % 2 != 0:
  80.                     raise GuardianError("Lookup variables must be provided "
  81.                         "as pairs of lookup_string and view_arg")
  82.                 lookup_dict = {}
  83.                 for lookup, view_arg in zip(lookups[::2], lookups[1::2]):
  84.                     if view_arg not in kwargs:
  85.                         raise GuardianError("Argument %s was not passed "
  86.                             "into view function" % view_arg)
  87.                     lookup_dict[lookup] = kwargs[view_arg]
  88.  
  89.                 if not check_static:
  90.                     obj = get_object_or_404(model, **lookup_dict)
  91.  
  92.             if check_static:
  93.                 has_perms = obj.has_perms(perm, request.user)
  94.             else:
  95.                 has_perms = obj.static_has_perms(perm, request.user)
  96.  
  97.             if not has_perms:
  98.                 raise ImmediateHttpResponse(response=http.HttpForbidden())
  99.             return view_func(request, *args, **kwargs)
  100.         return wraps(view_func)(wrapped)
  101.     return decorator
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top