File: permissions.py

package info (click to toggle)
strawberry-graphql-django 0.62.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,968 kB
  • sloc: python: 27,530; sh: 17; makefile: 16
file content (932 lines) | stat: -rw-r--r-- 27,345 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
import abc
import contextlib
import contextvars
import copy
import dataclasses
import enum
import functools
import inspect
from collections.abc import Callable, Hashable, Iterable
from typing import (
    TYPE_CHECKING,
    Any,
    ClassVar,
    Optional,
    TypeVar,
    Union,
    cast,
    overload,
)

import strawberry
from asgiref.sync import sync_to_async
from django.core.exceptions import PermissionDenied
from django.db.models import Model, QuerySet
from graphql.pyutils import AwaitableOrValue
from strawberry import relay, schema_directive
from strawberry.extensions.field_extension import (
    AsyncExtensionResolver,
    FieldExtension,
    SyncExtensionResolver,
)
from strawberry.schema_directive import Location
from strawberry.types.base import StrawberryList, StrawberryOptional
from strawberry.types.field import StrawberryField
from strawberry.types.info import Info
from strawberry.types.union import StrawberryUnion
from typing_extensions import Literal, assert_never

from strawberry_django.auth.utils import aget_current_user, get_current_user
from strawberry_django.fields.types import OperationInfo, OperationMessage
from strawberry_django.pagination import OffsetPaginated
from strawberry_django.resolvers import django_resolver

from .utils.query import filter_for_user
from .utils.typing import UserType

if TYPE_CHECKING:
    from strawberry.django.context import StrawberryDjangoContext

    from strawberry_django.fields.field import StrawberryDjangoField


_M = TypeVar("_M", bound=Model)


@functools.lru_cache
def _get_user_or_anonymous_getter() -> Optional[Callable[[UserType], UserType]]:
    try:
        from .integrations.guardian import get_user_or_anonymous
    except (ImportError, RuntimeError):  # pragma: no cover
        return None

    return get_user_or_anonymous


@dataclasses.dataclass
class PermContext:
    is_safe_list: list[bool] = dataclasses.field(default_factory=list)
    checkers: list["HasPerm"] = dataclasses.field(default_factory=list)

    def __copy__(self):
        return self.__class__(
            is_safe_list=self.is_safe_list[:],
            checkers=self.checkers[:],
        )

    @property
    def is_safe(self):
        return bool(self.is_safe_list and all(self.is_safe_list))


perm_context: contextvars.ContextVar[PermContext] = contextvars.ContextVar(
    "perm-safe",
    default=PermContext(),  # noqa: B039
)


@contextlib.contextmanager
def with_perm_checker(checker: "HasPerm"):
    context = copy.copy(perm_context.get())
    context.checkers.append(checker)
    token = perm_context.set(context)
    try:
        yield
    finally:
        perm_context.reset(token)


def set_perm_safe(value: bool):
    perm_context.get().is_safe_list.append(value)


def filter_with_perms(qs: QuerySet[_M], info: Info) -> QuerySet[_M]:
    context = perm_context.get()
    if not context.checkers or context.is_safe:
        return qs

    if isinstance(qs, list):
        # return sliced queryset as-is
        return qs

    # Do not do anything is results are cached
    if qs._result_cache is not None:  # type: ignore
        set_perm_safe(False)
        return qs

    user = cast("StrawberryDjangoContext", info.context).request.user
    # If the user is anonymous, we can't filter object permissions for it
    if user.is_anonymous:
        set_perm_safe(False)
        return qs.none()

    for check in context.checkers:
        if check.target != PermTarget.RETVAL:
            continue

        qs = filter_for_user(
            qs,
            user,
            [p.perm for p in check.perms],
            any_perm=check.any_perm,
            with_superuser=check.with_superuser,
        )

    set_perm_safe(True)
    return qs


@overload
def get_with_perms(
    pk: strawberry.ID,
    info: Info,
    *,
    required: Literal[True],
    model: type[_M],
    key_attr: str = ...,
) -> _M: ...


@overload
def get_with_perms(
    pk: strawberry.ID,
    info: Info,
    *,
    required: bool = ...,
    model: type[_M],
    key_attr: str = ...,
) -> Optional[_M]: ...


