|
| 1 | +# Copyright The IETF Trust 2024, All Rights Reserved |
| 2 | +# |
| 3 | +from rest_framework import permissions |
| 4 | +from ietf.api.ietf_utils import is_valid_token |
| 5 | + |
| 6 | + |
| 7 | +class HasApiKey(permissions.BasePermission): |
| 8 | + """Permissions class that validates a token using is_valid_token |
| 9 | + |
| 10 | + The view class must indicate the relevant endpoint by setting `api_key_endpoint`. |
| 11 | + Must be used with an Authentication class that puts a token in request.auth. |
| 12 | + """ |
| 13 | + def has_permission(self, request, view): |
| 14 | + endpoint = getattr(view, "api_key_endpoint", None) |
| 15 | + auth_token = getattr(request, "auth", None) |
| 16 | + if endpoint is not None and auth_token is not None: |
| 17 | + return is_valid_token(endpoint, auth_token) |
| 18 | + return False |
| 19 | + |
| 20 | + |
| 21 | +class IsOwnPerson(permissions.BasePermission): |
| 22 | + """Permission to access own Person object""" |
| 23 | + def has_object_permission(self, request, view, obj): |
| 24 | + if not (request.user.is_authenticated and hasattr(request.user, "person")): |
| 25 | + return False |
| 26 | + return obj == request.user.person |
| 27 | + |
| 28 | + |
| 29 | +class BelongsToOwnPerson(permissions.BasePermission): |
| 30 | + """Permission to access objects associated with own Person |
| 31 | + |
| 32 | + Requires that the object have a "person" field that indicates ownership. |
| 33 | + """ |
| 34 | + def has_object_permission(self, request, view, obj): |
| 35 | + if not (request.user.is_authenticated and hasattr(request.user, "person")): |
| 36 | + return False |
| 37 | + return ( |
| 38 | + hasattr(obj, "person") and obj.person == request.user.person |
| 39 | + ) |
0 commit comments