Allow customers to request databases and mailboxes within plan quotas

This commit is contained in:
parkel committed 2026-11-21 00:43:04 +01:00
1 parent cba291d4a9
commit 1424206903
6 files changed
+114 -40

No files matched your search

+2 -1
View File
@@ -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. 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 Their account list shows only the hosting accounts assigned to them. Each
account page shows its hosting plan, database requests, DNS zones, and mailbox 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 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 customer across all their hosting accounts. Use **Restore sign-in** to give
+1
View File
@@ -22,6 +22,7 @@ def panel_access(request):
customer = customer_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 reseller = not customer and reseller_for_user(request.user) is not None
return { return {
"is_customer": customer,
"is_reseller": reseller, "is_reseller": reseller,
"is_tenant": customer or reseller, "is_tenant": customer or reseller,
"is_operator": request.user.is_authenticated and not (customer or reseller), "is_operator": request.user.is_authenticated and not (customer or reseller),
+7 -5
View File
@@ -7,8 +7,10 @@ from coulobre.mail_node import MailboxSpec
from .models import HostingAccount, HostingMailbox, HostingMailDomain 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) accounts = HostingAccount.objects.filter(pk=account_id)
if customer_id is not None:
accounts = accounts.filter(customer_id=customer_id)
if connection.vendor == "sqlite": if connection.vendor == "sqlite":
# Acquire the write lock before reading the account and resource counts. # Acquire the write lock before reading the account and resource counts.
accounts.update(hosting_plan=F("hosting_plan")) accounts.update(hosting_plan=F("hosting_plan"))
@@ -16,8 +18,8 @@ def lock_hosting_account(account_id):
@transaction.atomic @transaction.atomic
def create_database_request(account_id, suffix): def create_database_request(account_id, suffix, *, customer_id=None):
account = lock_hosting_account(account_id) account = lock_hosting_account(account_id, customer_id)
databases = account.databases databases = account.databases
if databases.filter(suffix=suffix).exists(): if databases.filter(suffix=suffix).exists():
raise ValidationError( raise ValidationError(
@@ -35,8 +37,8 @@ def create_database_request(account_id, suffix):
@transaction.atomic @transaction.atomic
def create_mailbox_request(account_id, local_part): def create_mailbox_request(account_id, local_part, *, customer_id=None):
account = lock_hosting_account(account_id) account = lock_hosting_account(account_id, customer_id)
try: try:
spec = MailboxSpec(account.primary_domain, local_part) spec = MailboxSpec(account.primary_domain, local_part)
except ValueError as error: except ValueError as error:
@@ -49,7 +49,7 @@
{% endif %} {% endif %}
{% endif %} {% endif %}
</div> </div>
{% if is_operator and perms.hosting.add_hostingdatabase %} {% if is_customer or is_operator and perms.hosting.add_hostingdatabase %}
<a class="button primary" href="{% url 'panel:database_create' account.pk %}">Request database</a> <a class="button primary" href="{% url 'panel:database_create' account.pk %}">Request database</a>
{% endif %} {% endif %}
</header> </header>
@@ -127,7 +127,7 @@
{% endif %} {% endif %}
{% endif %} {% endif %}
</div> </div>
{% if is_operator and perms.hosting.add_hostingmailbox %} {% if is_customer or is_operator and perms.hosting.add_hostingmailbox %}
<a class="button primary" href="{% url 'panel:mailbox_create' account.pk %}">Request mailbox</a> <a class="button primary" href="{% url 'panel:mailbox_create' account.pk %}">Request mailbox</a>
{% endif %} {% endif %}
</header> </header>
+75 -4
View File
@@ -1,3 +1,5 @@
from unittest.mock import patch
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission from django.contrib.auth.models import Permission
from django.test import TestCase from django.test import TestCase
@@ -14,6 +16,8 @@ from .models import (
Reseller, Reseller,
WebProvisioningPlan, WebProvisioningPlan,
) )
from .resource_requests import create_database_request
from .views import DatabaseCreate
class CustomerAccessTests(TestCase): class CustomerAccessTests(TestCase):
@@ -113,8 +117,6 @@ class CustomerAccessTests(TestCase):
for label in ( for label in (
"Edit account", "Edit account",
"Recent Apache previews", "Recent Apache previews",
"Request database",
"Request mailbox",
"Download manifest", "Download manifest",
): ):
self.assertNotContains(detail, label) self.assertNotContains(detail, label)
@@ -138,10 +140,8 @@ class CustomerAccessTests(TestCase):
("panel:account_create", ()), ("panel:account_create", ()),
("panel:account_edit", (self.account.pk,)), ("panel:account_edit", (self.account.pk,)),
("panel:request_plan", (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_create", (self.account.pk,)),
("panel:dns_zone_edit", (self.zone.pk,)), ("panel:dns_zone_edit", (self.zone.pk,)),
("panel:mailbox_create", (self.account.pk,)),
): ):
with self.subTest(route=route): with self.subTest(route=route):
self.assertEqual( self.assertEqual(
@@ -153,6 +153,77 @@ class CustomerAccessTests(TestCase):
self.client.get(admin_url), f"{reverse('admin:login')}?next={admin_url}" 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): def test_operator_can_create_customer_and_reassign_existing_account(self):
user = get_user_model().objects.create_user("charlie") user = get_user_model().objects.create_user("charlie")
self.client.force_login(self.operator) self.client.force_login(self.operator)
+27 -28
View File
@@ -263,23 +263,32 @@ class CustomerAccess(OperatorOnlyMixin, PermissionRequiredMixin, View):
return redirect(reverse("panel:customers", query=request.GET)) return redirect(reverse("panel:customers", query=request.GET))
class DatabaseCreate(OperatorOnlyMixin, PermissionRequiredMixin, CreateView): class ResourceRequestCreate(PermissionRequiredMixin, CreateView):
model = HostingDatabase @cached_property
fields = ("suffix",) def customer(self):
template_name = "hosting/database_form.html" return customer_for_user(self.request.user)
permission_required = (VIEW_ACCOUNTS, VIEW_DATABASES, "hosting.add_hostingdatabase")
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 @cached_property
def account(self): 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): def get_context_data(self, **kwargs):
return super().get_context_data(account=self.account, **kwargs) return super().get_context_data(account=self.account, **kwargs)
def form_valid(self, form): def form_valid(self, form):
try: try:
self.object = create_database_request( self.object = self.create_request(
self.account.pk, form.cleaned_data["suffix"] self.account.pk,
**form.cleaned_data,
customer_id=self.customer.pk if self.customer is not None else None,
) )
except HostingAccount.DoesNotExist as error: except HostingAccount.DoesNotExist as error:
raise Http404 from error raise Http404 from error
@@ -289,6 +298,14 @@ class DatabaseCreate(OperatorOnlyMixin, PermissionRequiredMixin, CreateView):
return redirect(self.account) 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): class DownloadDatabaseManifest(OperatorOnlyMixin, PermissionRequiredMixin, View):
permission_required = (VIEW_ACCOUNTS, VIEW_DATABASES) 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 model = HostingMailbox
fields = ("local_part",) fields = ("local_part",)
template_name = "hosting/mailbox_form.html" template_name = "hosting/mailbox_form.html"
permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES, "hosting.add_hostingmailbox") permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES, "hosting.add_hostingmailbox")
create_request = staticmethod(create_mailbox_request)
@cached_property
def account(self):
return get_object_or_404(HostingAccount, pk=self.kwargs["pk"])
def get_form(self, form_class=None): def get_form(self, form_class=None):
form = super().get_form(form_class) form = super().get_form(form_class)
form.fields["local_part"].help_text = INVALID_LOCAL_PART form.fields["local_part"].help_text = INVALID_LOCAL_PART
return form 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): class DownloadMailboxManifest(OperatorOnlyMixin, PermissionRequiredMixin, View):
permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES) permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES)