Skip to content

Commit 29beb1e

Browse files
committed
refactored AsyncSessionAuth #201
1 parent 0c0f86f commit 29beb1e

File tree

3 files changed

+19
-14
lines changed

3 files changed

+19
-14
lines changed

ninja_extra/security/session.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from django.conf import settings
2+
from django.contrib.auth.middleware import get_user
23
from django.http import HttpRequest
3-
from ninja.signature import is_async
44

55
from ninja_extra.security.api_key import AsyncAPIKeyCookie
66

@@ -17,10 +17,12 @@ class AsyncSessionAuth(AsyncAPIKeyCookie):
1717
async def authenticate(
1818
self, request: HttpRequest, key: Optional[str]
1919
) -> Optional[Any]:
20-
if hasattr(request, "auser") and is_async(request.auser):
20+
from asgiref.sync import sync_to_async
21+
22+
if hasattr(request, "auser"):
2123
current_user = await request.auser()
2224
else:
23-
current_user = request.user
25+
current_user = await sync_to_async(get_user)(request)
2426

2527
if current_user.is_authenticated:
2628
return current_user

tests/test_async_auth.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
AsyncAPIKeyQuery,
1414
AsyncHttpBasicAuth,
1515
AsyncHttpBearer,
16-
async_django_auth,
1716
)
1817

1918
user_secret = base64.b64encode("admin:secret".encode("utf-8")).decode()
@@ -145,7 +144,6 @@ async def test_csrf_on():
145144
api = NinjaExtraAPI(csrf=True, urls_namespace="async_auth")
146145

147146
for path, auth in [
148-
("django_auth", async_django_auth),
149147
("callable", callable_auth),
150148
("apikeyquery", KeyQuery()),
151149
("apikeyheader", KeyHeader()),
@@ -163,8 +161,6 @@ async def test_csrf_on():
163161
@pytest.mark.parametrize(
164162
"path,kwargs,expected_code,expected_body",
165163
[
166-
("/django_auth", {}, 401, BODY_UNAUTHORIZED_DEFAULT),
167-
("/django_auth", {"user": MockUser("admin")}, 200, {"auth": "admin"}),
168164
("/callable", {}, 401, BODY_UNAUTHORIZED_DEFAULT),
169165
("/callable?auth=demo", {}, 200, {"auth": "demo"}),
170166
("/apikeyquery", {}, 401, BODY_UNAUTHORIZED_DEFAULT),
Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,47 @@
11
from unittest.mock import AsyncMock, Mock
22

33
import pytest
4+
from asgiref.sync import sync_to_async
5+
from django.contrib.sessions.middleware import SessionMiddleware
46
from django.http import HttpRequest
57

6-
from ninja_extra.security.session import AsyncSessionAuth
8+
from ninja_extra.security import async_django_auth
79

810

911
@pytest.mark.asyncio
12+
@pytest.mark.django_db
1013
async def test_async_session_auth():
11-
auth = AsyncSessionAuth()
1214
request = HttpRequest()
1315

16+
# Add session to request
17+
middleware = SessionMiddleware(lambda x: x)
18+
await sync_to_async(middleware.process_request)(request)
19+
await sync_to_async(request.session.save)()
20+
1421
# Test async authenticated user
1522
async_user = AsyncMock()
1623
async_user.is_authenticated = True
1724
request.auser = AsyncMock(return_value=async_user)
1825

19-
authenticated_user = await auth.authenticate(request, None)
26+
authenticated_user = await async_django_auth.authenticate(request, None)
2027
assert authenticated_user == async_user
2128
request.auser.assert_called_once()
2229

2330
# Test async non-authenticated user
2431
async_user.is_authenticated = False
25-
authenticated_user = await auth.authenticate(request, None)
32+
authenticated_user = await async_django_auth.authenticate(request, None)
2633
assert authenticated_user is None
2734

2835
# Test non-async authenticated user
2936
delattr(request, "auser")
3037
sync_user = Mock()
3138
sync_user.is_authenticated = True
32-
request.user = sync_user
39+
request._cached_user = sync_user
3340

34-
authenticated_user = await auth.authenticate(request, None)
41+
authenticated_user = await async_django_auth.authenticate(request, None)
3542
assert authenticated_user == sync_user
3643

3744
# Test non-async non-authenticated user
3845
sync_user.is_authenticated = False
39-
authenticated_user = await auth.authenticate(request, None)
46+
authenticated_user = await async_django_auth.authenticate(request, None)
4047
assert authenticated_user is None

0 commit comments

Comments
 (0)