From 22f1e24eed96b2801ca4d9c714eff13c02a94a81 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 00:28:31 +0100 Subject: [PATCH] Manage customer accounts and sign-in access in the panel --- docs/development.md | 18 +- src/coulobre/hosting/static/hosting/panel.css | 23 ++- .../hosting/templates/hosting/base.html | 6 + .../templates/hosting/customer_form.html | 16 ++ .../templates/hosting/customer_list.html | 61 +++++++ src/coulobre/hosting/test_customers.py | 158 ++++++++++++++++++ src/coulobre/hosting/urls.py | 7 + src/coulobre/hosting/views.py | 74 +++++++- 8 files changed, 355 insertions(+), 8 deletions(-) create mode 100644 src/coulobre/hosting/templates/hosting/customer_form.html create mode 100644 src/coulobre/hosting/templates/hosting/customer_list.html diff --git a/docs/development.md b/docs/development.md index 93d9b1c..de995f5 100644 --- a/docs/development.md +++ b/docs/development.md @@ -47,16 +47,26 @@ different file. Keep `COULOBRE_DEBUG` for local development. ## Give a customer access to hosting accounts -In `/admin/`, create a user with a password and add a **Customer** record for -that user. Open **Edit account** in Coulobre Panel and select the customer. -Operators need permission to view customers to make the assignment. Repeat the -assignment for each hosting account the customer should be able to access. +In Coulobre Panel, open **Customers** and select **Add customer**. Enter a +username and initial password. Select the customer when adding or editing a +hosting account. Repeat the assignment for each hosting account the customer +should be able to access. To give an existing user customer access, add a +**Customer** record for that user in `/admin/`. The customer can sign in to Coulobre Panel with that username and password. Their account list shows only the hosting accounts assigned to them. Each account page shows its hosting plan, database requests, DNS zones, and mailbox requests. Customer access is read-only. +Use **Suspend sign-in** in the customer list to block panel access for that +customer across all their hosting accounts. Use **Restore sign-in** to give +them access again. Account assignments are preserved through suspension. + +Operators need the **Can view customer** permission to use the customer list +and select a customer on hosting accounts they can create or edit. **Can add +customer** enables customer creation. **Can change customer** enables +sign-in suspension and restoration. + ## Request a MariaDB database Open a hosting account and select **Request database**. Choose a short suffix diff --git a/src/coulobre/hosting/static/hosting/panel.css b/src/coulobre/hosting/static/hosting/panel.css index 3328f18..bcc92ed 100644 --- a/src/coulobre/hosting/static/hosting/panel.css +++ b/src/coulobre/hosting/static/hosting/panel.css @@ -159,6 +159,25 @@ button, input, select, textarea { background: linear-gradient(currentColor, currentColor) center 35% / 40% 1px no-repeat; } +.nav-icon-customers { + position: relative; + height: 0.46rem; + margin-top: 0.47rem; + border-radius: 0.4rem 0.4rem 2px 2px; +} + +.nav-icon-customers::before { + position: absolute; + left: 50%; + bottom: calc(100% + 2px); + width: 0.39rem; + height: 0.39rem; + transform: translateX(-50%); + border: 1px solid currentColor; + border-radius: 50%; + content: ""; +} + .sidebar-account { display: grid; gap: 0.3rem; @@ -439,12 +458,12 @@ dd { font-weight: 680; } -.status.ready { +.status.ready, .status.active { background: #dcebdc; color: #205038; } -.status.pending { +.status.pending, .status.suspended { background: #f5ead6; color: #6b431b; } diff --git a/src/coulobre/hosting/templates/hosting/base.html b/src/coulobre/hosting/templates/hosting/base.html index b44bfae..42569d3 100644 --- a/src/coulobre/hosting/templates/hosting/base.html +++ b/src/coulobre/hosting/templates/hosting/base.html @@ -23,6 +23,12 @@ Hosting accounts {% endif %} + {% if is_operator and perms.hosting.view_customer %} + + + Customers + + {% endif %} {% if is_operator and perms.hosting.view_hostingplan %} diff --git a/src/coulobre/hosting/templates/hosting/customer_form.html b/src/coulobre/hosting/templates/hosting/customer_form.html new file mode 100644 index 0000000..23c90e4 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/customer_form.html @@ -0,0 +1,16 @@ +{% extends "hosting/base.html" %} +{% block title %}Add customer · Coulobre Panel{% endblock %} +{% block content %} + ← Customers +