@overload
def get_with_perms(
    pk: relay.GlobalID,
    info: Info,
    *,
    required: Literal[True],
    model: type[_M],
    key_attr: str = ...,
) -> _M: ...


@overload
def get_with_perms(
    pk: relay.GlobalID,
    info: Info,
    *,
    required: bool = ...,
    model: type[_M],
    key_attr: str = ...,
) -> Optional[_M]: ...


@overload
def get_with_perms(
    pk: relay.GlobalID,
    info: Info,
    *,
    required: Literal[True],
    key_attr: str = ...,
) -> Any: ...


@overload
def get_with_perms(
    pk: relay.GlobalID,
    info: Info,
    *,
    required: bool = ...,
    key_attr: str = ...,
) -> Optional[Any]: ...


def get_with_perms(
    pk,
    info,
    *,
    required=False,
    model=None,
    key_attr="pk",
):
    if isinstance(pk, relay.GlobalID):
        instance = pk.resolve_node_sync(info, required=required, ensure_type=model)
    else:
        assert model
        instance = model._default_manager.get(**{key_attr: pk})

    if instance is None:
        return None

    context = perm_context.get()
    if not context.checkers or context.is_safe:
        return instance

    user = cast("StrawberryDjangoContext", info.context).request.user
    if user and (get_user_or_anonymous := _get_user_or_anonymous_getter()) is not None:
        user = get_user_or_anonymous(user)

    for check in context.checkers:
        f = any if check.any_perm else all
        checker = check.obj_perm_checker(info, user)
        if not f(checker(p, instance) for p in check.perms):
            raise PermissionDenied(check.message)

    return instance


_return_condition = """\
When the condition fails, the following can be returned (following this priority):
1) `OperationInfo`/`OperationMessage` if those types are allowed at the return type
2) `null` in case the field is not mandatory (e.g. `String` or `[String]`)
3) An empty list in case the field is a list (e.g. `[String]!`)
4) An empty `Connection` in case the return type is a relay connection
2) Otherwise, an error will be raised
"""


def _desc(desc):
    return f"{desc}\n\n{_return_condition.strip()}"


class DjangoNoPermission(Exception):  # noqa: N818
    """Raise to identify that the user doesn't have perms for a given retval."""


