From 8de6eb8d88df6dd3ce2e6789161f15434736b7f8 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 00:23:52 +0100 Subject: [PATCH 1/4] Add account-scoped access for hosting customers --- docs/development.md | 12 ++ src/coulobre/admin.py | 6 +- src/coulobre/hosting/access.py | 36 +++- src/coulobre/hosting/admin.py | 11 +- .../migrations/0011_customer_access.py | 65 ++++++ src/coulobre/hosting/models.py | 21 +- .../templates/hosting/account_detail.html | 39 ++-- .../templates/hosting/account_list.html | 6 +- .../hosting/templates/hosting/base.html | 6 +- src/coulobre/hosting/test_customers.py | 189 ++++++++++++++++++ src/coulobre/hosting/views.py | 50 +++-- 11 files changed, 390 insertions(+), 51 deletions(-) create mode 100644 src/coulobre/hosting/migrations/0011_customer_access.py create mode 100644 src/coulobre/hosting/test_customers.py diff --git a/docs/development.md b/docs/development.md index 1da7d02..93d9b1c 100644 --- a/docs/development.md +++ b/docs/development.md @@ -45,6 +45,18 @@ and node deployment files. The local database defaults to `db.sqlite3`. Set `COULOBRE_SQLITE_PATH` to use a 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. + +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. + ## Request a MariaDB database Open a hosting account and select **Request database**. Choose a short suffix diff --git a/src/coulobre/admin.py b/src/coulobre/admin.py index 59e9741..3f2679b 100644 --- a/src/coulobre/admin.py +++ b/src/coulobre/admin.py @@ -1,14 +1,12 @@ from django.contrib.admin import AdminSite from django.contrib.admin.apps import AdminConfig -from .hosting.access import reseller_for_user +from .hosting.access import is_tenant class CoulobreAdminSite(AdminSite): def has_permission(self, request): - return ( - super().has_permission(request) and reseller_for_user(request.user) is None - ) + return super().has_permission(request) and not is_tenant(request.user) class CoulobreAdminConfig(AdminConfig): diff --git a/src/coulobre/hosting/access.py b/src/coulobre/hosting/access.py index 05b7d51..e585e32 100644 --- a/src/coulobre/hosting/access.py +++ b/src/coulobre/hosting/access.py @@ -1,30 +1,58 @@ -def reseller_for_user(user): +def customer_for_user(user): if not user.is_authenticated or user.is_superuser: return None + return getattr(user, "hosting_customer", None) + + +def reseller_for_user(user): + if ( + not user.is_authenticated + or user.is_superuser + or customer_for_user(user) is not None + ): + return None return getattr(user, "hosting_reseller", None) +def is_tenant(user): + return customer_for_user(user) is not None or reseller_for_user(user) is not None + + def panel_access(request): - return {"is_reseller": reseller_for_user(request.user) is not None} + customer = customer_for_user(request.user) is not None + reseller = not customer and reseller_for_user(request.user) is not None + return { + "is_reseller": reseller, + "is_tenant": customer or reseller, + "is_operator": request.user.is_authenticated and not (customer or reseller), + } class OperatorOnlyMixin: def dispatch(self, request, *args, **kwargs): - if reseller_for_user(request.user) is not None: + if is_tenant(request.user): return self.handle_no_permission() return super().dispatch(request, *args, **kwargs) -class ResellerScopeMixin: +class TenantScopeMixin: reseller_relation = "reseller" + customer_relation = None def has_permission(self): + if customer_for_user(self.request.user) is not None: + return self.customer_relation is not None return ( reseller_for_user(self.request.user) is not None or super().has_permission() ) def get_queryset(self): queryset = super().get_queryset() + customer = customer_for_user(self.request.user) + if customer is not None: + if self.customer_relation is None: + return queryset.none() + return queryset.filter(**{f"{self.customer_relation}_id": customer.pk}) reseller = reseller_for_user(self.request.user) if reseller is not None: return queryset.filter(**{f"{self.reseller_relation}_id": reseller.pk}) diff --git a/src/coulobre/hosting/admin.py b/src/coulobre/hosting/admin.py index 43439ae..c1ec0a8 100644 --- a/src/coulobre/hosting/admin.py +++ b/src/coulobre/hosting/admin.py @@ -1,7 +1,7 @@ from django.contrib import admin from django.utils.html import format_html -from .models import HostingAccount, HostingPlan, Reseller, WebProvisioningPlan +from .models import Customer, HostingAccount, HostingPlan, Reseller, WebProvisioningPlan @admin.register(HostingAccount) @@ -17,6 +17,8 @@ class HostingAccountAdmin(admin.ModelAdmin): excluded.append("hosting_plan") if not request.user.has_perm("hosting.view_reseller"): excluded.append("reseller") + if not request.user.has_perm("hosting.view_customer"): + excluded.append("customer") return excluded def save_model(self, request, obj, form, change): @@ -54,6 +56,13 @@ class ResellerAdmin(admin.ModelAdmin): return excluded +@admin.register(Customer) +class CustomerAdmin(admin.ModelAdmin): + list_display = ("user",) + list_select_related = ("user",) + search_fields = ("user__username",) + + @admin.register(WebProvisioningPlan) class WebProvisioningPlanAdmin(admin.ModelAdmin): list_display = ("primary_domain", "account", "requested_at", "completed_at") diff --git a/src/coulobre/hosting/migrations/0011_customer_access.py b/src/coulobre/hosting/migrations/0011_customer_access.py new file mode 100644 index 0000000..fd52772 --- /dev/null +++ b/src/coulobre/hosting/migrations/0011_customer_access.py @@ -0,0 +1,65 @@ +# Generated by Django 5.2.19 on 2026-11-20 23:20 + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0010_directadminimport"), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.AlterField( + model_name="reseller", + name="user", + field=models.OneToOneField( + limit_choices_to={ + "hosting_customer__isnull": True, + "is_superuser": False, + }, + on_delete=django.db.models.deletion.PROTECT, + related_name="hosting_reseller", + to=settings.AUTH_USER_MODEL, + ), + ), + migrations.CreateModel( + name="Customer", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ( + "user", + models.OneToOneField( + limit_choices_to={ + "hosting_reseller__isnull": True, + "is_staff": False, + "is_superuser": False, + }, + on_delete=django.db.models.deletion.PROTECT, + related_name="hosting_customer", + to=settings.AUTH_USER_MODEL, + ), + ), + ], + ), + migrations.AddField( + model_name="hostingaccount", + name="customer", + field=models.ForeignKey( + blank=True, + null=True, + on_delete=django.db.models.deletion.PROTECT, + to="hosting.customer", + ), + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 75add91..671fce9 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -21,7 +21,7 @@ class Reseller(models.Model): settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="hosting_reseller", - limit_choices_to={"is_superuser": False}, + limit_choices_to={"is_superuser": False, "hosting_customer__isnull": True}, ) account_limit = models.PositiveIntegerField(default=0) hosting_plans = models.ManyToManyField("HostingPlan", blank=True) @@ -33,6 +33,22 @@ class Reseller(models.Model): return self.user.get_username() +class Customer(models.Model): + user = models.OneToOneField( + settings.AUTH_USER_MODEL, + on_delete=models.PROTECT, + related_name="hosting_customer", + limit_choices_to={ + "is_staff": False, + "is_superuser": False, + "hosting_reseller__isnull": True, + }, + ) + + def __str__(self): + return self.user.get_username() + + class HostingPlan(models.Model): name = models.CharField(max_length=120, unique=True) description = models.CharField(max_length=240, blank=True) @@ -53,6 +69,9 @@ class HostingAccount(models.Model): reseller = models.ForeignKey( Reseller, on_delete=models.PROTECT, null=True, blank=True ) + customer = models.ForeignKey( + Customer, on_delete=models.PROTECT, null=True, blank=True + ) created_at = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index 3ee9cf2..a5adee4 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -7,25 +7,28 @@

