Skip to content

Commit

Permalink
Merge pull request #2952 from Ernest0x/patch-3
Browse files Browse the repository at this point in the history
Support basic authentication with custom user models that change username field
  • Loading branch information
tomchristie committed May 20, 2015
2 parents e33fed7 + 192719e commit 010f2ee
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
8 changes: 7 additions & 1 deletion rest_framework/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from django.utils.translation import ugettext_lazy as _
from rest_framework import exceptions, HTTP_HEADER_ENCODING
from rest_framework.authtoken.models import Token
from rest_framework.compat import get_user_model


def get_authorization_header(request):
Expand Down Expand Up @@ -85,7 +86,12 @@ def authenticate_credentials(self, userid, password):
"""
Authenticate the userid and password against username and password.
"""
user = authenticate(username=userid, password=password)
username_field = getattr(get_user_model(), 'USERNAME_FIELD', 'username')
credentials = {
username_field: userid,
'password': password
}
user = authenticate(**credentials)

if user is None:
raise exceptions.AuthenticationFailed(_('Invalid username/password.'))
Expand Down
8 changes: 8 additions & 0 deletions rest_framework/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,14 @@ def get_model_name(model_cls):
return model_cls._meta.module_name


# Support custom user models in Django 1.5+
try:
from django.contrib.auth import get_user_model
except ImportError:
from django.contrib.auth.models import User
get_user_model = lambda: User


# View._allowed_methods only present from 1.5 onwards
if django.VERSION >= (1, 5):
from django.views.generic import View
Expand Down

0 comments on commit 010f2ee

Please sign in to comment.