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

Fix of TypeError when returning None in AuthBase.__call__ from async code #1386 #1387

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion ninja/operation.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import inspect
from typing import (
TYPE_CHECKING,
Any,
Expand Down Expand Up @@ -187,7 +188,9 @@ def _run_authentication(self, request: HttpRequest) -> Optional[HttpResponse]:
for callback in self.auth_callbacks:
try:
if is_async_callable(callback) or getattr(callback, "is_async", False):
result = async_to_sync(callback)(request)
result = callback(request)
if inspect.iscoroutine(result):
result = async_to_sync(callback)(request)
else:
result = callback(request)
except Exception as exc:
Expand Down
22 changes: 22 additions & 0 deletions tests/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,14 @@ def authenticate(self, request, token):
raise AuthorizationError


class AsyncBearerAuth(HttpBearer):
async def authenticate(self, request, token):
if token == "bearertoken":
return token
if token == "nottherightone":
raise AuthorizationError


def demo_operation(request):
return {"auth": request.auth}

Expand All @@ -85,6 +93,7 @@ def on_custom_error(request, exc):
("apikeycookie", KeyCookie()),
("basic", BasicAuth()),
("bearer", BearerAuth()),
("async_bearer", AsyncBearerAuth()),
("customexception", KeyHeaderCustomException()),
]:
api.get(f"/{path}", auth=auth, operation_id=path)(demo_operation)
Expand Down Expand Up @@ -187,6 +196,18 @@ class MockSuperUser(str):
401,
BODY_UNAUTHORIZED_DEFAULT,
),
(
"/async_bearer",
dict(headers={"Authorization": "Bearer nonexistingtoken"}),
401,
BODY_UNAUTHORIZED_DEFAULT,
),
(
"/async_bearer",
dict(headers={}),
401,
BODY_UNAUTHORIZED_DEFAULT,
),
(
"/bearer",
dict(headers={"Authorization": "Bearer nottherightone"}),
Expand Down Expand Up @@ -215,6 +236,7 @@ def test_schema():
assert schema["components"]["securitySchemes"] == {
"BasicAuth": {"scheme": "basic", "type": "http"},
"BearerAuth": {"scheme": "bearer", "type": "http"},
"AsyncBearerAuth": {"scheme": "bearer", "type": "http"},
"KeyCookie": {"in": "cookie", "name": "key", "type": "apiKey"},
"KeyHeader": {"in": "header", "name": "key", "type": "apiKey"},
"KeyHeaderCustomException": {"in": "header", "name": "key", "type": "apiKey"},
Expand Down