jazzband / django-waffle

A feature flipper for Django
https://waffle.readthedocs.io
BSD 3-Clause "New" or "Revised" License
1.12k stars 258 forks source link

Django User object Anonymous on request during checks #426

Open TAnas0 opened 2 years ago

TAnas0 commented 2 years ago

I have a Django Rest Framework API and I am using Waffle.

I am using JWT authentication, and ModelViewSet classes with the mixin WaffleFlagMixin, and a custom Flag model very similar to the one given as an example in the docs.

The Flag has been having weird behaviours where, even if logged in, the user variable during Waffle checks was always set to an AnonymousUser.

After many trials and errors and debugging the code under different scenarios, I managed to fix it and it seems to me that the problem is the dispatch method of WaffleFlagMixin (https://github.com/django-waffle/django-waffle/blob/master/waffle/mixins.py#L29) doesn't call the self.initialize_request method (https://www.django-rest-framework.org/api-guide/views/#initialize_requestself-request-args-kwargs) This is where it seems that the request.user variable is set, at least with JWT authentication.

Is this something that should be fixed? I am surprised nobody faced this error before, or maybe this is an edge case For now I can monkey-path the Waffle Mixin and be fine.

Also wondering: How does this affect the other ways a view will use Waffle? What about using a Custom Flag model?

I can make a reproducible project to show the bug if there is interest in addressing this :man_shrugging:

TAnas0 commented 2 years ago

I ended up writing an "Adapter Mixin" close to the following:

class WaffleAdapterMixin(WaffleFlagMixin):
    def dispatch(self, request, *args, **kwargs):
        request = self.initialize_request(request, *args, **kwargs)
        ...
        return super().dispatch(request._request, *args, **kwargs) # https://stackoverflow.com/a/35442073/4017403

I am realizing now that this issue is also due to the fatc that I am using Django REST framework, and that my above code could be part of a DRF sub-library.

If we can hear back from one of the contributors and some guidance, I could work on such a PR

clintonb commented 2 years ago

Can you provide an example of a view that breaks?

TAnas0 commented 2 years ago

@clintonb I'll try making a repository which reproduces all the above this week