Skip to content

Commit 010f2ee

Browse files
committed
Merge pull request #2952 from Ernest0x/patch-3
Support basic authentication with custom user models that change username field
2 parents e33fed7 + 192719e commit 010f2ee

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

rest_framework/authentication.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from django.utils.translation import ugettext_lazy as _
99
from rest_framework import exceptions, HTTP_HEADER_ENCODING
1010
from rest_framework.authtoken.models import Token
11+
from rest_framework.compat import get_user_model
1112

1213

1314
def get_authorization_header(request):
@@ -85,7 +86,12 @@ def authenticate_credentials(self, userid, password):
8586
"""
8687
Authenticate the userid and password against username and password.
8788
"""
88-
user = authenticate(username=userid, password=password)
89+
username_field = getattr(get_user_model(), 'USERNAME_FIELD', 'username')
90+
credentials = {
91+
username_field: userid,
92+
'password': password
93+
}
94+
user = authenticate(**credentials)
8995

9096
if user is None:
9197
raise exceptions.AuthenticationFailed(_('Invalid username/password.'))

rest_framework/compat.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,14 @@ def get_model_name(model_cls):
119119
return model_cls._meta.module_name
120120

121121

122+
# Support custom user models in Django 1.5+
123+
try:
124+
from django.contrib.auth import get_user_model
125+
except ImportError:
126+
from django.contrib.auth.models import User
127+
get_user_model = lambda: User
128+
129+
122130
# View._allowed_methods only present from 1.5 onwards
123131
if django.VERSION >= (1, 5):
124132
from django.views.generic import View

0 commit comments

Comments
 (0)