2019-01-04 12:52:36 +00:00
|
|
|
from django.contrib.auth import backends, get_user_model
|
2020-04-01 12:34:56 +00:00
|
|
|
from allauth.account import auth_backends
|
|
|
|
|
|
|
|
from funkwhale_api.common import authentication
|
|
|
|
|
|
|
|
|
|
|
|
# ugly but allauth doesn't offer an easy way to override the querysets
|
|
|
|
# used to retrieve users, so we monkey patch
|
|
|
|
def decorate_for_auth(func):
|
|
|
|
def inner(*args, **kwargs):
|
|
|
|
qs = func(*args, **kwargs)
|
|
|
|
try:
|
|
|
|
return qs.for_auth()
|
|
|
|
except AttributeError:
|
|
|
|
return (
|
|
|
|
get_user_model()
|
|
|
|
.objects.all()
|
|
|
|
.for_auth()
|
|
|
|
.filter(pk__in=[u.pk for u in qs])
|
|
|
|
)
|
|
|
|
|
|
|
|
return inner
|
|
|
|
|
|
|
|
|
|
|
|
auth_backends.filter_users_by_email = decorate_for_auth(
|
|
|
|
auth_backends.filter_users_by_email
|
|
|
|
)
|
|
|
|
auth_backends.filter_users_by_username = decorate_for_auth(
|
|
|
|
auth_backends.filter_users_by_username
|
|
|
|
)
|
2019-01-04 12:52:36 +00:00
|
|
|
|
|
|
|
|
|
|
|
class ModelBackend(backends.ModelBackend):
|
|
|
|
def get_user(self, user_id):
|
|
|
|
"""
|
|
|
|
Select related to avoid two additional queries
|
|
|
|
"""
|
|
|
|
try:
|
2020-04-01 12:34:56 +00:00
|
|
|
user = get_user_model().objects.all().for_auth().get(pk=user_id)
|
2019-01-04 12:52:36 +00:00
|
|
|
except get_user_model().DoesNotExist:
|
|
|
|
return None
|
2020-04-01 12:34:56 +00:00
|
|
|
|
2019-01-04 12:52:36 +00:00
|
|
|
return user if self.user_can_authenticate(user) else None
|
2020-04-01 12:34:56 +00:00
|
|
|
|
|
|
|
def user_can_authenticate(self, user):
|
|
|
|
return super().user_can_authenticate(
|
|
|
|
user
|
|
|
|
) and not authentication.should_verify_email(user)
|
|
|
|
|
|
|
|
|
|
|
|
class AllAuthBackend(auth_backends.AuthenticationBackend, ModelBackend):
|
|
|
|
pass
|