Login

Generic Permissions

Author:
muhuk
Posted:
May 12, 2009
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

A mixin to define permissions on models. This is more of an abstract model to subclass/customise than a plug-in solution. Explanations are here.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from django.contrib.auth.models import User


class PermissionError(StandardError):
    pass


class PermissionMixin(object):
    def attempt(self, action, actor, msg=None):
        return PermissionMixin._attempt(self, action, actor, msg=None)

    @classmethod
    def cls_attempt(cls, action, actor, msg=None):
        return PermissionMixin._attempt(cls, action, actor, msg=None)

    @staticmethod
    def _attempt(obj, action, actor, msg):
        if actor.__class__ != User or not isinstance(action, basestring):
            raise TypeError
        if getattr(obj, 'allows_%s_for' % action.lower().replace(' ', '_'))(actor):
            return True
        else:
            if msg is None:
                msg = u'%s doesn\'t have permission to %s %s' % (actor.username, action.lower(), repr(obj))
            raise PermissionError(msg)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 9 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 3 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
  5. Help text hyperlinks by sa2812 1 year, 5 months ago

Comments

buriy (on May 12, 2009):

Could you please write how to use your code?

#

Please login first before commenting.