from rest_framework import permissions from apps.projects.models import ProjectMembership def get_project_from_obj(obj): """Helper to extract the project from different model types.""" # If the object is a Project, it will have a 'workspace' attribute. # Otherwise, it's a related model (Membership, Rate) and has a 'project' attribute. return obj if hasattr(obj, "workspace") else obj.project class IsProjectMember(permissions.BasePermission): """ Allows access only to users who have an active membership in the project. """ message = "شما عضو این پروژه نیستید." def has_object_permission(self, request, view, obj): if not request.user or not request.user.is_authenticated: return False project = get_project_from_obj(obj) return ProjectMembership.objects.filter( project=project, user=request.user, is_active=True, is_deleted=False ).exists() class IsProjectManager(permissions.BasePermission): """ Allows access only to users who are active MANAGERs of the project. """ message = "فقط مدیران پروژه مجاز به انجام این عملیات هستند." def has_object_permission(self, request, view, obj): if not request.user or not request.user.is_authenticated: return False project = get_project_from_obj(obj) return ProjectMembership.objects.filter( project=project, user=request.user, role=ProjectMembership.Role.MANAGER, is_active=True, is_deleted=False ).exists()