app_permissions.py 2.05 KB
Newer Older
1 2 3
from rest_framework import permissions
from rest_framework.permissions import (  # noqa: F401
    BasePermission,
4 5
    IsAuthenticated as rf_IsAuthenticated,
    IsAdminUser,
6 7 8 9 10
)

from backend_app.utils import is_member


11 12 13 14 15 16 17 18
class IsAuthenticated(rf_IsAuthenticated):
    pass


class IsStaff(IsAdminUser):
    pass


19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
class IsDri(permissions.BasePermission):
    """
    Permission to make a viewset readonly unless the request user
    is a member of the DRI group.
    """

    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.

36 37
    The object must have a owner field that corresponds to a user, or the object
    must be the user itself.
38 39 40
    """

    def has_object_permission(self, request, view, obj):
41 42 43 44 45
        try:
            return request.user == obj.owner
        except AttributeError:
            # For the user model
            return request.user == obj
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73


class NoDelete(BasePermission):
    """
    Permission to prevent the use of the DELETE method.
    """

    def has_permission(self, request, view):
        if request.method == "DELETE":
            return False

        return True


class NoPost(permissions.BasePermission):
    """
    Permission to disallow POST request
    """

    def has_permission(self, request, view):
        return request.method != "POST"


class ReadOnly(permissions.BasePermission):
    """
    Permission to make a viewset read-only.
    """

74 75 76 77 78 79 80 81
    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

82 83
    def has_permission(self, request, view):
        return request.method in permissions.SAFE_METHODS