From 18848eec2c207ff7d2fc4249e5c3887f20359ad2 Mon Sep 17 00:00:00 2001 From: Thiago Bellini Ribeiro Date: Tue, 24 Sep 2024 18:52:09 -0300 Subject: [PATCH] refactor: Remove guardian ObjectPermissionChecker monkey patch 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. --- strawberry_django/integrations/guardian.py | 23 +--------------------- 1 file changed, 1 insertion(+), 22 deletions(-) diff --git a/strawberry_django/integrations/guardian.py b/strawberry_django/integrations/guardian.py index f15baf44..b1656dc1 100644 --- a/strawberry_django/integrations/guardian.py +++ b/strawberry_django/integrations/guardian.py @@ -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: @@ -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