permissions.py 1.34 KB
Newer Older
1
2
3
import operator

from django.http import Http404
4

5
from rest_framework.permissions import BasePermission
6

7
8
from funkwhale_api.common import preferences

9
10
11

class ConditionalAuthentication(BasePermission):
    def has_permission(self, request, view):
Eliot Berriot's avatar
Eliot Berriot committed
12
        if preferences.get("common__api_authentication_required"):
13
            return request.user and request.user.is_authenticated
14
        return True
Eliot Berriot's avatar
Eliot Berriot committed
15
16


17
18
19
20
21
22
23
24
25
26
27
28
class OwnerPermission(BasePermission):
    """
    Ensure the request user is the owner of the object.

    Usage:

    class MyView(APIView):
        model = MyModel
        permission_classes = [OwnerPermission]
        owner_field = 'owner'
        owner_checks = ['read', 'write']
    """
Eliot Berriot's avatar
Eliot Berriot committed
29

30
    perms_map = {
Eliot Berriot's avatar
Eliot Berriot committed
31
32
33
34
35
36
37
        "GET": "read",
        "OPTIONS": "read",
        "HEAD": "read",
        "POST": "write",
        "PUT": "write",
        "PATCH": "write",
        "DELETE": "write",
38
39
40
41
    }

    def has_object_permission(self, request, view, obj):
        method_check = self.perms_map[request.method]
Eliot Berriot's avatar
Eliot Berriot committed
42
        owner_checks = getattr(view, "owner_checks", ["read", "write"])
43
44
45
46
        if method_check not in owner_checks:
            # check not enabled
            return True

Eliot Berriot's avatar
Eliot Berriot committed
47
        owner_field = getattr(view, "owner_field", "user")
48
49
50
51
        owner = operator.attrgetter(owner_field)(obj)
        if owner != request.user:
            raise Http404
        return True