2019-10-28 13:07:53 +00:00
|
|
|
"""permission classes for django restframework"""
|
|
|
|
from rest_framework.permissions import BasePermission, DjangoObjectPermissions
|
|
|
|
|
|
|
|
from passbook.policies.engine import PolicyEngine
|
2020-05-15 20:15:01 +00:00
|
|
|
from passbook.policies.models import PolicyBindingModel
|
2019-10-28 13:07:53 +00:00
|
|
|
|
|
|
|
|
|
|
|
class CustomObjectPermissions(DjangoObjectPermissions):
|
|
|
|
"""Similar to `DjangoObjectPermissions`, but adding 'view' permissions."""
|
|
|
|
|
|
|
|
perms_map = {
|
2019-12-31 11:51:16 +00:00
|
|
|
"GET": ["%(app_label)s.view_%(model_name)s"],
|
|
|
|
"OPTIONS": ["%(app_label)s.view_%(model_name)s"],
|
|
|
|
"HEAD": ["%(app_label)s.view_%(model_name)s"],
|
|
|
|
"POST": ["%(app_label)s.add_%(model_name)s"],
|
|
|
|
"PUT": ["%(app_label)s.change_%(model_name)s"],
|
|
|
|
"PATCH": ["%(app_label)s.change_%(model_name)s"],
|
|
|
|
"DELETE": ["%(app_label)s.delete_%(model_name)s"],
|
2019-10-28 13:07:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
class PolicyPermissions(BasePermission):
|
|
|
|
"""Permission checker based on PolicyEngine"""
|
|
|
|
|
|
|
|
policy_engine: PolicyEngine
|
|
|
|
|
2020-05-15 20:15:01 +00:00
|
|
|
def has_object_permission(self, request, view, obj: PolicyBindingModel) -> bool:
|
|
|
|
self.policy_engine = PolicyEngine(obj.policies.all(), request.user, request)
|
2019-10-28 16:40:57 +00:00
|
|
|
self.policy_engine.request.obj = obj
|
2019-10-28 13:07:53 +00:00
|
|
|
return self.policy_engine.build().passing
|