Skip to content

Commit 277b704

Browse files
authored
Merge pull request #1387 from mmkhitaryan/master
Fix of TypeError when returning None in AuthBase.__call__ from async code #1386
2 parents 67c855e + 2b27afe commit 277b704

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

ninja/operation.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import inspect
12
from typing import (
23
TYPE_CHECKING,
34
Any,
@@ -204,7 +205,9 @@ def _run_authentication(self, request: HttpRequest) -> Optional[HttpResponse]:
204205
for callback in self.auth_callbacks:
205206
try:
206207
if is_async_callable(callback) or getattr(callback, "is_async", False):
207-
result = async_to_sync(callback)(request)
208+
result = callback(request)
209+
if inspect.iscoroutine(result):
210+
result = async_to_sync(callback)(request)
208211
else:
209212
result = callback(request)
210213
except Exception as exc:

tests/test_auth.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,14 @@ def authenticate(self, request, token):
6565
raise AuthorizationError
6666

6767

68+
class AsyncBearerAuth(HttpBearer):
69+
async def authenticate(self, request, token):
70+
if token == "bearertoken":
71+
return token
72+
if token == "nottherightone":
73+
raise AuthorizationError
74+
75+
6876
def demo_operation(request):
6977
return {"auth": request.auth}
7078

@@ -87,6 +95,7 @@ def on_custom_error(request, exc):
8795
("apikeycookie", KeyCookie()),
8896
("basic", BasicAuth()),
8997
("bearer", BearerAuth()),
98+
("async_bearer", AsyncBearerAuth()),
9099
("customexception", KeyHeaderCustomException()),
91100
]:
92101
api.get(f"/{path}", auth=auth, operation_id=path)(demo_operation)
@@ -216,6 +225,18 @@ class MockStaffUser(str):
216225
401,
217226
BODY_UNAUTHORIZED_DEFAULT,
218227
),
228+
(
229+
"/async_bearer",
230+
dict(headers={"Authorization": "Bearer nonexistingtoken"}),
231+
401,
232+
BODY_UNAUTHORIZED_DEFAULT,
233+
),
234+
(
235+
"/async_bearer",
236+
dict(headers={}),
237+
401,
238+
BODY_UNAUTHORIZED_DEFAULT,
239+
),
219240
(
220241
"/bearer",
221242
dict(headers={"Authorization": "Bearer nottherightone"}),
@@ -244,6 +265,7 @@ def test_schema():
244265
assert schema["components"]["securitySchemes"] == {
245266
"BasicAuth": {"scheme": "basic", "type": "http"},
246267
"BearerAuth": {"scheme": "bearer", "type": "http"},
268+
"AsyncBearerAuth": {"scheme": "bearer", "type": "http"},
247269
"KeyCookie": {"in": "cookie", "name": "key", "type": "apiKey"},
248270
"KeyHeader": {"in": "header", "name": "key", "type": "apiKey"},
249271
"KeyHeaderCustomException": {"in": "header", "name": "key", "type": "apiKey"},

0 commit comments

Comments
 (0)