Skip to content

Commit

Permalink
feat: is_self permission
Browse files Browse the repository at this point in the history
  • Loading branch information
SKairinos committed Feb 8, 2024
1 parent 8e07893 commit d1aaf51
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
1 change: 1 addition & 0 deletions codeforlife/permissions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@

from .allow_none import AllowNone
from .is_cron_request_from_google import IsCronRequestFromGoogle
from .is_self import IsSelf
from .operators import AND, NOT, OR, Permission
42 changes: 42 additions & 0 deletions codeforlife/permissions/is_self.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""
© Ocado Group
Created on 08/02/2024 at 11:19:37(+00:00).
"""

import typing as t

from rest_framework.permissions import IsAuthenticated


class IsSelf(IsAuthenticated):
"""Request's user must be the selected user."""

def __init__(
self,
lookup_field: str = "pk",
lookup_url_kwarg: t.Optional[str] = None,
):
"""Initialize permission.
Args:
lookup_field: The field used to uniquely identify a user.
lookup_url_kwarg: The key for the url arg used to lookup the user.
"""

super().__init__()
self.lookup_field = lookup_field
self.lookup_url_kwarg = lookup_url_kwarg or lookup_field

def __eq__(self, other):
return (
isinstance(other, self.__class__)
and self.lookup_field == other.lookup_field
and self.lookup_url_kwarg == other.lookup_url_kwarg
)

def has_permission(self, request, view):
return (
super().has_permission(request, view)
and getattr(request.user, self.lookup_field)
== view.kwargs[self.lookup_url_kwarg]
)

0 comments on commit d1aaf51

Please sign in to comment.