from django.conf import settings from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django_object_actions import DjangoObjectActions, action from .models import CustomUser # Must match loadtest/locustfile.py's own defaults (LOAD_TEST_USER_COUNT, # LOAD_TEST_USER_PREFIX, LOAD_TEST_PASSWORD) - see that file for what these # accounts are for and how they're used. LOAD_TEST_USER_COUNT = 500 LOAD_TEST_USER_PREFIX = "loadtest" LOAD_TEST_PASSWORD = "loadtest-only-password" @admin.register(CustomUser) class CustomUserAdmin(DjangoObjectActions, UserAdmin): """Admin interface for CustomUser.""" # Add custom fields to the user admin fieldsets = UserAdmin.fieldsets + ( ( "CAS Information", { "fields": ("cas_user_id", "cas_groups", "cas_attributes"), }, ), ) # Add custom fields to the list display list_display = UserAdmin.list_display + ("cas_user_id", "get_cas_groups_display") # Add search fields search_fields = UserAdmin.search_fields + ("cas_user_id",) # Add filters list_filter = UserAdmin.list_filter + ("cas_groups",) # Make CAS fields readonly in admin readonly_fields = ("cas_user_id", "cas_groups", "cas_attributes") changelist_actions = ("create_load_test_users",) def get_cas_groups_display(self, obj): """Display CAS groups in admin list.""" return obj.get_cas_groups_display() get_cas_groups_display.short_description = "CAS Groups" def has_delete_permission(self, request, obj=None): return False def get_changelist_actions(self, request): # Second layer of the same guard rail as the login endpoint itself # (see testing_auth_views.py): the button doesn't even show up # unless this deployment opted into load testing. if not settings.LOAD_TEST_LOGIN_ENABLED: return [] return super().get_changelist_actions(request) @action( label="Create load test users", description=( "Create/reset the local loadtestN accounts used by " "loadtest/locustfile.py - authenticates via ModelBackend, " "never the real CAS server" ), ) def create_load_test_users(self, request, _queryset): created = 0 for i in range(LOAD_TEST_USER_COUNT): username = f"{LOAD_TEST_USER_PREFIX}{i}" user, was_created = CustomUser.objects.get_or_create(username=username) user.set_password(LOAD_TEST_PASSWORD) user.save() created += was_created self.message_user( request, f"{created} created, {LOAD_TEST_USER_COUNT - created} already existed " f"(password reset on all {LOAD_TEST_USER_COUNT}).", )