class DjangoPermissionExtension(FieldExtension, abc.ABC):
    """Base django permission extension."""

    DEFAULT_ERROR_MESSAGE: ClassVar[str] = "User does not have permission."
    SCHEMA_DIRECTIVE_LOCATIONS: ClassVar[list[Location]] = [Location.FIELD_DEFINITION]
    SCHEMA_DIRECTIVE_DESCRIPTION: ClassVar[Optional[str]] = None

    def __init__(
        self,
        *,
        message: Optional[str] = None,
        use_directives: bool = True,
        fail_silently: bool = True,
    ):
        super().__init__()
        self.message = message if message is not None else self.DEFAULT_ERROR_MESSAGE
        self.fail_silently = fail_silently
        self.use_directives = use_directives

    def apply(self, field: StrawberryField) -> None:  # pragma: no cover
        if self.use_directives:
            directive = self.schema_directive
            # Avoid interfaces duplicating the directives
            if directive not in field.directives:
                field.directives.append(self.schema_directive)

    @functools.cached_property
    def schema_directive(self) -> object:
        key = "__strawberry_directive_type__"
        directive_class = getattr(self.__class__, key, None)

        if directive_class is None:

            @schema_directive(
                name=self.__class__.__name__,
                locations=self.SCHEMA_DIRECTIVE_LOCATIONS,
                description=self.SCHEMA_DIRECTIVE_DESCRIPTION,
                repeatable=True,
            )
            class AutoDirective: ...

            directive_class = AutoDirective

        return directive_class()

    @django_resolver(qs_hook=None)
    def resolve(
        self,
        next_: SyncExtensionResolver,
        source: Any,
        info: Info,
        **kwargs: dict[str, Any],
    ) -> Any:
        user = get_current_user(info)

        if (
            user
            and (get_user_or_anonymous := _get_user_or_anonymous_getter()) is not None
        ):
            user = get_user_or_anonymous(user)

        # make sure the user is loaded
        user.is_authenticated  # noqa: B018

        try:
            retval = self.resolve_for_user(
                functools.partial(next_, source, info, **kwargs),
                user,
                info=info,
                source=source,
            )
        except DjangoNoPermission as e:
            retval = self.handle_no_permission(e, info=info)

        return retval

    async def resolve_async(
        self,
        next_: AsyncExtensionResolver,
        source: Any,
        info: Info,
        **kwargs: dict[str, Any],
    ) -> Any:
        user = await aget_current_user(info)

        try:
            from .integrations.guardian import get_user_or_anonymous
        except (ImportError, RuntimeError):  # pragma: no cover
            pass
        else:
            user = user and await sync_to_async(get_user_or_anonymous)(user)

        # make sure the user is loaded
        await sync_to_async(getattr)(user, "is_anonymous")

        try:
            retval = self.resolve_for_user(
                functools.partial(next_, source, info, **kwargs),
                user,
                info=info,
                source=source,
            )
            while inspect.isawaitable(retval):
                retval = await retval
        except DjangoNoPermission as e:
            retval = self.handle_no_permission(e, info=info)

        return retval

    def handle_no_permission(self, exception: BaseException, *, info: Info):
        if not self.fail_silently:
            raise PermissionDenied(self.message) from exception

        ret_type = info.return_type

        if isinstance(ret_type, StrawberryOptional):
            ret_type = ret_type.of_type
            is_optional = True
        else:
            is_optional = False

        if isinstance(ret_type, StrawberryUnion):
            ret_types = []
            for type_ in ret_type.types:
                ret_types.append(ret_type)

                if not isinstance(type_, type):
                    continue

                if issubclass(type_, OperationInfo):
                    return type_(
                        messages=[
                            OperationMessage(
                                kind=OperationMessage.Kind.PERMISSION,
                                message=self.message,
                                field=info.field_name,
                            ),
                        ],
                    )

                if issubclass(type_, OperationMessage):
                    return type_(
                        kind=OperationMessage.Kind.PERMISSION,
                        message=self.message,
                        field=info.field_name,
                    )
        else:
            ret_types = [ret_type]

        if is_optional:
            return None

        if isinstance(ret_type, StrawberryList):
            return []

        if isinstance(ret_type, type) and issubclass(ret_type, OffsetPaginated):
            django_model = cast("StrawberryDjangoField", info._field).django_model
            assert django_model
            return django_model._default_manager.none()

        # If it is a Connection, try to return an empty connection, but only if
        # it is the only possibility available...
        for ret_possibility in ret_types:
            if isinstance(ret_possibility, type) and issubclass(
                ret_possibility,
                relay.Connection,
            ):
                return []

        # In last case, raise an error
        raise PermissionDenied(self.message) from exception

    @abc.abstractmethod
    def resolve_for_user(  # pragma: no cover
        self,
        resolver: Callable,
        user: Optional[UserType],
        *,
        info: Info,
        source: Any,
    ) -> AwaitableOrValue[Any]: ...


class IsAuthenticated(DjangoPermissionExtension):
    """Mark a field as only resolvable by authenticated users."""

    DEFAULT_ERROR_MESSAGE: ClassVar[str] = "User is not authenticated."
    SCHEMA_DIRECTIVE_DESCRIPTION: ClassVar[Optional[str]] = _desc(
        "Can only be resolved by authenticated users.",
    )

    @django_resolver(qs_hook=None)
    def resolve_for_user(
        self,
        resolver: Callable,
        user: Optional[UserType],
        *,
        info: Info,
        source: Any,
    ):
        if user is None or not user.is_authenticated or not user.is_active:
            raise DjangoNoPermission

        return resolver()


class IsStaff(DjangoPermissionExtension):
    """Mark a field as only resolvable by staff users."""

    DEFAULT_ERROR_MESSAGE: ClassVar[str] = "User is not a staff member."
    SCHEMA_DIRECTIVE_DESCRIPTION: ClassVar[Optional[str]] = _desc(
        "Can only be resolved by staff users.",
    )

    @django_resolver(qs_hook=None)
    def resolve_for_user(
        self,
        resolver: Callable,
        user: Optional[UserType],
        *,
        info: Info,
        source: Any,
    ):
        if (
            user is None
            or not user.is_authenticated
            or not getattr(user, "is_staff", False)
        ):
            raise DjangoNoPermission

        return resolver()


