像 cancan 这样的重新权限。
我正在使用djang-rules,最终结果看起来/功能很像 cancan。
模型/用户.py
class User(AbstractBaseUser, PermissionsMixin):
# ...
def has_perm(self, name, obj=None):
rset = self.__ruleset
return rset.test_rule(name, self, obj)
@property
def __ruleset(self):
from models.rules import (
ManagerRuleSet, EmployeeRuleSet, GuestRuleSet
)
if self.group.is_manager:
return ManagerRuleSet(self)
elif self.group.is_employee:
return EmployeeRuleSet(self)
else:
return GuestRuleSet(self)
模型/规则.py
from rules import RuleSet
class InvalidUser(Exception):
pass
class BaseRuleSet(RuleSet):
def __init__(self, user):
super()
class ManagerRuleSet(BaseRuleSet):
def __init__(self, user):
super()
if user and not user.group.is_owner:
raise InvalidUser("instantiated OwnerRuleSet with user in {} group",
user.group.name)
# Calendar permissions (pass appointment or schedule event)
self.add_rule('calendar.can_view_calendar', rules.always_true)
self.add_rule('calendar.can_manage_schedule',
is_own | has_accepted_invite)
示例视图.py
def index(request, id):
calendar = Calendar.objects.get(id=id)
if not request.user.has_perm('calendar.can_manage_schedule', calendar):
return HttpResponseForbidden()
# ...