From 67de32ccc23c3c7245f8b4623d96f93963ed1e34 Mon Sep 17 00:00:00 2001 From: Eliot Berriot Date: Fri, 4 Jan 2019 13:52:36 +0100 Subject: [PATCH] =?UTF-8?q?Removed=202=C2=A0DB=20queries=20per=20request?= =?UTF-8?q?=20when=20user=20is=20authenticated?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/config/settings/common.py | 2 +- api/funkwhale_api/users/auth_backends.py | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 api/funkwhale_api/users/auth_backends.py diff --git a/api/config/settings/common.py b/api/config/settings/common.py index c0ff1e828..1976ddcab 100644 --- a/api/config/settings/common.py +++ b/api/config/settings/common.py @@ -327,7 +327,7 @@ SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") # AUTHENTICATION CONFIGURATION # ------------------------------------------------------------------------------ AUTHENTICATION_BACKENDS = ( - "django.contrib.auth.backends.ModelBackend", + "funkwhale_api.users.auth_backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ) SESSION_COOKIE_HTTPONLY = False diff --git a/api/funkwhale_api/users/auth_backends.py b/api/funkwhale_api/users/auth_backends.py new file mode 100644 index 000000000..404b34f4d --- /dev/null +++ b/api/funkwhale_api/users/auth_backends.py @@ -0,0 +1,17 @@ +from django.contrib.auth import backends, get_user_model + + +class ModelBackend(backends.ModelBackend): + def get_user(self, user_id): + """ + Select related to avoid two additional queries + """ + try: + user = ( + get_user_model() + ._default_manager.select_related("actor__domain") + .get(pk=user_id) + ) + except get_user_model().DoesNotExist: + return None + return user if self.user_can_authenticate(user) else None