{{ account.name }}

{{ account.primary_domain }}

- {% if not is_reseller and perms.hosting.change_hostingaccount %} + {% if is_operator and perms.hosting.change_hostingaccount %} Edit account {% endif %}
Primary domain
{{ account.primary_domain }}
- {% if is_reseller or perms.hosting.view_hostingplan %} + {% if is_tenant or perms.hosting.view_hostingplan %}
Hosting plan
{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}Unassigned{% endif %}
{% endif %} - {% if not is_reseller and perms.hosting.view_reseller %} + {% if is_operator and perms.hosting.view_reseller %}
Reseller
{{ account.reseller|default_if_none:"Unassigned" }}
{% endif %} + {% if is_operator and perms.hosting.view_customer %} +
Customer
{{ account.customer|default_if_none:"Unassigned" }}
+ {% endif %}
Added
{{ account.created_at|date:"j M Y, H:i" }} UTC
- {% if is_reseller or perms.hosting.view_webprovisioningplan %} + {% if is_reseller or is_operator and perms.hosting.view_webprovisioningplan %}

Recent Apache previews

- {% if not is_reseller and perms.hosting.change_hostingaccount %} + {% if is_operator and perms.hosting.change_hostingaccount %}
{% csrf_token %} @@ -35,23 +38,23 @@ {% include "hosting/plan_table.html" %}
{% endif %} - {% if is_reseller or perms.hosting.view_hostingdatabase %} + {% if is_tenant or perms.hosting.view_hostingdatabase %}

MariaDB database requests

- {% if not is_reseller and perms.hosting.add_hostingdatabase %} + {% if is_operator and perms.hosting.add_hostingdatabase %} Request database {% endif %}
{% if databases %}
- {% if not is_reseller %}{% endif %} + {% if is_operator %}{% endif %} {% for database in databases %} - {% if not is_reseller %} + {% if is_operator %} {% endif %} @@ -64,11 +67,11 @@ {% endif %} {% endif %} - {% if is_reseller or perms.hosting.view_hostingdnszone %} + {% if is_tenant or perms.hosting.view_hostingdnszone %}

DNS zones

- {% if not is_reseller and perms.hosting.add_hostingdnszone and not has_primary_zone %} + {% if is_operator and perms.hosting.add_hostingdnszone and not has_primary_zone %} Add DNS zone {% endif %}
@@ -79,21 +82,21 @@
- {% if not is_reseller %}{% endif %} + {% if is_operator %}{% endif %} {% for zone in dns_zones %} - {% if not is_reseller %} + {% if is_operator %} {% endif %} @@ -106,11 +109,11 @@ {% endif %} {% endif %} - {% if is_reseller or perms.hosting.view_hostingmailbox %} + {% if is_tenant or perms.hosting.view_hostingmailbox %}

Mailbox requests

- {% if not is_reseller and perms.hosting.add_hostingmailbox %} + {% if is_operator and perms.hosting.add_hostingmailbox %} Request mailbox {% endif %}
@@ -120,14 +123,14 @@
- {% if not is_reseller %}{% endif %} + {% if is_operator %}{% endif %} {% for mailbox in mailboxes %} - {% if not is_reseller %} + {% if is_operator %} {% endif %} diff --git a/src/coulobre/hosting/templates/hosting/account_list.html b/src/coulobre/hosting/templates/hosting/account_list.html index ba3a507..669bcc0 100644 --- a/src/coulobre/hosting/templates/hosting/account_list.html +++ b/src/coulobre/hosting/templates/hosting/account_list.html @@ -7,7 +7,7 @@

