Skip to content

Commit d1aaf51

Browse files
committed
feat: is_self permission
1 parent 8e07893 commit d1aaf51

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

codeforlife/permissions/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,5 @@
77

88
from .allow_none import AllowNone
99
from .is_cron_request_from_google import IsCronRequestFromGoogle
10+
from .is_self import IsSelf
1011
from .operators import AND, NOT, OR, Permission

codeforlife/permissions/is_self.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
© Ocado Group
3+
Created on 08/02/2024 at 11:19:37(+00:00).
4+
"""
5+
6+
import typing as t
7+
8+
from rest_framework.permissions import IsAuthenticated
9+
10+
11+
class IsSelf(IsAuthenticated):
12+
"""Request's user must be the selected user."""
13+
14+
def __init__(
15+
self,
16+
lookup_field: str = "pk",
17+
lookup_url_kwarg: t.Optional[str] = None,
18+
):
19+
"""Initialize permission.
20+
21+
Args:
22+
lookup_field: The field used to uniquely identify a user.
23+
lookup_url_kwarg: The key for the url arg used to lookup the user.
24+
"""
25+
26+
super().__init__()
27+
self.lookup_field = lookup_field
28+
self.lookup_url_kwarg = lookup_url_kwarg or lookup_field
29+
30+
def __eq__(self, other):
31+
return (
32+
isinstance(other, self.__class__)
33+
and self.lookup_field == other.lookup_field
34+
and self.lookup_url_kwarg == other.lookup_url_kwarg
35+
)
36+
37+
def has_permission(self, request, view):
38+
return (
39+
super().has_permission(request, view)
40+
and getattr(request.user, self.lookup_field)
41+
== view.kwargs[self.lookup_url_kwarg]
42+
)

0 commit comments

Comments
 (0)