Skip to content

Commit

Permalink
refactor: Remove guardian ObjectPermissionChecker monkey patch
Browse files Browse the repository at this point in the history
This is an old monkey patch that was introduced back when this code
used to live in `strawberry-django-plus`, with the intention of avoiding
too many queries to the database when fetching permissions.

This ended up causing an issue, as checking for a permission would
cache the result, and later when trying to modify the permissions and
checking those again would return the cached result instead.

This seems like to not be required anymore as well, based on the fact
that we have a lot of unit tests that test the permissioning stuff
with guardian, while also ensuring that the number of db requests
are known, and none presented any issues.
  • Loading branch information
bellini666 committed Sep 24, 2024
1 parent 93b1bf4 commit 18848ee
Showing 1 changed file with 1 addition and 22 deletions.
23 changes: 1 addition & 22 deletions strawberry_django/integrations/guardian.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,16 @@
import contextlib
import dataclasses
import weakref
from typing import Optional, Type, Union, cast
from typing import Type, Union, cast

from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.db import models
from guardian import backends as _guardian_backends
from guardian.conf import settings as guardian_settings
from guardian.core import ObjectPermissionChecker as _ObjectPermissionChecker
from guardian.models.models import GroupObjectPermissionBase, UserObjectPermissionBase
from guardian.utils import get_anonymous_user as _get_anonymous_user
from guardian.utils import get_group_obj_perms_model, get_user_obj_perms_model

from strawberry_django.utils.typing import UserType

_cache = weakref.WeakKeyDictionary()


@dataclasses.dataclass
class ObjectPermissionModels:
Expand All @@ -39,18 +33,3 @@ def get_user_or_anonymous(user: UserType) -> UserType:
with contextlib.suppress(get_user_model().DoesNotExist):
return cast(UserType, _get_anonymous_user())
return user


class ObjectPermissionChecker(_ObjectPermissionChecker):
def __new__(cls, user_or_group: Optional[Union[UserType, Group]] = None):
if user_or_group is not None and user_or_group in _cache:
return _cache[user_or_group]

obj = _ObjectPermissionChecker(user_or_group=user_or_group)
_cache[user_or_group] = obj

return obj


# Use our implementation that reuses the checker for the same user/group
_guardian_backends.ObjectPermissionChecker = ObjectPermissionChecker

0 comments on commit 18848ee

Please sign in to comment.