{{ paginator.count }} account{{ paginator.count|pluralize }}{% if search %} matching your search{% endif %}

{% if account_allowance %}

{{ account_allowance.used }} of {{ account_allowance.limit }} accounts allocated

{% endif %} - {% if account_allowance and account_allowance.used < account_allowance.limit or not is_reseller and perms.hosting.add_hostingaccount %} + {% if account_allowance and account_allowance.used < account_allowance.limit or is_operator and perms.hosting.add_hostingaccount %} Add hosting account {% endif %} @@ -25,7 +25,7 @@ - {% if is_reseller or perms.hosting.view_hostingplan %}{% endif %} + {% if is_tenant or perms.hosting.view_hostingplan %}{% endif %} @@ -34,7 +34,7 @@ - {% if is_reseller or perms.hosting.view_hostingplan %} + {% if is_tenant or perms.hosting.view_hostingplan %} {% endif %} diff --git a/src/coulobre/hosting/templates/hosting/base.html b/src/coulobre/hosting/templates/hosting/base.html index efde25d..b44bfae 100644 --- a/src/coulobre/hosting/templates/hosting/base.html +++ b/src/coulobre/hosting/templates/hosting/base.html @@ -17,19 +17,19 @@
DatabaseDeployment
DatabaseDeployment
{{ database }}Download manifest
Domain SOA serialDeploymentDeployment
- {% if not is_reseller and perms.hosting.change_hostingdnszone %} + {% if is_operator and perms.hosting.change_hostingdnszone %} {{ zone.domain }} {% else %} {{ zone.domain }} {% endif %} {{ zone.serial }}Download manifest
Email addressDeploymentDeployment
{{ mailbox }}Download manifest
Account Primary domainHosting planHosting planAdded
{{ account.name }} {{ account.primary_domain }}{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}Unassigned{% endif %}{{ account.created_at|date:"j M Y" }}
+ + + + + {% 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",) -- 2.43.0 From cba291d4a976315a74b96c8eb34978b453bc3d08 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 00:34:37 +0100 Subject: [PATCH 3/4] Enforce per-account database and mailbox quotas --- README.md | 2 + docs/development.md | 11 ++++ src/coulobre/hosting/admin.py | 8 ++- .../migrations/0012_hosting_plan_quotas.py | 30 ++++++++++ src/coulobre/hosting/models.py | 10 ++++ src/coulobre/hosting/resource_requests.py | 60 +++++++++++++++++++ .../templates/hosting/account_detail.html | 18 +++++- .../templates/hosting/hosting_plan_list.html | 11 +++- src/coulobre/hosting/test_databases.py | 33 +++++++++- src/coulobre/hosting/test_hosting_plans.py | 30 +++++++++- src/coulobre/hosting/test_mailboxes.py | 43 ++++++++++++- src/coulobre/hosting/views.py | 52 +++++++--------- 12 files changed, 268 insertions(+), 40 deletions(-) create mode 100644 src/coulobre/hosting/migrations/0012_hosting_plan_quotas.py create mode 100644 src/coulobre/hosting/resource_requests.py diff --git a/README.md b/README.md index 835a4a8..9ef27ed 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,8 @@ See [Local development](docs/development.md) to run it. - Self-hosted installation on a single Ubuntu server, with Debian support planned. - Hosting plans and self-service access for administrators, resellers, and customers. +- Customer impersonation for administrator support, with a dedicated permission, + a visible session indicator, and an audit trail. - Domains, TLS certificates, SFTP, and databases using Apache, PHP-FPM, and MariaDB. - Mail and DNS on the hosting server or on separate servers. - Account backups, restore, and migration from DirectAdmin. diff --git a/docs/development.md b/docs/development.md index de995f5..a1254ca 100644 --- a/docs/development.md +++ b/docs/development.md @@ -23,6 +23,17 @@ Use **Hosting plans** to add named plans with an optional description. Choose a plan when creating or editing an account. Existing accounts start unassigned. Operators need permission to view hosting plans before they can assign one. +Set a database limit and a mailbox limit on a hosting plan to cap how many +requests each assigned account can make through the panel. A blank limit allows +unlimited requests. Zero blocks new requests of that type. Accounts without a +plan have unlimited requests. The account page shows usage for configured +limits. Mailboxes count toward the same limit across all of an account's mail +domains, including domains retained after a primary domain change. + +Changing or reassigning a plan preserves existing databases and mailboxes. If +the new limit is at or below current usage, the panel blocks additional +requests of that type. + ## Give a reseller access to assigned accounts In `/admin/`, create a normal user and add a **Reseller** record for that user. diff --git a/src/coulobre/hosting/admin.py b/src/coulobre/hosting/admin.py index c1ec0a8..e85e797 100644 --- a/src/coulobre/hosting/admin.py +++ b/src/coulobre/hosting/admin.py @@ -38,9 +38,15 @@ class HostingAccountAdmin(admin.ModelAdmin): @admin.register(HostingPlan) class HostingPlanAdmin(admin.ModelAdmin): - list_display = ("name", "description") + list_display = ("name", "description", "database_limit", "mailbox_limit") search_fields = ("name",) + def save_model(self, request, obj, form, change): + if change: + obj.save(update_fields=form.changed_data) + else: + super().save_model(request, obj, form, change) + @admin.register(Reseller) class ResellerAdmin(admin.ModelAdmin): diff --git a/src/coulobre/hosting/migrations/0012_hosting_plan_quotas.py b/src/coulobre/hosting/migrations/0012_hosting_plan_quotas.py new file mode 100644 index 0000000..f23b1c7 --- /dev/null +++ b/src/coulobre/hosting/migrations/0012_hosting_plan_quotas.py @@ -0,0 +1,30 @@ +# Generated by Django 5.2.19 on 2026-11-20 23:31 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0011_customer_access"), + ] + + operations = [ + migrations.AddField( + model_name="hostingplan", + name="database_limit", + field=models.PositiveIntegerField( + blank=True, + help_text="Leave blank for unlimited. Enter 0 to block new database requests.", + null=True, + ), + ), + migrations.AddField( + model_name="hostingplan", + name="mailbox_limit", + field=models.PositiveIntegerField( + blank=True, + help_text="Leave blank for unlimited. Enter 0 to block new mailbox requests.", + null=True, + ), + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 671fce9..cd8270c 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -52,6 +52,16 @@ class Customer(models.Model): class HostingPlan(models.Model): name = models.CharField(max_length=120, unique=True) description = models.CharField(max_length=240, blank=True) + database_limit = models.PositiveIntegerField( + blank=True, + null=True, + help_text="Leave blank for unlimited. Enter 0 to block new database requests.", + ) + mailbox_limit = models.PositiveIntegerField( + blank=True, + null=True, + help_text="Leave blank for unlimited. Enter 0 to block new mailbox requests.", + ) class Meta: ordering = ("name", "pk") diff --git a/src/coulobre/hosting/resource_requests.py b/src/coulobre/hosting/resource_requests.py new file mode 100644 index 0000000..b6944fe --- /dev/null +++ b/src/coulobre/hosting/resource_requests.py @@ -0,0 +1,60 @@ +from django.core.exceptions import ValidationError +from django.db import connection, transaction +from django.db.models import F + +from coulobre.mail_node import MailboxSpec + +from .models import HostingAccount, HostingMailbox, HostingMailDomain + + +def lock_hosting_account(account_id): + accounts = HostingAccount.objects.filter(pk=account_id) + if connection.vendor == "sqlite": + # Acquire the write lock before reading the account and resource counts. + accounts.update(hosting_plan=F("hosting_plan")) + return accounts.select_for_update().get() + + +@transaction.atomic +def create_database_request(account_id, suffix): + account = lock_hosting_account(account_id) + databases = account.databases + if databases.filter(suffix=suffix).exists(): + raise ValidationError( + {"suffix": "This account already has a database with that suffix."} + ) + + plan = account.hosting_plan + if ( + plan + and plan.database_limit is not None + and databases.count() >= plan.database_limit + ): + raise ValidationError("This hosting account has reached its database limit.") + return databases.create(suffix=suffix) + + +@transaction.atomic +def create_mailbox_request(account_id, local_part): + account = lock_hosting_account(account_id) + try: + spec = MailboxSpec(account.primary_domain, local_part) + except ValueError as error: + raise ValidationError({"local_part": str(error)}) from error + + mail_domain, _ = HostingMailDomain.objects.get_or_create( + domain=spec.domain, defaults={"account": account} + ) + if mail_domain.account_id != account.pk: + raise ValidationError("This mail domain belongs to another hosting account.") + if mail_domain.mailboxes.filter(local_part=spec.local_part).exists(): + raise ValidationError( + {"local_part": "This mailbox has already been requested."} + ) + + plan = account.hosting_plan + if plan and plan.mailbox_limit is not None: + mailboxes = HostingMailbox.objects.filter(mail_domain__account=account) + if mailboxes.count() >= plan.mailbox_limit: + raise ValidationError("This hosting account has reached its mailbox limit.") + return mail_domain.mailboxes.create(local_part=spec.local_part) diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index a5adee4..84e8853 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -41,7 +41,14 @@ {% if is_tenant or perms.hosting.view_hostingdatabase %}
-

MariaDB database requests

+
+

MariaDB database requests

+ {% if is_tenant or perms.hosting.view_hostingplan %} + {% if account.hosting_plan and account.hosting_plan.database_limit is not None %} +

{{ databases|length }} of {{ account.hosting_plan.database_limit }} databases requested

+ {% endif %} + {% endif %} +
{% if is_operator and perms.hosting.add_hostingdatabase %} Request database {% endif %} @@ -112,7 +119,14 @@ {% if is_tenant or perms.hosting.view_hostingmailbox %}
-

Mailbox requests

+
+

Mailbox requests

+ {% if is_tenant or perms.hosting.view_hostingplan %} + {% if account.hosting_plan and account.hosting_plan.mailbox_limit is not None %} +

{{ mailboxes|length }} of {{ account.hosting_plan.mailbox_limit }} mailboxes requested

+ {% endif %} + {% endif %} +
{% if is_operator and perms.hosting.add_hostingmailbox %} Request mailbox {% endif %} diff --git a/src/coulobre/hosting/templates/hosting/hosting_plan_list.html b/src/coulobre/hosting/templates/hosting/hosting_plan_list.html index da1a082..9bf7016 100644 --- a/src/coulobre/hosting/templates/hosting/hosting_plan_list.html +++ b/src/coulobre/hosting/templates/hosting/hosting_plan_list.html @@ -11,7 +11,14 @@ {% if hosting_plans %}
- + + + + + + + + {% for hosting_plan in hosting_plans %} @@ -23,6 +30,8 @@ {% endif %} + + {% endfor %} diff --git a/src/coulobre/hosting/test_databases.py b/src/coulobre/hosting/test_databases.py index 011c7fe..07b9b11 100644 --- a/src/coulobre/hosting/test_databases.py +++ b/src/coulobre/hosting/test_databases.py @@ -5,7 +5,7 @@ from django.urls import reverse from coulobre.database_node import DatabaseSpec -from .models import HostingAccount, HostingDatabase, Reseller +from .models import HostingAccount, HostingDatabase, HostingPlan, Reseller class DatabaseRequestTests(TestCase): @@ -74,6 +74,37 @@ class DatabaseRequestTests(TestCase): self.assertIn("suffix", response.context["form"].errors) self.assertFalse(HostingDatabase.objects.exists()) + def test_database_limit_is_per_account_and_uses_the_current_plan(self): + plan = HostingPlan.objects.create(name="Starter", database_limit=1) + HostingAccount.objects.update(hosting_plan=plan) + self.assertRedirects( + self.client.post(self.request_url, {"suffix": "cms"}), + self.account.get_absolute_url(), + ) + capped = self.client.post(self.request_url, {"suffix": "shop"}) + self.assertContains( + capped, "This hosting account has reached its database limit." + ) + + other_url = reverse("panel:database_create", args=[self.other_account.pk]) + self.assertRedirects( + self.client.post(other_url, {"suffix": "cms"}), + self.other_account.get_absolute_url(), + ) + zero = HostingPlan.objects.create(name="No databases", database_limit=0) + HostingAccount.objects.filter(pk=self.account.pk).update(hosting_plan=zero) + self.assertContains( + self.client.get(self.account.get_absolute_url()), + "1 of 0 databases requested", + ) + capped = self.client.post(self.request_url, {"suffix": "shop"}) + self.assertContains( + capped, "This hosting account has reached its database limit." + ) + self.assertEqual( + list(self.account.databases.values_list("suffix", flat=True)), ["cms"] + ) + def test_reseller_view_is_scoped_and_node_actions_require_an_operator(self): owned = HostingDatabase.objects.create(account=self.account, suffix="wordpress") HostingDatabase.objects.create(account=self.other_account, suffix="othersite") diff --git a/src/coulobre/hosting/test_hosting_plans.py b/src/coulobre/hosting/test_hosting_plans.py index 7a3e745..80ea446 100644 --- a/src/coulobre/hosting/test_hosting_plans.py +++ b/src/coulobre/hosting/test_hosting_plans.py @@ -30,10 +30,17 @@ class HostingPlanTests(TestCase): list_url = reverse("panel:hosting_plans") response = self.client.post( reverse("panel:hosting_plan_create"), - {"name": "Starter", "description": "Shared hosting for small sites"}, + { + "name": "Starter", + "description": "Shared hosting for small sites", + "database_limit": 0, + "mailbox_limit": 5, + }, ) self.assertRedirects(response, list_url) plan = HostingPlan.objects.get() + self.assertEqual(plan.database_limit, 0) + self.assertEqual(plan.mailbox_limit, 5) self.assertContains( self.client.get(self.account.get_absolute_url()), "Unassigned" @@ -52,9 +59,18 @@ class HostingPlanTests(TestCase): response = self.client.post( reverse("panel:hosting_plan_edit", args=[plan.pk]), - {"name": "Standard", "description": "Updated description"}, + { + "name": "Standard", + "description": "Updated description", + "database_limit": "", + "mailbox_limit": 2, + }, ) self.assertRedirects(response, list_url) + plan.refresh_from_db() + self.assertIsNone(plan.database_limit) + self.assertEqual(plan.mailbox_limit, 2) + self.assertContains(self.client.get(list_url), "Unlimited") self.assertContains(self.client.get(reverse("panel:accounts")), "Standard") response = self.client.post( @@ -69,6 +85,16 @@ class HostingPlanTests(TestCase): self.assertRedirects(response, new_account.get_absolute_url()) self.assertEqual(new_account.hosting_plan_id, plan.pk) + def test_plan_rejects_negative_limits(self): + self.client.force_login(self.operator) + response = self.client.post( + reverse("panel:hosting_plan_create"), + {"name": "Invalid plan", "database_limit": -1, "mailbox_limit": -2}, + ) + self.assertIn("database_limit", response.context["form"].errors) + self.assertIn("mailbox_limit", response.context["form"].errors) + self.assertFalse(HostingPlan.objects.exists()) + def test_editor_without_plan_permission_cannot_assign_in_either_interface(self): current = HostingPlan.objects.create(name="Private plan") other = HostingPlan.objects.create(name="Other plan") diff --git a/src/coulobre/hosting/test_mailboxes.py b/src/coulobre/hosting/test_mailboxes.py index 7ac8fa1..2dd2915 100644 --- a/src/coulobre/hosting/test_mailboxes.py +++ b/src/coulobre/hosting/test_mailboxes.py @@ -10,7 +10,13 @@ from django.urls import reverse from coulobre.mail_node import MailboxSpec, main -from .models import HostingAccount, HostingMailbox, HostingMailDomain, Reseller +from .models import ( + HostingAccount, + HostingMailbox, + HostingMailDomain, + HostingPlan, + Reseller, +) class MailboxRequestTests(TestCase): @@ -79,6 +85,41 @@ class MailboxRequestTests(TestCase): self.assertIn("local_part", response.context["form"].errors) self.assertFalse(HostingMailDomain.objects.exists()) + def test_mailbox_quota_counts_old_domains_and_preserves_existing_requests(self): + plan = HostingPlan.objects.create(name="Solo mail", mailbox_limit=1) + HostingAccount.objects.filter(pk=self.account.pk).update(hosting_plan=plan) + original = self.request_mailbox("support") + response = self.client.post( + reverse("panel:account_edit", args=[self.account.pk]), + { + "name": self.account.name, + "primary_domain": "new.example", + "hosting_plan": plan.pk, + }, + ) + self.assertRedirects(response, self.account.get_absolute_url()) + self.assertContains( + self.client.get(self.account.get_absolute_url()), + "1 of 1 mailboxes requested", + ) + capped = self.client.post(self.request_url, {"local_part": "billing"}) + self.assertContains( + capped, "This hosting account has reached its mailbox limit." + ) + self.assertEqual(HostingMailbox.objects.get(), original) + self.assertFalse( + HostingMailDomain.objects.filter(domain="new.example").exists() + ) + + HostingPlan.objects.filter(pk=plan.pk).update(mailbox_limit=2) + self.assertRedirects( + self.client.post(self.request_url, {"local_part": "billing"}), + self.account.get_absolute_url(), + ) + self.assertEqual( + HostingMailbox.objects.get(local_part="billing").spec.domain, "new.example" + ) + def test_renamed_account_keeps_existing_mail_and_prevents_domain_reassignment(self): original = self.request_mailbox("support") mail_domain = original.mail_domain.domain diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 8b3d08a..897f05a 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -15,7 +15,7 @@ from django.views.generic import CreateView, DetailView, FormView, ListView, Upd from django.views.generic.detail import SingleObjectMixin from coulobre.dns_node import MAX_SOA_SERIAL -from coulobre.mail_node import INVALID_LOCAL_PART, MailboxSpec +from coulobre.mail_node import INVALID_LOCAL_PART from .access import ( OperatorOnlyMixin, @@ -30,12 +30,12 @@ from .models import ( HostingDatabase, HostingDnsZone, HostingMailbox, - HostingMailDomain, HostingPlan, Reseller, WebProvisioningPlan, ) from .reseller_accounts import create_reseller_account +from .resource_requests import create_database_request, create_mailbox_request from .web_node import build_web_smoke_bundle, serialize_deployment_manifest VIEW_ACCOUNTS = "hosting.view_hostingaccount" @@ -277,17 +277,14 @@ class DatabaseCreate(OperatorOnlyMixin, PermissionRequiredMixin, CreateView): return super().get_context_data(account=self.account, **kwargs) def form_valid(self, form): - self.object = form.save(commit=False) - self.object.account = self.account try: - with transaction.atomic(): - self.object.save() - except IntegrityError: - if not self.account.databases.filter(suffix=self.object.suffix).exists(): - raise - form.add_error( - "suffix", "This account already has a database with that suffix." + self.object = create_database_request( + self.account.pk, form.cleaned_data["suffix"] ) + except HostingAccount.DoesNotExist as error: + raise Http404 from error + except ValidationError as error: + form.add_error(None, error) return self.form_invalid(form) return redirect(self.account) @@ -445,27 +442,13 @@ class MailboxCreate(OperatorOnlyMixin, PermissionRequiredMixin, CreateView): def form_valid(self, form): try: - spec = MailboxSpec( - self.account.primary_domain, form.cleaned_data["local_part"] + self.object = create_mailbox_request( + self.account.pk, form.cleaned_data["local_part"] ) - except ValueError as error: - form.add_error("local_part", str(error)) - return self.form_invalid(form) - - with transaction.atomic(): - mail_domain, _ = HostingMailDomain.objects.get_or_create( - domain=spec.domain, defaults={"account": self.account} - ) - if mail_domain.account_id != self.account.pk: - form.add_error( - None, "This mail domain belongs to another hosting account." - ) - return self.form_invalid(form) - self.object, created = HostingMailbox.objects.get_or_create( - mail_domain=mail_domain, local_part=spec.local_part - ) - if not created: - form.add_error("local_part", "This mailbox has already been requested.") + except HostingAccount.DoesNotExist as error: + raise Http404 from error + except ValidationError as error: + form.add_error(None, error) return self.form_invalid(form) return redirect(self.account) @@ -496,7 +479,7 @@ class HostingPlanList(OperatorOnlyMixin, PermissionRequiredMixin, ListView): class HostingPlanEditor: model = HostingPlan - fields = ("name", "description") + fields = ("name", "description", "database_limit", "mailbox_limit") template_name = "hosting/hosting_plan_form.html" success_url = reverse_lazy("panel:hosting_plans") @@ -514,6 +497,11 @@ class HostingPlanEdit( permission_required = (VIEW_HOSTING_PLANS, "hosting.change_hostingplan") extra_context = {"page_title": "Edit hosting plan", "submit_label": "Save changes"} + def form_valid(self, form): + self.object = form.save(commit=False) + self.object.save(update_fields=form.changed_data) + return redirect(self.get_success_url()) + class RequestWebPlan( OperatorOnlyMixin, PermissionRequiredMixin, SingleObjectMixin, View -- 2.43.0 From 1424206903e2f9dab92bc763f4eddef219cbd2da Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 00:43:04 +0100 Subject: [PATCH 4/4] Allow customers to request databases and mailboxes within plan quotas --- docs/development.md | 3 +- src/coulobre/hosting/access.py | 1 + src/coulobre/hosting/resource_requests.py | 12 +-- .../templates/hosting/account_detail.html | 4 +- src/coulobre/hosting/test_customers.py | 79 ++++++++++++++++++- src/coulobre/hosting/views.py | 55 +++++++------ 6 files changed, 114 insertions(+), 40 deletions(-) diff --git a/docs/development.md b/docs/development.md index a1254ca..5cbddee 100644 --- a/docs/development.md +++ b/docs/development.md @@ -67,7 +67,8 @@ should be able to access. To give an existing user customer access, add a 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. +requests. Customers can request databases and mailboxes for their own accounts +within their plan limits. Operators deploy those requests on the hosting nodes. 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 diff --git a/src/coulobre/hosting/access.py b/src/coulobre/hosting/access.py index e585e32..3145f11 100644 --- a/src/coulobre/hosting/access.py +++ b/src/coulobre/hosting/access.py @@ -22,6 +22,7 @@ def panel_access(request): customer = customer_for_user(request.user) is not None reseller = not customer and reseller_for_user(request.user) is not None return { + "is_customer": customer, "is_reseller": reseller, "is_tenant": customer or reseller, "is_operator": request.user.is_authenticated and not (customer or reseller), diff --git a/src/coulobre/hosting/resource_requests.py b/src/coulobre/hosting/resource_requests.py index b6944fe..b29f83e 100644 --- a/src/coulobre/hosting/resource_requests.py +++ b/src/coulobre/hosting/resource_requests.py @@ -7,8 +7,10 @@ from coulobre.mail_node import MailboxSpec from .models import HostingAccount, HostingMailbox, HostingMailDomain -def lock_hosting_account(account_id): +def lock_hosting_account(account_id, customer_id): accounts = HostingAccount.objects.filter(pk=account_id) + if customer_id is not None: + accounts = accounts.filter(customer_id=customer_id) if connection.vendor == "sqlite": # Acquire the write lock before reading the account and resource counts. accounts.update(hosting_plan=F("hosting_plan")) @@ -16,8 +18,8 @@ def lock_hosting_account(account_id): @transaction.atomic -def create_database_request(account_id, suffix): - account = lock_hosting_account(account_id) +def create_database_request(account_id, suffix, *, customer_id=None): + account = lock_hosting_account(account_id, customer_id) databases = account.databases if databases.filter(suffix=suffix).exists(): raise ValidationError( @@ -35,8 +37,8 @@ def create_database_request(account_id, suffix): @transaction.atomic -def create_mailbox_request(account_id, local_part): - account = lock_hosting_account(account_id) +def create_mailbox_request(account_id, local_part, *, customer_id=None): + account = lock_hosting_account(account_id, customer_id) try: spec = MailboxSpec(account.primary_domain, local_part) except ValueError as error: diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index 84e8853..d858710 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -49,7 +49,7 @@ {% endif %} {% endif %} - {% if is_operator and perms.hosting.add_hostingdatabase %} + {% if is_customer or is_operator and perms.hosting.add_hostingdatabase %} Request database {% endif %} @@ -127,7 +127,7 @@ {% endif %} {% endif %} - {% if is_operator and perms.hosting.add_hostingmailbox %} + {% if is_customer or is_operator and perms.hosting.add_hostingmailbox %} Request mailbox {% endif %} diff --git a/src/coulobre/hosting/test_customers.py b/src/coulobre/hosting/test_customers.py index 86c257a..7ff9e96 100644 --- a/src/coulobre/hosting/test_customers.py +++ b/src/coulobre/hosting/test_customers.py @@ -1,3 +1,5 @@ +from unittest.mock import patch + from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.test import TestCase @@ -14,6 +16,8 @@ from .models import ( Reseller, WebProvisioningPlan, ) +from .resource_requests import create_database_request +from .views import DatabaseCreate class CustomerAccessTests(TestCase): @@ -113,8 +117,6 @@ class CustomerAccessTests(TestCase): for label in ( "Edit account", "Recent Apache previews", - "Request database", - "Request mailbox", "Download manifest", ): self.assertNotContains(detail, label) @@ -138,10 +140,8 @@ class CustomerAccessTests(TestCase): ("panel:account_create", ()), ("panel:account_edit", (self.account.pk,)), ("panel:request_plan", (self.account.pk,)), - ("panel:database_create", (self.account.pk,)), ("panel:dns_zone_create", (self.account.pk,)), ("panel:dns_zone_edit", (self.zone.pk,)), - ("panel:mailbox_create", (self.account.pk,)), ): with self.subTest(route=route): self.assertEqual( @@ -153,6 +153,77 @@ class CustomerAccessTests(TestCase): self.client.get(admin_url), f"{reverse('admin:login')}?next={admin_url}" ) + def test_customer_can_request_databases_and_mailboxes_up_to_the_plan_limits(self): + HostingPlan.objects.filter(pk=self.package.pk).update( + database_limit=2, mailbox_limit=2 + ) + self.client.force_login(self.alice) + account_url = self.account.get_absolute_url() + detail = self.client.get(account_url) + self.assertContains(detail, "Request database") + self.assertContains(detail, "Request mailbox") + + database_url = reverse("panel:database_create", args=[self.account.pk]) + self.assertContains(self.client.get(database_url), "Request MariaDB database") + self.assertRedirects( + self.client.post(database_url, {"suffix": "shop"}), account_url + ) + self.assertContains( + self.client.post(database_url, {"suffix": "another"}), + "This hosting account has reached its database limit.", + ) + self.assertEqual(self.account.databases.count(), 2) + + mailbox_url = reverse("panel:mailbox_create", args=[self.account.pk]) + self.assertContains(self.client.get(mailbox_url), "Request mailbox") + self.assertRedirects( + self.client.post(mailbox_url, {"local_part": "Sales"}), account_url + ) + self.assertContains( + self.client.post(mailbox_url, {"local_part": "billing"}), + "This hosting account has reached its mailbox limit.", + ) + self.assertEqual( + HostingMailbox.objects.filter(mail_domain__account=self.account).count(), 2 + ) + self.assertContains(self.client.get(account_url), "sales@alice.example") + + def test_customer_cannot_open_or_submit_resource_forms_for_other_accounts(self): + self.alice.user_permissions.add( + *Permission.objects.filter(content_type__app_label="hosting") + ) + self.client.force_login(self.alice) + for account in (self.other_account, self.unassigned_account): + for route, data in ( + ("panel:database_create", {"suffix": "shop"}), + ("panel:mailbox_create", {"local_part": "sales"}), + ): + with self.subTest(account=account, route=route): + url = reverse(route, args=[account.pk]) + self.assertEqual(self.client.get(url).status_code, 404) + self.assertEqual(self.client.post(url, data).status_code, 404) + self.assertEqual(HostingDatabase.objects.count(), 1) + self.assertEqual(HostingMailbox.objects.count(), 1) + + def test_database_request_rechecks_customer_assignment_before_writing(self): + self.client.force_login(self.alice) + + def reassign_before_create(account_id, **kwargs): + HostingAccount.objects.filter(pk=account_id).update( + customer=self.other_customer + ) + return create_database_request(account_id, **kwargs) + + with patch.object( + DatabaseCreate, "create_request", side_effect=reassign_before_create + ): + response = self.client.post( + reverse("panel:database_create", args=[self.account.pk]), + {"suffix": "shop"}, + ) + self.assertEqual(response.status_code, 404) + self.assertFalse(self.account.databases.filter(suffix="shop").exists()) + def test_operator_can_create_customer_and_reassign_existing_account(self): user = get_user_model().objects.create_user("charlie") self.client.force_login(self.operator) diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 897f05a..260d8ac 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -263,23 +263,32 @@ class CustomerAccess(OperatorOnlyMixin, PermissionRequiredMixin, View): return redirect(reverse("panel:customers", query=request.GET)) -class DatabaseCreate(OperatorOnlyMixin, PermissionRequiredMixin, CreateView): - model = HostingDatabase - fields = ("suffix",) - template_name = "hosting/database_form.html" - permission_required = (VIEW_ACCOUNTS, VIEW_DATABASES, "hosting.add_hostingdatabase") +class ResourceRequestCreate(PermissionRequiredMixin, CreateView): + @cached_property + def customer(self): + return customer_for_user(self.request.user) + + def has_permission(self): + return self.customer is not None or ( + reseller_for_user(self.request.user) is None and super().has_permission() + ) @cached_property def account(self): - return get_object_or_404(HostingAccount, pk=self.kwargs["pk"]) + accounts = HostingAccount.objects.all() + if self.customer is not None: + accounts = accounts.filter(customer=self.customer) + return get_object_or_404(accounts, pk=self.kwargs["pk"]) def get_context_data(self, **kwargs): return super().get_context_data(account=self.account, **kwargs) def form_valid(self, form): try: - self.object = create_database_request( - self.account.pk, form.cleaned_data["suffix"] + self.object = self.create_request( + self.account.pk, + **form.cleaned_data, + customer_id=self.customer.pk if self.customer is not None else None, ) except HostingAccount.DoesNotExist as error: raise Http404 from error @@ -289,6 +298,14 @@ class DatabaseCreate(OperatorOnlyMixin, PermissionRequiredMixin, CreateView): return redirect(self.account) +class DatabaseCreate(ResourceRequestCreate): + model = HostingDatabase + fields = ("suffix",) + template_name = "hosting/database_form.html" + permission_required = (VIEW_ACCOUNTS, VIEW_DATABASES, "hosting.add_hostingdatabase") + create_request = staticmethod(create_database_request) + + class DownloadDatabaseManifest(OperatorOnlyMixin, PermissionRequiredMixin, View): permission_required = (VIEW_ACCOUNTS, VIEW_DATABASES) @@ -422,36 +439,18 @@ class DownloadDnsZoneManifest(OperatorOnlyMixin, PermissionRequiredMixin, View): ) -class MailboxCreate(OperatorOnlyMixin, PermissionRequiredMixin, CreateView): +class MailboxCreate(ResourceRequestCreate): model = HostingMailbox fields = ("local_part",) template_name = "hosting/mailbox_form.html" permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES, "hosting.add_hostingmailbox") - - @cached_property - def account(self): - return get_object_or_404(HostingAccount, pk=self.kwargs["pk"]) + create_request = staticmethod(create_mailbox_request) def get_form(self, form_class=None): form = super().get_form(form_class) form.fields["local_part"].help_text = INVALID_LOCAL_PART return form - def get_context_data(self, **kwargs): - return super().get_context_data(account=self.account, **kwargs) - - def form_valid(self, form): - try: - self.object = create_mailbox_request( - self.account.pk, form.cleaned_data["local_part"] - ) - except HostingAccount.DoesNotExist as error: - raise Http404 from error - except ValidationError as error: - form.add_error(None, error) - return self.form_invalid(form) - return redirect(self.account) - class DownloadMailboxManifest(OperatorOnlyMixin, PermissionRequiredMixin, View): permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES) -- 2.43.0
PlanDescription
PlanDescriptionDatabase limitMailbox limit
{{ hosting_plan.description|default:"—" }}{{ hosting_plan.database_limit|default_if_none:"Unlimited" }}{{ hosting_plan.mailbox_limit|default_if_none:"Unlimited" }}