Add customer

+
+
+ {% csrf_token %} + {{ form.as_div }} +
+ + Cancel +
+
+
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/customer_list.html b/src/coulobre/hosting/templates/hosting/customer_list.html new file mode 100644 index 0000000..fce179f --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/customer_list.html @@ -0,0 +1,61 @@ +{% extends "hosting/base.html" %} +{% block title %}Customers · Coulobre Panel{% endblock %} +{% block content %} +
+

Customers

+ {% if perms.hosting.add_customer %} + Add customer + {% endif %} +
+
+ + {% if customers %} +
+ + + + + + {% if perms.hosting.change_customer %}{% endif %} + + + + {% for customer in customers %} + + + + {% if perms.hosting.change_customer %} + + {% endif %} + + {% endfor %} + +
UsernameSign-in statusActions
{{ customer }} + {% if customer.user.is_active %}Active + {% else %}Suspended{% endif %} + + {% if not customer.user.is_staff and not customer.user.is_superuser and not customer.user.hosting_reseller %} +
+ {% csrf_token %} + {% if customer.user.is_active %} + + {% else %} + + {% endif %} +
+ {% endif %} +
+
+ {% elif search %} +

No customers match this search.

+ {% else %} +

No customers yet.

+ {% endif %} + {% include "hosting/pagination.html" %} +
+{% endblock %} diff --git a/src/coulobre/hosting/test_customers.py b/src/coulobre/hosting/test_customers.py index 49c632e..86c257a 100644 --- a/src/coulobre/hosting/test_customers.py +++ b/src/coulobre/hosting/test_customers.py @@ -187,3 +187,161 @@ class CustomerAccessTests(TestCase): self.assertContains( self.client.get(self.account.get_absolute_url()), self.account.name ) + + +class CustomerManagementTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.operator = users.create_user("operator", is_staff=True) + cls.operator.user_permissions.add( + *Permission.objects.filter( + content_type__app_label="hosting", + codename__in=( + "view_customer", + "add_customer", + "change_customer", + "view_hostingaccount", + "add_hostingaccount", + ), + ) + ) + cls.customer = Customer.objects.create(user=users.create_user("alice")) + cls.account = HostingAccount.objects.create( + name="Alice hosting", primary_domain="alice.example", customer=cls.customer + ) + + def test_operator_can_create_customer_and_assign_hosting_in_the_panel(self): + self.client.force_login(self.operator) + customers = reverse("panel:customers") + self.assertContains(self.client.get(customers), "Add customer") + + password = "initial-correct-horse-battery-staple" + self.assertRedirects( + self.client.post( + reverse("panel:customer_create"), + { + "username": "charlie", + "password1": password, + "password2": password, + "is_staff": "on", + "is_superuser": "on", + }, + ), + customers, + ) + charlie = Customer.objects.select_related("user").get(user__username="charlie") + self.assertFalse(charlie.user.is_staff) + self.assertFalse(charlie.user.is_superuser) + results = self.client.get(customers, {"q": "CHARLIE"}) + self.assertContains(results, "charlie") + self.assertNotContains(results, "alice") + + response = self.client.post( + reverse("panel:account_create"), + { + "name": "Charlie hosting", + "primary_domain": "charlie.example", + "customer": charlie.pk, + }, + ) + account = HostingAccount.objects.get(customer=charlie) + self.assertRedirects(response, account.get_absolute_url()) + + self.client.logout() + self.assertRedirects( + self.client.post( + reverse("panel:login"), {"username": "charlie", "password": password} + ), + reverse("panel:accounts"), + ) + self.assertContains(self.client.get(reverse("panel:accounts")), account.name) + + def test_customer_creation_preserves_existing_users_and_validates_passwords(self): + self.client.force_login(self.operator) + existing = get_user_model().objects.create_user("existing") + url = reverse("panel:customer_create") + password = "initial-correct-horse-battery-staple" + duplicate = self.client.post( + url, {"username": "Existing", "password1": password, "password2": password} + ) + self.assertIn("username", duplicate.context["form"].errors) + self.assertFalse(Customer.objects.filter(user=existing).exists()) + invalid = self.client.post( + url, {"username": "new", "password1": "123", "password2": "123"} + ) + self.assertIn("password2", invalid.context["form"].errors) + self.assertFalse(get_user_model().objects.filter(username="new").exists()) + + def test_suspend_blocks_an_existing_session_and_preserves_assignments(self): + self.client.force_login(self.customer.user) + self.assertContains( + self.client.get(self.account.get_absolute_url()), self.account.name + ) + operator_client = self.client_class() + operator_client.force_login(self.operator) + url = reverse("panel:customer_access", args=[self.customer.pk]) + customers = reverse("panel:customers") + self.assertEqual(operator_client.get(url).status_code, 405) + self.assertEqual(operator_client.post(url, {}).status_code, 400) + for _ in range(2): + self.assertRedirects( + operator_client.post(url, {"access": "suspend"}), customers + ) + self.assertContains(operator_client.get(customers), "Suspended") + account_url = self.account.get_absolute_url() + self.assertRedirects( + self.client.get(account_url), f"{reverse('panel:login')}?next={account_url}" + ) + self.account.refresh_from_db() + self.assertEqual(self.account.customer_id, self.customer.pk) + + filtered = f"{customers}?q=alice" + self.assertContains(operator_client.get(filtered), f'action="{url}?q=alice"') + self.assertRedirects( + operator_client.post(f"{url}?q=alice", {"access": "restore"}), filtered + ) + self.customer.user.refresh_from_db() + self.assertTrue(self.customer.user.is_active) + self.client.force_login(self.customer.user) + self.assertContains(self.client.get(account_url), self.account.name) + + def test_customer_permissions_cannot_manage_other_customers(self): + self.customer.user.user_permissions.add(*self.operator.user_permissions.all()) + self.client.force_login(self.customer.user) + self.assertNotContains( + self.client.get(reverse("panel:accounts")), reverse("panel:customers") + ) + self.assertEqual(self.client.get(reverse("panel:customers")).status_code, 403) + self.assertEqual( + self.client.post(reverse("panel:customer_create")).status_code, 403 + ) + self.assertEqual( + self.client.post( + reverse("panel:customer_access", args=[self.customer.pk]), + {"access": "suspend"}, + ).status_code, + 403, + ) + + def test_view_only_operator_and_privileged_logins_cannot_be_modified(self): + users = get_user_model().objects + reader = users.create_user("reader") + reader.user_permissions.add(Permission.objects.get(codename="view_customer")) + url = reverse("panel:customer_access", args=[self.customer.pk]) + self.client.force_login(reader) + response = self.client.get(reverse("panel:customers")) + self.assertContains(response, "alice") + self.assertNotContains(response, "Add customer") + self.assertNotContains(response, "Suspend sign-in") + self.assertEqual(self.client.post(url, {"access": "suspend"}).status_code, 403) + self.assertEqual( + self.client.get(reverse("panel:customer_create")).status_code, 403 + ) + + self.client.force_login(self.operator) + self.customer.user.is_staff = True + self.customer.user.save(update_fields=["is_staff"]) + self.assertEqual(self.client.post(url, {"access": "suspend"}).status_code, 404) + self.customer.user.refresh_from_db() + self.assertTrue(self.customer.user.is_active) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 0a39867..d4b6bc8 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -19,6 +19,13 @@ urlpatterns = [ path("accounts/new/", views.AccountCreate.as_view(), name="account_create"), path("accounts//", views.AccountDetail.as_view(), name="account"), path("accounts//edit/", views.AccountEdit.as_view(), name="account_edit"), + path("customers/", views.CustomerList.as_view(), name="customers"), + path("customers/new/", views.CustomerCreate.as_view(), name="customer_create"), + path( + "customers//access/", + views.CustomerAccess.as_view(), + name="customer_access", + ), path( "accounts//databases/new/", views.DatabaseCreate.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 357edcd..8b3d08a 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -1,12 +1,16 @@ +from django.contrib.auth import get_user_model +from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.mixins import PermissionRequiredMixin from django.core.exceptions import ValidationError from django.db import IntegrityError, transaction from django.db.models import Q -from django.http import HttpResponse, JsonResponse +from django.http import Http404, HttpResponse, HttpResponseBadRequest, JsonResponse from django.shortcuts import get_object_or_404, redirect -from django.urls import reverse_lazy +from django.urls import reverse, reverse_lazy +from django.utils.decorators import method_decorator from django.utils.functional import cached_property from django.views import View +from django.views.decorators.debug import sensitive_post_parameters from django.views.generic import CreateView, DetailView, FormView, ListView, UpdateView from django.views.generic.detail import SingleObjectMixin @@ -21,12 +25,14 @@ from .access import ( ) from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record from .models import ( + Customer, HostingAccount, HostingDatabase, HostingDnsZone, HostingMailbox, HostingMailDomain, HostingPlan, + Reseller, WebProvisioningPlan, ) from .reseller_accounts import create_reseller_account @@ -193,6 +199,70 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): return context +class CustomerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView): + queryset = Customer.objects.select_related("user__hosting_reseller").order_by( + "user__username" + ) + permission_required = VIEW_CUSTOMERS + template_name = "hosting/customer_list.html" + context_object_name = "customers" + paginate_by = 20 + + def get_queryset(self): + self.search = self.request.GET.get("q", "").strip()[:150] + queryset = super().get_queryset() + if self.search: + queryset = queryset.filter(user__username__icontains=self.search) + return queryset + + def get_context_data(self, **kwargs): + return super().get_context_data(search=self.search, **kwargs) + + +@method_decorator(sensitive_post_parameters("password1", "password2"), name="dispatch") +class CustomerCreate(OperatorOnlyMixin, PermissionRequiredMixin, FormView): + permission_required = (VIEW_CUSTOMERS, "hosting.add_customer") + form_class = UserCreationForm + template_name = "hosting/customer_form.html" + success_url = reverse_lazy("panel:customers") + + def form_valid(self, form): + try: + with transaction.atomic(): + Customer.objects.create(user=form.save()) + except IntegrityError: + user = form.instance + users = get_user_model().objects + if not users.filter(username__iexact=user.username).exists(): + raise + form.add_error( + "username", user.unique_error_message(type(user), ["username"]) + ) + return self.form_invalid(form) + return super().form_valid(form) + + +class CustomerAccess(OperatorOnlyMixin, PermissionRequiredMixin, View): + permission_required = (VIEW_CUSTOMERS, "hosting.change_customer") + + def post(self, request, pk): + access = request.POST.get("access") + if access not in ("restore", "suspend"): + return HttpResponseBadRequest( + "Choose whether to restore or suspend sign-in." + ) + customer = Customer.objects.filter(pk=pk).values("user_id") + resellers = Reseller.objects.values("user_id") + users = ( + get_user_model() + .objects.filter(pk__in=customer, is_staff=False, is_superuser=False) + .exclude(pk__in=resellers) + ) + if not users.update(is_active=access == "restore"): + raise Http404 + return redirect(reverse("panel:customers", query=request.GET)) + + class DatabaseCreate(OperatorOnlyMixin, PermissionRequiredMixin, CreateView): model = HostingDatabase fields = ("suffix",)