from rest_framework import permissions from rest_framework.permissions import ( # noqa: F401 BasePermission, IsAuthenticated as rf_IsAuthenticated, IsAdminUser, ) from backend_app.utils import is_member class IsAuthenticated(rf_IsAuthenticated): def has_object_permission(self, request, view, obj): return self.has_permission(request, view) class IsStaff(IsAdminUser): def has_object_permission(self, request, view, obj): return self.has_permission(request, view) class IsDri(BasePermission): """ Permission to make a viewset readonly unless the request user is a member of the DRI group. """ def has_object_permission(self, request, view, obj): return self.has_permission(request, view) def has_permission(self, request, view): if request.method in permissions.SAFE_METHODS: return True else: return is_member("DRI", request.user) class IsOwner(BasePermission): """ Permission that checks that the requester is the owner of the object. The object must have an owner field that corresponds to a user, or the object must be the user itself. """ def has_object_permission(self, request, view, obj): try: return request.user == obj.owner except AttributeError: # For the user model return request.user == obj def has_permission(self, request, view): return True class IsFollower(BasePermission): """ Permission that checks that the requester is a follower of the object (a list of universities). The object must have a "followers" field that corresponds to a list of users. """ def has_object_permission(self, request, view, obj): return obj.followers.filter(pk=request.user.pk).exists() class IsPublic(BasePermission): """ Permission that checks that the object is public. The object must have a "is_public" field. """ def has_object_permission(self, request, view, obj): return obj.is_public class NoDelete(BasePermission): """ Permission to prevent the use of the DELETE method. """ def has_object_permission(self, request, view, obj): return self.has_permission(request, view) def has_permission(self, request, view): return request.method != "DELETE" class NoPost(BasePermission): """ Permission to disallow POST request """ def has_object_permission(self, request, view, obj): return self.has_permission(request, view) def has_permission(self, request, view): return request.method != "POST" class ReadOnly(BasePermission): """ Permission to make a viewset read-only. """ def has_object_permission(self, request, view, obj): """ We absolutely need this one since it is used with "OR". If we don't put it, the IsOwner Or ReadOnly would pass the the has_permission on IsOwner and then the has_object_permission on Read_only. """ return request.method in permissions.SAFE_METHODS def has_permission(self, request, view): return request.method in permissions.SAFE_METHODS