From 4f53cb72546e31bf99a23414d1669a00b554aec3 Mon Sep 17 00:00:00 2001 From: Ivan Ivanov Date: Fri, 25 Jul 2025 00:20:38 +0300 Subject: [PATCH] feat(admin): add custom admin site that reuses the allauth login --- docker-app/qfieldcloud/core/admin.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docker-app/qfieldcloud/core/admin.py b/docker-app/qfieldcloud/core/admin.py index 4da43eb58..b983bb2b0 100644 --- a/docker-app/qfieldcloud/core/admin.py +++ b/docker-app/qfieldcloud/core/admin.py @@ -20,6 +20,7 @@ from django.contrib.admin.sites import AdminSite from django.contrib.admin.templatetags.admin_urls import admin_urlname from django.contrib.admin.views.main import ChangeList +from django.contrib.auth.views import redirect_to_login from django.core.exceptions import PermissionDenied, ValidationError from django.db.models import Q, QuerySet from django.db.models.fields.json import JSONField @@ -78,6 +79,22 @@ def __init__(self, *args, **kwargs) -> None: for _model, model_admin in self._registry.items(): model_admin.admin_site = self + def login( + self, request: HttpRequest, extra_context: dict[str, Any] | None = None + ) -> HttpResponse: + """Override the default Django admin login view to redirect to the Allauth's login view.""" + if request.method == "GET" and self.has_permission(request): + # Already logged-in, redirect to admin index + index_path = reverse("admin:index", current_app=self.name) + return HttpResponseRedirect(index_path) + + # If the user is not authenticated, redirect to the accounts login page, but keep the query string that has the original request URL. + return redirect_to_login( + request.GET.get("next", ""), login_url=reverse(settings.LOGIN_URL) + ) + + # TODO consider adding a logout view to redirect to the Allauth's logout view, but then we lose the nice template we have right now. + qfc_admin_site = QfcAdminSite(name="qfc_admin_site")