33 lines
1.1 KiB
Python
33 lines
1.1 KiB
Python
from rest_framework.permissions import SAFE_METHODS, BasePermission
|
|
|
|
|
|
class IsAdminOrReadOnly(BasePermission):
|
|
"""Admin users can perform any action; others can only read."""
|
|
|
|
def has_permission(self, request, view):
|
|
if not request.user or not request.user.is_authenticated:
|
|
return False
|
|
if request.method in SAFE_METHODS:
|
|
return True
|
|
return request.user.is_admin
|
|
|
|
def has_object_permission(self, request, view, obj):
|
|
if request.method in SAFE_METHODS:
|
|
return True
|
|
return request.user.is_admin
|
|
|
|
|
|
class IsOwnerOrAdmin(BasePermission):
|
|
"""Users can only access their own resources; admins can access all."""
|
|
|
|
def has_permission(self, request, view):
|
|
return bool(request.user and request.user.is_authenticated)
|
|
|
|
def has_object_permission(self, request, view, obj):
|
|
if request.user.is_admin:
|
|
return True
|
|
# Expect obj to have a `user` FK pointing to the owning user
|
|
user_field = getattr(obj, "user", None)
|
|
if user_field is not None:
|
|
return user_field == request.user
|
|
return False |