class IsSuperuser(DjangoPermissionExtension):
    """Mark a field as only resolvable by superuser users."""

    DEFAULT_ERROR_MESSAGE: ClassVar[str] = "User is not a superuser."
    SCHEMA_DIRECTIVE_DESCRIPTION: ClassVar[Optional[str]] = _desc(
        "Can only be resolved by superuser users.",
    )

    @django_resolver(qs_hook=None)
    def resolve_for_user(
        self,
        resolver: Callable,
        user: Optional[UserType],
        *,
        info: Info,
        source: Any,
    ):
        if (
            user is None
            or not user.is_authenticated
            or not getattr(user, "is_superuser", False)
        ):
            raise DjangoNoPermission

        return resolver()


@strawberry.input(description="Permission definition for schema directives.")
class PermDefinition:
    """Permission definition.

    Attributes
    ----------
        app:
            The app to which we are requiring permission.
        permission:
            The permission itself

    """

    app: Optional[str] = strawberry.field(
        description=(
            "The app to which we are requiring permission. If this is "
            "empty that means that we are checking the permission directly."
        ),
    )
    permission: Optional[str] = strawberry.field(
        description=(
            "The permission itself. If this is empty that means that we "
            "are checking for any permission for the given app."
        ),
    )

    @classmethod
    def from_perm(cls, perm: str):
        parts = perm.split(".")
        if len(parts) != 2:  # noqa: PLR2004
            raise TypeError(
                "Permissions need to be defined as `app_label.perm`, `app_label.`"
                " or `.perm`",
            )
        return cls(
            app=parts[0].strip() or None,
            permission=parts[1].strip() or None,
        )

    @property
    def perm(self):
        return f"{self.app or ''}.{self.permission or ''}".strip(".")

    def __eq__(self, other: object):
        if not isinstance(other, PermDefinition):
            return NotImplemented

        return self.perm == other.perm

    def __hash__(self):
        return hash((self.__class__, self.perm))


class PermTarget(enum.IntEnum):
    """Permission location."""

    GLOBAL = enum.auto()
    SOURCE = enum.auto()
    RETVAL = enum.auto()


def _default_perm_checker(info: Info, user: UserType):
    def perm_checker(perm: PermDefinition) -> bool:
        return (
            user.has_perm(perm.perm)  # type: ignore
            if perm.permission
            else user.has_module_perms(cast("str", perm.app))  # type: ignore
        )

    return perm_checker


def _default_obj_perm_checker(info: Info, user: UserType):
    def perm_checker(perm: PermDefinition, obj: Any) -> bool:
        # Check global perms first, then object specific
        return user.has_perm(perm.perm) or user.has_perm(  # type: ignore
            perm.perm,
            obj=obj,
        )

    return perm_checker


