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

Support basic authentication with custom user models that change username field #2952

Merged
merged 6 commits into from May 20, 2015
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 7 additions & 1 deletion rest_framework/authentication.py
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
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