-
-
Notifications
You must be signed in to change notification settings - Fork 7.1k
Fix #8839: Use USERNAME_FIELD instead of hardcoded 'username' in AuthTokenSerializer #9932
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
base: main
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,4 @@ | ||
| from django.contrib.auth import authenticate | ||
| from django.contrib.auth import authenticate, get_user_model | ||
| from django.utils.translation import gettext_lazy as _ | ||
|
|
||
| from rest_framework import serializers | ||
|
|
@@ -20,13 +20,25 @@ class AuthTokenSerializer(serializers.Serializer): | |
| read_only=True | ||
| ) | ||
|
|
||
| def __init__(self, *args, **kwargs): | ||
| super().__init__(*args, **kwargs) | ||
| User = get_user_model() | ||
| username_field = User.USERNAME_FIELD | ||
| if username_field != 'username': | ||
| self.fields[username_field] = self.fields.pop('username') | ||
| self.fields[username_field].label = _(username_field.capitalize()) | ||
|
|
||
|
Comment on lines
+26
to
+38
|
||
| def validate(self, attrs): | ||
| username = attrs.get('username') | ||
| User = get_user_model() | ||
| username_field = User.USERNAME_FIELD | ||
| username = attrs.get(username_field) | ||
| password = attrs.get('password') | ||
|
Comment on lines
+41
to
43
|
||
|
|
||
| if username and password: | ||
| user = authenticate(request=self.context.get('request'), | ||
| username=username, password=password) | ||
| user = authenticate( | ||
| request=self.context.get('request'), | ||
| **{username_field: username, 'password': password} | ||
| ) | ||
|
Comment on lines
+23
to
+49
|
||
|
|
||
| # The authenticate call simply returns None for is_active=False | ||
| # users. (Assuming the default ModelBackend authentication | ||
|
|
@@ -35,7 +47,7 @@ def validate(self, attrs): | |
| msg = _('Unable to log in with provided credentials.') | ||
| raise serializers.ValidationError(msg, code='authorization') | ||
| else: | ||
| msg = _('Must include "username" and "password".') | ||
| msg = _(f'Must include "{username_field}" and "password".') | ||
| raise serializers.ValidationError(msg, code='authorization') | ||
|
Comment on lines
57
to
59
|
||
|
|
||
| attrs['user'] = user | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.