Newer
Older
import operator
Eliot Berriot
committed
from django.conf import settings
from django.http import Http404
Eliot Berriot
committed
from rest_framework.permissions import BasePermission
Eliot Berriot
committed
from funkwhale_api.common import preferences
Eliot Berriot
committed
class ConditionalAuthentication(BasePermission):
def has_permission(self, request, view):
if preferences.get('common__api_authentication_required'):
return request.user and request.user.is_authenticated
Eliot Berriot
committed
return True
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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']
"""
perms_map = {
'GET': 'read',
'OPTIONS': 'read',
'HEAD': 'read',
'POST': 'write',
'PUT': 'write',
'PATCH': 'write',
'DELETE': 'write',
}
def has_object_permission(self, request, view, obj):
method_check = self.perms_map[request.method]
owner_checks = getattr(view, 'owner_checks', ['read', 'write'])
if method_check not in owner_checks:
# check not enabled
return True
owner_field = getattr(view, 'owner_field', 'user')
owner = operator.attrgetter(owner_field)(obj)
if owner != request.user:
raise Http404
return True