Added common permission classes and validator methods
This commit is contained in:
parent
31332c518b
commit
ddae68b433
1 changed files with 37 additions and 0 deletions
37
apps/accounts/permissions.py
Normal file
37
apps/accounts/permissions.py
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
from rest_framework.permissions import BasePermission
|
||||
|
||||
from apps.accounts.models import Organization
|
||||
|
||||
def get_organization_from_object(obj):
|
||||
if isinstance(obj, Organization):
|
||||
return obj
|
||||
|
||||
organization = getattr(obj, 'organization', None)
|
||||
if isinstance(organization, Organization):
|
||||
return organization
|
||||
|
||||
role = getattr(obj, 'role', None)
|
||||
organization = getattr(role, 'organization', None)
|
||||
if isinstance(organization, Organization):
|
||||
return organization
|
||||
|
||||
return None
|
||||
|
||||
def can_manage_organization(user, organization):
|
||||
if organization is None:
|
||||
return False
|
||||
|
||||
is_owner = organization.owner.id == user.id
|
||||
is_member_manager = bool(user.is_manager) and organization.members.filter(id=user.id).exists()
|
||||
return is_owner or is_member_manager
|
||||
|
||||
class IsOrganizationOwnerOrMember(BasePermission):
|
||||
def has_object_permission(self, request, view, obj):
|
||||
if not isinstance(obj, Organization):
|
||||
return False
|
||||
return request.user.is_member_of(obj) or request.user.is_owner_of(obj)
|
||||
|
||||
class CanManageOrganization(BasePermission):
|
||||
def has_object_permission(self, request, view, obj):
|
||||
organization = get_organization_from_object(obj)
|
||||
return can_manage_organization(request.user, organization)
|
||||
Loading…
Reference in a new issue