Add a customer portal with hosting plan quotas #11

Merged
parkel merged 4 commits from feature/customer-portal into main 2026-11-21 00:43:36 +01:00
8 changed files with 355 additions and 8 deletions
Showing only changes of commit 22f1e24eed - Show all commits

No files matched your search

+14 -4
View File
@@ -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
+21 -2
View File
@@ -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;
}
@@ -23,6 +23,12 @@
Hosting accounts
</a>
{% endif %}
{% if is_operator and perms.hosting.view_customer %}
<a href="{% url 'panel:customers' %}"{% if current == 'customers' or current == 'customer_create' %} aria-current="page"{% endif %}>
<span class="nav-icon nav-icon-customers" aria-hidden="true"></span>
Customers
</a>
{% endif %}
{% if is_operator and perms.hosting.view_hostingplan %}
<a href="{% url 'panel:hosting_plans' %}"{% if current == 'hosting_plans' or current == 'hosting_plan_create' or current == 'hosting_plan_edit' %} aria-current="page"{% endif %}>
<span class="nav-icon nav-icon-packages" aria-hidden="true"></span>
@@ -0,0 +1,16 @@
{% extends "hosting/base.html" %}
{% block title %}Add customer · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{% url 'panel:customers' %}">← Customers</a>
<header class="page-heading"><h1>Add customer</h1></header>
<section class="surface editor-surface">
<form method="post" class="editor">
{% csrf_token %}
{{ form.as_div }}
<div class="form-actions">
<button class="button primary" type="submit">Add customer</button>
<a class="button secondary" href="{% url 'panel:customers' %}">Cancel</a>
</div>
</form>
</section>
{% endblock %}
@@ -0,0 +1,61 @@
{% extends "hosting/base.html" %}
{% block title %}Customers · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading">
<h1>Customers</h1>
{% if perms.hosting.add_customer %}
<a class="button primary" href="{% url 'panel:customer_create' %}">Add customer</a>
{% endif %}
</header>
<section class="surface" aria-label="Customer list">
<form class="toolbar" method="get" action="{% url 'panel:customers' %}" role="search">
<label class="visually-hidden" for="customer-search">Search customers by username</label>
<input type="search" id="customer-search" name="q" placeholder="Username" value="{{ search }}">
<button class="button secondary" type="submit">Search</button>
{% if search %}<a class="quiet-link" href="{% url 'panel:customers' %}">Clear</a>{% endif %}
</form>
{% if customers %}
<div class="table-scroll">
<table>
<thead>
<tr>
<th scope="col">Username</th>
<th scope="col">Sign-in status</th>
{% if perms.hosting.change_customer %}<th scope="col">Actions</th>{% endif %}
</tr>
</thead>
<tbody>
{% for customer in customers %}
<tr>
<td><strong>{{ customer }}</strong></td>
<td>
{% if customer.user.is_active %}<span class="status active">Active</span>
{% else %}<span class="status suspended">Suspended</span>{% endif %}
</td>
{% if perms.hosting.change_customer %}
<td>
{% if not customer.user.is_staff and not customer.user.is_superuser and not customer.user.hosting_reseller %}
<form method="post" action="{% url 'panel:customer_access' customer.pk %}{% querystring %}">
{% csrf_token %}
{% if customer.user.is_active %}
<button class="button secondary" type="submit" name="access" value="suspend" aria-label="Suspend sign-in for {{ customer }}">Suspend sign-in</button>
{% else %}
<button class="button secondary" type="submit" name="access" value="restore" aria-label="Restore sign-in for {{ customer }}">Restore sign-in</button>
{% endif %}
</form>
{% endif %}
</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% elif search %}
<p class="empty">No customers match this search.</p>
{% else %}
<p class="empty">No customers yet.</p>
{% endif %}
{% include "hosting/pagination.html" %}
</section>
{% endblock %}
+158
View File
@@ -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)
+7
View File
@@ -19,6 +19,13 @@ urlpatterns = [
path("accounts/new/", views.AccountCreate.as_view(), name="account_create"),
path("accounts/<int:pk>/", views.AccountDetail.as_view(), name="account"),
path("accounts/<int:pk>/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/<int:pk>/access/",
views.CustomerAccess.as_view(),
name="customer_access",
),
path(
"accounts/<int:pk>/databases/new/",
views.DatabaseCreate.as_view(),
+72 -2
View File
@@ -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",)