From eb4e1ad198c3375e27a7504ca422deea882d4fc1 Mon Sep 17 00:00:00 2001 From: Jake Howard Date: Fri, 24 May 2024 21:37:51 +0100 Subject: [PATCH] Allow the admin to be enabled --- yamdl_playground/core/admin.py | 29 +++++++++++++++++++++++++++++ yamdl_playground/core/apps.py | 5 +++++ yamdl_playground/core/middleware.py | 26 ++++++++++++++++++++++++++ yamdl_playground/settings.py | 26 ++++++++++++++++++++++++++ yamdl_playground/urls.py | 6 ++++++ 5 files changed, 92 insertions(+) create mode 100644 yamdl_playground/core/admin.py create mode 100644 yamdl_playground/core/middleware.py diff --git a/yamdl_playground/core/admin.py b/yamdl_playground/core/admin.py new file mode 100644 index 0000000..1e18b7e --- /dev/null +++ b/yamdl_playground/core/admin.py @@ -0,0 +1,29 @@ +from django.contrib import admin +from .models import Page + +class PageAdmin(admin.ModelAdmin): + list_display = ["id", "title", "slug"] + list_display_links = ["id", "title"] + sortable_by = ["title"] + ordering = ["title"] + + def has_add_permission(self, request, obj=None): + return False + + def has_delete_permission(self, request, obj=None): + return False + + def has_change_permission(self, request, obj=None): + return False + + def get_readonly_fields(self, request, obj=None): + return [field.name for field in (obj._meta.fields + obj._meta.many_to_many)] + + @admin.options.csrf_protect_m + def changeform_view(self, *args, **kwargs): + """ + Override to prevent issues with `db_for_write` + """ + return self._changeform_view(*args, **kwargs) + +admin.site.register(Page, PageAdmin) diff --git a/yamdl_playground/core/apps.py b/yamdl_playground/core/apps.py index 54314c8..5ed3227 100644 --- a/yamdl_playground/core/apps.py +++ b/yamdl_playground/core/apps.py @@ -3,6 +3,7 @@ from django.db import connections from django.db.models.signals import post_save import warnings from django.utils.html import strip_tags +from django.core.management import call_command class CoreConfig(AppConfig): @@ -19,6 +20,10 @@ class CoreConfig(AppConfig): with warnings.catch_warnings(): # Django doesn't like running DB queries during app initialization warnings.filterwarnings("ignore", module="django.db", category=RuntimeWarning) + + # Run migrations, if there are any + call_command("migrate", verbosity=0, no_input=True) + with connection.cursor() as cursor: cursor.execute("CREATE VIRTUAL TABLE search_index USING fts5(body, content='');") diff --git a/yamdl_playground/core/middleware.py b/yamdl_playground/core/middleware.py new file mode 100644 index 0000000..f545f44 --- /dev/null +++ b/yamdl_playground/core/middleware.py @@ -0,0 +1,26 @@ +from django.contrib.auth.models import AnonymousUser + +class FakeUser(AnonymousUser): + is_authenticated = True + is_anonymous = False + is_staff = True + is_active = True + is_superuser = True + username = "Fake user" + + def has_module_perms(self, module): + # Don't allow access to the 'auth' app + # Also stops it showing up in the admin + return module not in {"auth"} + + def has_perm(self, perm, obj=None): + return True + +class FakeAuthenticationMiddleware: + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + # HACK: Inject our user in to user caches + request._cached_user = request._acached_user = FakeUser() + return self.get_response(request) diff --git a/yamdl_playground/settings.py b/yamdl_playground/settings.py index 0aae9a2..3a12eaa 100644 --- a/yamdl_playground/settings.py +++ b/yamdl_playground/settings.py @@ -11,6 +11,7 @@ https://docs.djangoproject.com/en/5.0/ref/settings/ """ from pathlib import Path +import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent @@ -188,3 +189,28 @@ LOGGING = { DEBUG_TOOLBAR_CONFIG = { "SHOW_TOOLBAR_CALLBACK": "yamdl_playground.core.utils.show_debug_toolbar" } + + +if "ENABLE_ADMIN" in os.environ: + INSTALLED_APPS.extend([ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.messages', + 'django.contrib.sessions', + ]) + + MIDDLEWARE.extend([ + 'yamdl_playground.core.middleware.FakeAuthenticationMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + ]) + + # To make sure it's definitely working + AUTHENTICATION_BACKENDS = [] + + TEMPLATES[0]["OPTIONS"]["context_processors"].extend([ + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ]) diff --git a/yamdl_playground/urls.py b/yamdl_playground/urls.py index 93f54fb..2d12acc 100644 --- a/yamdl_playground/urls.py +++ b/yamdl_playground/urls.py @@ -16,6 +16,7 @@ Including another URLconf """ from django.urls import path, include from .core import views +from django.apps import apps urlpatterns = [ path("search/", views.search), @@ -23,3 +24,8 @@ urlpatterns = [ path("__debug__/", include("debug_toolbar.urls")), path("cached-content//", views.cached_content) ] + +if apps.is_installed("django.contrib.admin"): + from django.contrib import admin + + urlpatterns.append(path("admin/", admin.site.urls))