strawberry-graphql / strawberry

A GraphQL library for Python that leverages type annotations 🍓
https://strawberry.rocks
MIT License
4.03k stars 535 forks source link

allow permission_class instances #3595

Open Speedy1991 opened 3 months ago

Speedy1991 commented 3 months ago

Feature Request Type

Description

Currently it is not possible to use instances of PermissionClasses, leading to lots of boilerplate.

Usecase: I want to check for specific features, like this: @strawberry.field(permission_classes=[FeatureRequired(feature_1), FeatureRequired(feature_2)]

This does not work, because permission_classes only takes classes and will be instanciated here.

To "fix" this the Typing must be fixed List[Type[BasePermission]] to something like List[Type[BasePermission] | BasePermission]] and the code snippet here:

permission_instances = [
  permission_class() for permission_class in permission_classes
]

needs some inspection like this:

permission_instances = list()
for permission_class in permission_classes:
  if isinstance(permission_class, type):
    permission_class = permission_class()
  permission_instances.append(permission_instance)

with this changes I also would suggest to refactor the permission_classes name to permissions + deprecating the permission_classes argument on strawberry.field

Upvote & Fund

Fund with Polar

Speedy1991 commented 3 months ago

Btw. in another MR it would be awesome to have some binary operation possible, e.g.: strawberry.field(permissions=[(FeatureRequired(feature_1) | FeatureRequired(feature_2)) & MemberRoleRequired])

patrick91 commented 3 months ago

I'm +1 for this! I also think it might be worth renaming permission_classes to permissions, since we don't just allow classes after implementing this PR

and yes, there's a PR for supporting boolean operators :) will check that soon

Speedy1991 commented 3 months ago

A littlebit offtopic, but maybe it would be possible to annotate type too? But I think this should be a follow up feature request after this one is implemented :)

e.g.: @type(permissions=[A(), B()]

These permissions will be applied to all fields with & condition?