class HasPerm(DjangoPermissionExtension):
    """Defines permissions required to access the given object/field.

    Given a `app` name, the user can access the decorated object/field
    if he has any of the permissions defined in this directive.

    Examples
    --------
        To indicate that a mutation can only be done by someone who
        has "product.add_product" perm in the django system:

        >>> @strawberry.type
        ... class Query:
        ...     @strawberry.mutation(directives=[HasPerm("product.add_product")])
        ...     def create_product(self, name: str) -> ProductType:
        ...         ...

    Attributes
    ----------
        perms:
            Perms required to access this app.
        any_perm:
            If any perm or all perms are required to resolve the object/field.
        target:
            The target to check for permissions. Use `HasSourcePerm` or
            `HasRetvalPerm` as a shortcut for this.
        with_anonymous:
            If we should optimize the permissions check and consider an anonymous
            user as not having any permissions. This is true by default, which means
            that anonymous users will not trigger has_perm checks.
        with_superuser:
            If we should optimize the permissions check and consider a superuser
            as having permissions foe everything. This is false by default to avoid
            returning unexpected results. Setting this to true will avoid triggering
            has_perm checks.

    """

    DEFAULT_TARGET: ClassVar[PermTarget] = PermTarget.GLOBAL
    DEFAULT_ERROR_MESSAGE: ClassVar[str] = (
        "You don't have permission to access this app."
    )
    SCHEMA_DIRECTIVE_DESCRIPTION: ClassVar[Optional[str]] = _desc(
        "Will check if the user has any/all permissions to resolve this.",
    )

    def __init__(
        self,
        perms: Union[list[str], str],
        *,
        message: Optional[str] = None,
        use_directives: bool = True,
        fail_silently: bool = True,
        target: Optional[PermTarget] = None,
        any_perm: bool = True,
        perm_checker: Optional[
            Callable[[Info, UserType], Callable[[PermDefinition], bool]]
        ] = None,
        obj_perm_checker: Optional[
            Callable[[Info, UserType], Callable[[PermDefinition, Any], bool]]
        ] = None,
        with_anonymous: bool = True,
        with_superuser: bool = False,
    ):
        super().__init__(
            message=message,
            use_directives=use_directives,
            fail_silently=fail_silently,
        )

        if isinstance(perms, str):
            perms = [perms]

        if not perms:
            raise TypeError(f"At least one perm is required for {self!r}")

        self.perms: tuple[PermDefinition, ...] = tuple(
            PermDefinition.from_perm(p) if isinstance(p, str) else p for p in perms
        )

        assert all(isinstance(p, PermDefinition) for p in self.perms)
        self.target = target if target is not None else self.DEFAULT_TARGET
        self.permissions = perms
        self.any_perm = any_perm
        self.perm_checker = (
            perm_checker if perm_checker is not None else _default_perm_checker
        )
        self.obj_perm_checker = (
            obj_perm_checker
            if obj_perm_checker is not None
            else _default_obj_perm_checker
        )
        self.with_anonymous = with_anonymous
        self.with_superuser = with_superuser

    @functools.cached_property
    def schema_directive(self) -> object:
        key = "__strawberry_directive_class__"
        directive_class = getattr(self.__class__, key, None)

        if directive_class is None:

            @schema_directive(
                name=self.__class__.__name__,
                locations=self.SCHEMA_DIRECTIVE_LOCATIONS,
                description=self.SCHEMA_DIRECTIVE_DESCRIPTION,
                repeatable=True,
            )
            class AutoDirective:
                permissions: list[PermDefinition] = strawberry.field(
                    description="Required perms to access this resource.",
                    default_factory=list,
                )
                any: bool = strawberry.field(
                    description="If any or all perms listed are required.",
                    default=True,
                )

            directive_class = AutoDirective

        return directive_class(
            permissions=list(self.perms),
            any=self.any_perm,
        )

    @django_resolver(qs_hook=None)
    def resolve_for_user(
        self,
        resolver: Callable,
        user: Optional[UserType],
        *,
        info: Info,
        source: Any,
    ):
        if user is None or (self.with_anonymous and user.is_anonymous):
            raise DjangoNoPermission

        if (
            self.with_superuser
            and user.is_active
            and getattr(user, "is_superuser", False)
        ):
            return resolver()

        return self.resolve_for_user_with_perms(
            resolver,
            user,
            info=info,
            source=source,
        )

    def resolve_for_user_with_perms(
        self,
        resolver: Callable,
        user: Optional[UserType],
        *,
        info: Info,
        source: Any,
    ):
        if user is None:
            raise DjangoNoPermission

        if self.target == PermTarget.GLOBAL:
            if not self._has_perm(source, user, info=info):
                raise DjangoNoPermission

            retval = resolver()
        elif self.target == PermTarget.SOURCE:
            # Just call _resolve_obj, it will raise DjangoNoPermission
            # if the user doesn't have permission for it
            self._resolve_obj(source, user, source, info=info)
            retval = resolver()
        elif self.target == PermTarget.RETVAL:
            with with_perm_checker(self):
                obj = resolver()
                retval = self._resolve_obj(source, user, obj, info=info)
        else:
            assert_never(self.target)

        return retval

    def _get_cache(
        self,
        info: Info,
        user: UserType,
    ) -> dict[tuple[Hashable, ...], bool]:
        cache_key = "_strawberry_django_permissions_cache"

        cache = getattr(user, cache_key, None)
        if cache is None:
            cache = {}
            setattr(user, cache_key, cache)

        return cache

    def _has_perm(
        self,
        source: Any,
        user: UserType,
        *,
        info: Info,
    ) -> bool:
        cache = self._get_cache(info, user)

        # Maybe the result ended up in the cache in the meantime
        cache_key = (self.perms, self.any_perm)
        if cache_key in cache:
            return cache[cache_key]

        f = any if self.any_perm else all
        checker = self.perm_checker(info, user)
        has_perm = f(checker(p) for p in self.perms)
        cache[cache_key] = has_perm

        return has_perm

    def _resolve_obj(
        self,
        source: Any,
        user: UserType,
        obj: Any,
        *,
        info: Info,
    ) -> Any:
        context = perm_context.get()
        if context.is_safe:
            return obj

        if isinstance(obj, Iterable):
            return list(self._resolve_iterable_obj(source, user, obj, info=info))

        cache = self._get_cache(info, user)
        cache_key = (self.perms, self.any_perm, obj)
        has_perm = cache.get(cache_key)

        if has_perm is None:
            if isinstance(obj, OperationInfo):
                has_perm = True
            else:
                f = any if self.any_perm else all
                checker = self.obj_perm_checker(info, user)
                has_perm = f(checker(p, obj) for p in self.perms)

            cache[cache_key] = has_perm

        if not has_perm:
            raise DjangoNoPermission

        return obj

    def _resolve_iterable_obj(
        self,
        source: Any,
        user: UserType,
        objs: Iterable[Any],
        *,
        info: Info,
    ) -> Any:
        cache = self._get_cache(info, user)
        f = any if self.any_perm else all
        checker = self.obj_perm_checker(info, user)

        for obj in objs:
            cache_key = (self.perms, self.any_perm, obj)
            has_perm = cache.get(cache_key)

            if has_perm is None:
                if isinstance(obj, OperationInfo):
                    has_perm = True
                else:
                    has_perm = f(checker(p, obj) for p in self.perms)

                cache[cache_key] = has_perm

            if has_perm:
                yield obj


