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. Django Settings Assignment Expressions aka Walrus Operator example by webology 3 weeks, 1 day ago
  2. codigo alto nivel by MrRocklion 2 months, 2 weeks ago
  3. Load template from specific app by Krzysiek555 3 months, 1 week ago
  4. PostgreSQL JSON subqueries by dolamroth 3 months, 1 week ago
  5. "Magic Link" Management Command by webology 8 months, 2 weeks ago

Comments

buriy (on May 12, 2009):

Could you please write how to use your code?

#

Please login first before commenting.