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

Username field #16

Merged
merged 2 commits into from
Aug 1, 2024
Merged
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
3 changes: 3 additions & 0 deletions docs/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ Same-site policy to be used for refresh token cookie, defaults to `"Strict"`.
This is the path set on the cookie for refresh token, this path needs to match the url endpoint you are exposing for
web token refresh. Defaults to `"/api/auth/web/token-refresh"`.

### USERNAME_FIELD
This is the field on the User model that is used as the username. Defaults to `"username"`.

### TOKEN_CLAIM_USER_ATTRIBUTE_MAP
A dictionary mapping token claims to corresponding User model attributes. Defaults to the following:
```python
Expand Down
5 changes: 3 additions & 2 deletions ninja_simple_jwt/auth/views/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
get_refresh_token_for_user,
)
from ninja_simple_jwt.settings import ninja_simple_jwt_settings
from ninja_simple_jwt.utils import make_authentication_params

mobile_auth_router = Router()
web_auth_router = Router()
Expand All @@ -28,7 +29,7 @@
@mobile_auth_router.post("/sign-in", response=MobileSignInResponse, url_name="mobile_signin")
def mobile_sign_in(request: HttpRequest, payload: SignInRequest) -> dict:
payload_data = payload.dict()
user = authenticate(username=payload_data["username"], password=payload_data["password"])
user = authenticate(**make_authentication_params(payload_data))

if user is None:
raise AuthenticationError()
Expand All @@ -53,7 +54,7 @@ def mobile_token_refresh(request: HttpRequest, payload: MobileTokenRefreshReques
@web_auth_router.post("/sign-in", response=WebSignInResponse, url_name="web_signin")
def web_sign_in(request: HttpRequest, payload: SignInRequest, response: HttpResponse) -> dict:
payload_data = payload.dict()
user = authenticate(username=payload_data["username"], password=payload_data["password"])
user = authenticate(**make_authentication_params(payload_data))

if user is None:
raise AuthenticationError()
Expand Down
2 changes: 2 additions & 0 deletions ninja_simple_jwt/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class NinjaSimpleJwtSettingsDict(TypedDict):
WEB_REFRESH_COOKIE_HTTP_ONLY: NotRequired[bool]
WEB_REFRESH_COOKIE_SAME_SITE_POLICY: NotRequired[str]
WEB_REFRESH_COOKIE_PATH: NotRequired[str]
USERNAME_FIELD: NotRequired[str]
TOKEN_CLAIM_USER_ATTRIBUTE_MAP: NotRequired[dict[str, str]]
TOKEN_USER_ENCODER_CLS: NotRequired[str]

Expand All @@ -36,6 +37,7 @@ class NinjaSimpleJwtSettingsDict(TypedDict):
"WEB_REFRESH_COOKIE_HTTP_ONLY": True,
"WEB_REFRESH_COOKIE_SAME_SITE_POLICY": "Strict",
"WEB_REFRESH_COOKIE_PATH": "/api/auth/web/token-refresh",
"USERNAME_FIELD": "username",
"TOKEN_CLAIM_USER_ATTRIBUTE_MAP": {
"user_id": "id",
"username": "username",
Expand Down
7 changes: 7 additions & 0 deletions ninja_simple_jwt/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from ninja_simple_jwt.settings import ninja_simple_jwt_settings


def make_authentication_params(params: dict) -> dict:
print(params)
print(ninja_simple_jwt_settings.USERNAME_FIELD)
return {ninja_simple_jwt_settings.USERNAME_FIELD: params["username"], "password": params["password"]}
4 changes: 2 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

black==23.11.0
cryptography==41.0.7
black==24.4.2
cryptography==43.0.0
Django>=4.2
django-ninja>=1.0
django-stubs[compatible-mypy]==4.2.7
Expand Down
25 changes: 25 additions & 0 deletions tests/test_auth/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from typing import Any

from django.test import TestCase

from ninja_simple_jwt.settings import DEFAULTS
from ninja_simple_jwt.utils import make_authentication_params


class TestMakeAuthenticationParams(TestCase):
@staticmethod
def merge_settings(**kwargs: Any) -> dict:
return {**DEFAULTS, **kwargs}

def test_make_default_username_field_params(self) -> None:
with self.settings():
params = {"username": "username", "password": "password"}
result = make_authentication_params(params)
self.assertEqual(params, result, "Default settings should return the same params.")

def test_make_customized_username_field_params(self) -> None:
with self.settings(NINJA_SIMPLE_JWT=self.merge_settings(USERNAME_FIELD="email")):
params = {"username": "email", "password": "password"}
expected = {"email": "email", "password": "password"}
result = make_authentication_params(params)
self.assertEqual(expected, result, "Customized settings should return the same params.")
Loading