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 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions rest_framework/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +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 +85,16 @@ def authenticate_credentials(self, userid, password):
"""
Authenticate the userid and password against username and password.
"""
user = authenticate(username=userid, password=password)
user_model = get_user_model()
if hasattr(user_model, 'USERNAME_FIELD'):
username_field = user_model.USERNAME_FIELD
else:
username_field = 'username'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could slim this down with username_field = getattr(user_model, 'USERNAME_FIELD', 'username') I think?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just addressed that

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