Generic Permissions

 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. Fix duplicate first page of paginated results by muhuk 3 years, 8 months ago
  2. Ordered items in the database by Leonidas 6 years ago
  3. Ordered items in the database - alternative by Leonidas 5 years, 11 months ago
  4. i18n base model for translatable content by foxbunny 4 years, 10 months ago
  5. Truncate HTML without breaking tags by olau 4 years ago

Comments

buriy (on May 12, 2009):

Could you please write how to use your code?

#

mark0978 (on March 1, 2011):

How to use this is covered here

#

(Forgotten your password?)