class HasSourcePerm(HasPerm):
    """Defines permissions required to access the given field at object level.

    This will check the permissions for the source object to access the given field.

    Unlike `HasRetvalPerm`, this uses the source value (the object where the field
    is defined) to resolve the field, which means that this cannot be used for source
    queries and types.

    Examples
    --------
        To indicate that a field inside a `ProductType` can only be accessed if
        the user has "product.view_field" in it in the django system:

        >>> @gql.django.type(Product)
        ... class ProductType:
        ...     some_field: str = strawberry.field(
        ...         directives=[HasSourcePerm(".add_product")],
        ...     )

    """

    DEFAULT_TARGET: ClassVar[PermTarget] = PermTarget.SOURCE
    SCHEMA_DIRECTIVE_DESCRIPTION: ClassVar[Optional[str]] = _desc(
        "Will check if the user has any/all permissions for the parent "
        "of this field to resolve this.",
    )


class HasRetvalPerm(HasPerm):
    """Defines permissions required to access the given object/field at object level.

    Given a `app` name, the user can access the decorated object/field
    if he has any of the permissions defined in this directive.

    Note that this depends on resolving the object to check the permissions
    specifically for that object, unlike `HasPerm` which checks it before resolving.

    Examples
    --------
        To indicate that a field that returns a `ProductType` can only be accessed
        by someone who has "product.view_product"
        has "product.view_product" perm in the django system:

        >>> @strawberry.type
        ... class SomeType:
        ...     product: ProductType = strawberry.field(
        ...         directives=[HasRetvalPerm(".add_product")],
        ...     )

    """

    DEFAULT_TARGET: ClassVar[PermTarget] = PermTarget.RETVAL
    SCHEMA_DIRECTIVE_DESCRIPTION: ClassVar[Optional[str]] = _desc(
        "Will check if the user has any/all permissions for the resolved "
        "value of this field before returning it.",
    )