Merge pull request #2952 from Ernest0x/patch-3

Support basic authentication with custom user models that change username field
This commit is contained in:
Tom Christie 2015-05-20 09:56:38 +01:00
commit 010f2ee9bd
2 changed files with 15 additions and 1 deletions

View File

@ -8,6 +8,7 @@ from django.middleware.csrf import CsrfViewMiddleware
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):
@ -85,7 +86,12 @@ class BasicAuthentication(BaseAuthentication):
"""
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.'))

View File

@ -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