""" API v1 Custom Permissions This module contains custom permission classes for the API v1 endpoints, providing flexible access control for different operations. """ from rest_framework import permissions class ReadOnlyOrAuthenticated(permissions.BasePermission): """ Permission that allows read-only access to anyone but requires authentication for write operations. - GET, HEAD, OPTIONS requests are allowed for anyone (no authentication required) - POST, PUT, PATCH, DELETE requests require authentication """ def has_permission(self, request, view): """Check if user has permission to access the view.""" # Allow read-only access for safe methods if request.method in permissions.SAFE_METHODS: return True # Require authentication for write operations return request.user and request.user.is_authenticated def has_object_permission(self, request, view, obj): """Check object-level permissions.""" # Allow read-only access for safe methods if request.method in permissions.SAFE_METHODS: return True # Require authentication for write operations return bool(request.user and request.user.is_authenticated) class ReadOnlyOrOwnerOrStaff(permissions.BasePermission): """ Permission that allows read-only access to anyone but requires ownership or staff privileges for write operations. - GET, HEAD, OPTIONS requests are allowed for anyone (no authentication required) - POST requests require authentication - PUT, PATCH, DELETE requests require ownership or staff privileges """ def has_permission(self, request, view): """Check if user has permission to access the view.""" # Allow read-only access for safe methods if request.method in permissions.SAFE_METHODS: return True # Require authentication for write operations return request.user and request.user.is_authenticated def has_object_permission(self, request, view, obj): """Check object-level permissions.""" # Allow read-only access for safe methods if request.method in permissions.SAFE_METHODS: return True # Require authentication for write operations if not (request.user and request.user.is_authenticated): return False # For write operations, check ownership or staff status if request.method in ['PUT', 'PATCH', 'DELETE']: # Check if user is the owner (uploaded_by field) or staff if hasattr(obj, 'uploaded_by'): return bool(obj.uploaded_by == request.user or getattr(request.user, 'is_staff', False)) # Fallback to staff check if no ownership field return bool(getattr(request.user, 'is_staff', False)) # For POST operations, just require authentication (already checked above) return True