Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] Async authentication doesn't play well with sync views #827

Closed
selcuk opened this issue Aug 18, 2023 · 2 comments
Closed

[BUG] Async authentication doesn't play well with sync views #827

selcuk opened this issue Aug 18, 2023 · 2 comments

Comments

@selcuk
Copy link

selcuk commented Aug 18, 2023

Describe the bug
Django Ninja supports both sync and async authentication classes, but even though sync authentication works well with both sync and async views; async authentication requires async views.

To reproduce:

class MyAsyncTokenAuth(HttpAuthBase):
    openapi_scheme: str = "bearer"
    header: str = "Authorization"

    async def __call__(self, request: HttpRequest) -> Optional[Any]:
        # ...
        return {"user": "foobar"}

then

api = NinjaAPI(title="MyAPI", auth=MyAsyncTokenAuth())

this works well here:

async def my_async_view(request):
    if request.auth["user"] == "foobar":
        # The user is authenticated

but it fails with a sync view:

def my_async_view(request):
    if request.auth["user"] == "foobar":

Exception:

builtins.TypeError: 'coroutine' object is not subscriptable

Cause
Although AsyncOperation._run_authentication checks if the __call__ method of the authentication class is async, its sync counterpart (Operation._run_authentication) does not perform this check.

Versions (please complete the following information):

  • Python version: [e.g. 3.11]
  • Django version: [e.g. 4.2.4]
  • Django-Ninja version: [e.g. 0.22.2]
  • Pydantic version: [e.g. 1.10.7]
@selcuk
Copy link
Author

selcuk commented Aug 18, 2023

Hmm, on a closer look, this looks like a Duplicate of #756 and seems to be fixed in the latest master branch. 🎉

@selcuk selcuk closed this as completed Aug 18, 2023
@vitalik
Copy link
Owner

vitalik commented Aug 18, 2023

@selcuk you can try it with recent alpha release pip install django-ninja==1.0a3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants