Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions account/auth_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,31 @@
from account.utils import get_user_lookup_kwargs


class UsernameAuthenticationBackend(ModelBackend):
User = get_user_model()


class AccountModelBackend(ModelBackend):
"""
This authentication backend ensures that the account is always selected
on any query with the user, so we don't issue extra unnecessary queries
"""

def get_user(self, user_id):
"""Get the user and select account at the same time"""
user = User._default_manager.filter(pk=user_id).select_related('account').first()
if not user:
return None
return user if self.user_can_authenticate(user) else None


class UsernameAuthenticationBackend(AccountModelBackend):
"""Username authentication"""

def authenticate(self, request, username=None, password=None, **kwargs):
"""Authenticate the user based on user"""
if username is None or password is None:
return None

User = get_user_model()
try:
lookup_kwargs = get_user_lookup_kwargs({
"{username}__iexact": username
Expand All @@ -25,9 +43,11 @@ def authenticate(self, request, username=None, password=None, **kwargs):
return user


class EmailAuthenticationBackend(ModelBackend):
class EmailAuthenticationBackend(AccountModelBackend):
"""Email authentication"""

def authenticate(self, request, username=None, password=None, **kwargs):
"""Authenticate the user based email"""
qs = EmailAddress.objects.filter(Q(primary=True) | Q(verified=True))

if username is None or password is None:
Expand Down
7 changes: 3 additions & 4 deletions account/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,9 @@ class Account(models.Model):
def for_request(cls, request):
user = getattr(request, "user", None)
if user and user.is_authenticated:
try:
return Account._default_manager.get(user=user)
except Account.DoesNotExist:
pass
account = user.account
if account:
return account
return AnonymousAccount(request)

@classmethod
Expand Down
7 changes: 7 additions & 0 deletions docs/installation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@ Optionally include ``account.middleware.ExpiredPasswordMiddleware`` in
...
]

Set the authentication backends to the following::

AUTHENTICATION_BACKENDS = [
'account.auth_backends.AccountModelBackend',
'django.contrib.auth.backends.ModelBackend'
]

Once everything is in place make sure you run ``migrate`` to modify the
database with the ``account`` app models.

Expand Down