Add account-scoped access for hosting customers

This commit is contained in:
parkel committed 2026-11-21 00:23:52 +01:00
1 parent 4bbe265915
commit 8de6eb8d88
11 files changed
+389 -50

No files matched your search

+12
View File
@@ -45,6 +45,18 @@ and node deployment files.
The local database defaults to `db.sqlite3`. Set `COULOBRE_SQLITE_PATH` to use a The local database defaults to `db.sqlite3`. Set `COULOBRE_SQLITE_PATH` to use a
different file. Keep `COULOBRE_DEBUG` for local development. 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 ## Request a MariaDB database
Open a hosting account and select **Request database**. Choose a short suffix Open a hosting account and select **Request database**. Choose a short suffix
+2 -4
View File
@@ -1,14 +1,12 @@
from django.contrib.admin import AdminSite from django.contrib.admin import AdminSite
from django.contrib.admin.apps import AdminConfig from django.contrib.admin.apps import AdminConfig
from .hosting.access import reseller_for_user from .hosting.access import is_tenant
class CoulobreAdminSite(AdminSite): class CoulobreAdminSite(AdminSite):
def has_permission(self, request): def has_permission(self, request):
return ( return super().has_permission(request) and not is_tenant(request.user)
super().has_permission(request) and reseller_for_user(request.user) is None
)
class CoulobreAdminConfig(AdminConfig): class CoulobreAdminConfig(AdminConfig):
+32 -4
View File
@@ -1,30 +1,58 @@
def reseller_for_user(user): def customer_for_user(user):
if not user.is_authenticated or user.is_superuser: if not user.is_authenticated or user.is_superuser:
return None 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) 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): 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: class OperatorOnlyMixin:
def dispatch(self, request, *args, **kwargs): 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 self.handle_no_permission()
return super().dispatch(request, *args, **kwargs) return super().dispatch(request, *args, **kwargs)
class ResellerScopeMixin: class TenantScopeMixin:
reseller_relation = "reseller" reseller_relation = "reseller"
customer_relation = None
def has_permission(self): def has_permission(self):
if customer_for_user(self.request.user) is not None:
return self.customer_relation is not None
return ( return (
reseller_for_user(self.request.user) is not None or super().has_permission() reseller_for_user(self.request.user) is not None or super().has_permission()
) )
def get_queryset(self): def get_queryset(self):
queryset = super().get_queryset() 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) reseller = reseller_for_user(self.request.user)
if reseller is not None: if reseller is not None:
return queryset.filter(**{f"{self.reseller_relation}_id": reseller.pk}) return queryset.filter(**{f"{self.reseller_relation}_id": reseller.pk})
+10 -1
View File
@@ -1,7 +1,7 @@
from django.contrib import admin from django.contrib import admin
from django.utils.html import format_html 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) @admin.register(HostingAccount)
@@ -17,6 +17,8 @@ class HostingAccountAdmin(admin.ModelAdmin):
excluded.append("hosting_plan") excluded.append("hosting_plan")
if not request.user.has_perm("hosting.view_reseller"): if not request.user.has_perm("hosting.view_reseller"):
excluded.append("reseller") excluded.append("reseller")
if not request.user.has_perm("hosting.view_customer"):
excluded.append("customer")
return excluded return excluded
def save_model(self, request, obj, form, change): def save_model(self, request, obj, form, change):
@@ -54,6 +56,13 @@ class ResellerAdmin(admin.ModelAdmin):
return excluded return excluded
@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
list_display = ("user",)
list_select_related = ("user",)
search_fields = ("user__username",)
@admin.register(WebProvisioningPlan) @admin.register(WebProvisioningPlan)
class WebProvisioningPlanAdmin(admin.ModelAdmin): class WebProvisioningPlanAdmin(admin.ModelAdmin):
list_display = ("primary_domain", "account", "requested_at", "completed_at") list_display = ("primary_domain", "account", "requested_at", "completed_at")
@@ -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",
),
),
]
+20 -1
View File
@@ -21,7 +21,7 @@ class Reseller(models.Model):
settings.AUTH_USER_MODEL, settings.AUTH_USER_MODEL,
on_delete=models.PROTECT, on_delete=models.PROTECT,
related_name="hosting_reseller", 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) account_limit = models.PositiveIntegerField(default=0)
hosting_plans = models.ManyToManyField("HostingPlan", blank=True) hosting_plans = models.ManyToManyField("HostingPlan", blank=True)
@@ -33,6 +33,22 @@ class Reseller(models.Model):
return self.user.get_username() 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): class HostingPlan(models.Model):
name = models.CharField(max_length=120, unique=True) name = models.CharField(max_length=120, unique=True)
description = models.CharField(max_length=240, blank=True) description = models.CharField(max_length=240, blank=True)
@@ -53,6 +69,9 @@ class HostingAccount(models.Model):
reseller = models.ForeignKey( reseller = models.ForeignKey(
Reseller, on_delete=models.PROTECT, null=True, blank=True 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) created_at = models.DateTimeField(auto_now_add=True)
def get_absolute_url(self): def get_absolute_url(self):
@@ -7,25 +7,28 @@
<h1>{{ account.name }}</h1> <h1>{{ account.name }}</h1>
<p class="heading-meta domain">{{ account.primary_domain }}</p> <p class="heading-meta domain">{{ account.primary_domain }}</p>
</div> </div>
{% if not is_reseller and perms.hosting.change_hostingaccount %} {% if is_operator and perms.hosting.change_hostingaccount %}
<a class="button secondary" href="{% url 'panel:account_edit' account.pk %}">Edit account</a> <a class="button secondary" href="{% url 'panel:account_edit' account.pk %}">Edit account</a>
{% endif %} {% endif %}
</header> </header>
<dl class="details surface"> <dl class="details surface">
<div><dt>Primary domain</dt><dd class="domain">{{ account.primary_domain }}</dd></div> <div><dt>Primary domain</dt><dd class="domain">{{ account.primary_domain }}</dd></div>
{% if is_reseller or perms.hosting.view_hostingplan %} {% if is_tenant or perms.hosting.view_hostingplan %}
<div><dt>Hosting plan</dt><dd>{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}Unassigned{% endif %}</dd></div> <div><dt>Hosting plan</dt><dd>{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}Unassigned{% endif %}</dd></div>
{% endif %} {% endif %}
{% if not is_reseller and perms.hosting.view_reseller %} {% if is_operator and perms.hosting.view_reseller %}
<div><dt>Reseller</dt><dd>{{ account.reseller|default_if_none:"Unassigned" }}</dd></div> <div><dt>Reseller</dt><dd>{{ account.reseller|default_if_none:"Unassigned" }}</dd></div>
{% endif %} {% endif %}
{% if is_operator and perms.hosting.view_customer %}
<div><dt>Customer</dt><dd>{{ account.customer|default_if_none:"Unassigned" }}</dd></div>
{% endif %}
<div><dt>Added</dt><dd>{{ account.created_at|date:"j M Y, H:i" }} UTC</dd></div> <div><dt>Added</dt><dd>{{ account.created_at|date:"j M Y, H:i" }} UTC</dd></div>
</dl> </dl>
{% if is_reseller or perms.hosting.view_webprovisioningplan %} {% if is_reseller or is_operator and perms.hosting.view_webprovisioningplan %}
<section class="surface" aria-labelledby="previews-heading"> <section class="surface" aria-labelledby="previews-heading">
<header class="section-heading"> <header class="section-heading">
<h2 id="previews-heading">Recent Apache previews</h2> <h2 id="previews-heading">Recent Apache previews</h2>
{% if not is_reseller and perms.hosting.change_hostingaccount %} {% if is_operator and perms.hosting.change_hostingaccount %}
<form method="post" action="{% url 'panel:request_plan' account.pk %}"> <form method="post" action="{% url 'panel:request_plan' account.pk %}">
{% csrf_token %} {% csrf_token %}
<button class="button primary" type="submit">Request Apache preview</button> <button class="button primary" type="submit">Request Apache preview</button>
@@ -35,23 +38,23 @@
{% include "hosting/plan_table.html" %} {% include "hosting/plan_table.html" %}
</section> </section>
{% endif %} {% endif %}
{% if is_reseller or perms.hosting.view_hostingdatabase %} {% if is_tenant or perms.hosting.view_hostingdatabase %}
<section class="surface" aria-labelledby="databases-heading"> <section class="surface" aria-labelledby="databases-heading">
<header class="section-heading"> <header class="section-heading">
<h2 id="databases-heading">MariaDB database requests</h2> <h2 id="databases-heading">MariaDB database requests</h2>
{% if not is_reseller and perms.hosting.add_hostingdatabase %} {% if 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>
{% if databases %} {% if databases %}
<div class="table-scroll"> <div class="table-scroll">
<table> <table>
<thead><tr><th scope="col">Database</th>{% if not is_reseller %}<th scope="col">Deployment</th>{% endif %}</tr></thead> <thead><tr><th scope="col">Database</th>{% if is_operator %}<th scope="col">Deployment</th>{% endif %}</tr></thead>
<tbody> <tbody>
{% for database in databases %} {% for database in databases %}
<tr> <tr>
<td class="domain">{{ database }}</td> <td class="domain">{{ database }}</td>
{% if not is_reseller %} {% if is_operator %}
<td><a class="record-link" href="{% url 'panel:database_manifest' database.pk %}" aria-label="Download manifest for {{ database }}">Download manifest</a></td> <td><a class="record-link" href="{% url 'panel:database_manifest' database.pk %}" aria-label="Download manifest for {{ database }}">Download manifest</a></td>
{% endif %} {% endif %}
</tr> </tr>
@@ -64,11 +67,11 @@
{% endif %} {% endif %}
</section> </section>
{% endif %} {% endif %}
{% if is_reseller or perms.hosting.view_hostingdnszone %} {% if is_tenant or perms.hosting.view_hostingdnszone %}
<section class="surface" aria-labelledby="dns-zones-heading"> <section class="surface" aria-labelledby="dns-zones-heading">
<header class="section-heading"> <header class="section-heading">
<h2 id="dns-zones-heading">DNS zones</h2> <h2 id="dns-zones-heading">DNS zones</h2>
{% 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 %}
<a class="button primary" href="{% url 'panel:dns_zone_create' account.pk %}">Add DNS zone</a> <a class="button primary" href="{% url 'panel:dns_zone_create' account.pk %}">Add DNS zone</a>
{% endif %} {% endif %}
</header> </header>
@@ -79,21 +82,21 @@
<tr> <tr>
<th scope="col">Domain</th> <th scope="col">Domain</th>
<th scope="col">SOA serial</th> <th scope="col">SOA serial</th>
{% if not is_reseller %}<th scope="col">Deployment</th>{% endif %} {% if is_operator %}<th scope="col">Deployment</th>{% endif %}
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{% for zone in dns_zones %} {% for zone in dns_zones %}
<tr> <tr>
<td class="domain"> <td class="domain">
{% if not is_reseller and perms.hosting.change_hostingdnszone %} {% if is_operator and perms.hosting.change_hostingdnszone %}
<a class="record-link" href="{% url 'panel:dns_zone_edit' zone.pk %}" aria-label="Edit DNS zone for {{ zone.domain }}">{{ zone.domain }}</a> <a class="record-link" href="{% url 'panel:dns_zone_edit' zone.pk %}" aria-label="Edit DNS zone for {{ zone.domain }}">{{ zone.domain }}</a>
{% else %} {% else %}
{{ zone.domain }} {{ zone.domain }}
{% endif %} {% endif %}
</td> </td>
<td>{{ zone.serial }}</td> <td>{{ zone.serial }}</td>
{% if not is_reseller %} {% if is_operator %}
<td><a class="record-link" href="{% url 'panel:dns_zone_manifest' zone.pk %}" aria-label="Download DNS manifest for {{ zone.domain }}">Download manifest</a></td> <td><a class="record-link" href="{% url 'panel:dns_zone_manifest' zone.pk %}" aria-label="Download DNS manifest for {{ zone.domain }}">Download manifest</a></td>
{% endif %} {% endif %}
</tr> </tr>
@@ -106,11 +109,11 @@
{% endif %} {% endif %}
</section> </section>
{% endif %} {% endif %}
{% if is_reseller or perms.hosting.view_hostingmailbox %} {% if is_tenant or perms.hosting.view_hostingmailbox %}
<section class="surface" aria-labelledby="mailboxes-heading"> <section class="surface" aria-labelledby="mailboxes-heading">
<header class="section-heading"> <header class="section-heading">
<h2 id="mailboxes-heading">Mailbox requests</h2> <h2 id="mailboxes-heading">Mailbox requests</h2>
{% if not is_reseller and perms.hosting.add_hostingmailbox %} {% if 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>
@@ -120,14 +123,14 @@
<thead> <thead>
<tr> <tr>
<th scope="col">Email address</th> <th scope="col">Email address</th>
{% if not is_reseller %}<th scope="col">Deployment</th>{% endif %} {% if is_operator %}<th scope="col">Deployment</th>{% endif %}
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{% for mailbox in mailboxes %} {% for mailbox in mailboxes %}
<tr> <tr>
<td class="domain">{{ mailbox }}</td> <td class="domain">{{ mailbox }}</td>
{% if not is_reseller %} {% if is_operator %}
<td><a class="record-link" href="{% url 'panel:mailbox_manifest' mailbox.pk %}" aria-label="Download mailbox manifest for {{ mailbox }}">Download manifest</a></td> <td><a class="record-link" href="{% url 'panel:mailbox_manifest' mailbox.pk %}" aria-label="Download mailbox manifest for {{ mailbox }}">Download manifest</a></td>
{% endif %} {% endif %}
</tr> </tr>
@@ -7,7 +7,7 @@
<p class="heading-meta">{{ paginator.count }} account{{ paginator.count|pluralize }}{% if search %} matching your search{% endif %}</p> <p class="heading-meta">{{ paginator.count }} account{{ paginator.count|pluralize }}{% if search %} matching your search{% endif %}</p>
{% if account_allowance %}<p class="heading-meta">{{ account_allowance.used }} of {{ account_allowance.limit }} accounts allocated</p>{% endif %} {% if account_allowance %}<p class="heading-meta">{{ account_allowance.used }} of {{ account_allowance.limit }} accounts allocated</p>{% endif %}
</div> </div>
{% 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 %}
<a class="button primary" href="{% url 'panel:account_create' %}">Add hosting account</a> <a class="button primary" href="{% url 'panel:account_create' %}">Add hosting account</a>
{% endif %} {% endif %}
</header> </header>
@@ -25,7 +25,7 @@
<tr> <tr>
<th scope="col">Account</th> <th scope="col">Account</th>
<th scope="col">Primary domain</th> <th scope="col">Primary domain</th>
{% if is_reseller or perms.hosting.view_hostingplan %}<th scope="col">Hosting plan</th>{% endif %} {% if is_tenant or perms.hosting.view_hostingplan %}<th scope="col">Hosting plan</th>{% endif %}
<th scope="col" class="cell-date">Added</th> <th scope="col" class="cell-date">Added</th>
</tr> </tr>
</thead> </thead>
@@ -34,7 +34,7 @@
<tr> <tr>
<td><a class="record-link" href="{{ account.get_absolute_url }}">{{ account.name }}</a></td> <td><a class="record-link" href="{{ account.get_absolute_url }}">{{ account.name }}</a></td>
<td class="domain">{{ account.primary_domain }}</td> <td class="domain">{{ account.primary_domain }}</td>
{% if is_reseller or perms.hosting.view_hostingplan %} {% if is_tenant or perms.hosting.view_hostingplan %}
<td>{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}<span class="muted">Unassigned</span>{% endif %}</td> <td>{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}<span class="muted">Unassigned</span>{% endif %}</td>
{% endif %} {% endif %}
<td class="cell-date muted">{{ account.created_at|date:"j M Y" }}</td> <td class="cell-date muted">{{ account.created_at|date:"j M Y" }}</td>
@@ -17,19 +17,19 @@
</a> </a>
<nav class="navigation" aria-label="Main navigation"> <nav class="navigation" aria-label="Main navigation">
{% with current=request.resolver_match.url_name %} {% with current=request.resolver_match.url_name %}
{% if is_reseller or perms.hosting.view_hostingaccount %} {% if is_tenant or perms.hosting.view_hostingaccount %}
<a href="{% url 'panel:accounts' %}"{% if current == 'accounts' or current == 'account' or current == 'account_create' or current == 'account_edit' or current == 'database_create' %} aria-current="page"{% endif %}> <a href="{% url 'panel:accounts' %}"{% if current == 'accounts' or current == 'account' or current == 'account_create' or current == 'account_edit' or current == 'database_create' %} aria-current="page"{% endif %}>
<span class="nav-icon nav-icon-accounts" aria-hidden="true"></span> <span class="nav-icon nav-icon-accounts" aria-hidden="true"></span>
Hosting accounts Hosting accounts
</a> </a>
{% endif %} {% endif %}
{% if not is_reseller and perms.hosting.view_hostingplan %} {% 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 %}> <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> <span class="nav-icon nav-icon-packages" aria-hidden="true"></span>
Hosting plans Hosting plans
</a> </a>
{% endif %} {% endif %}
{% if is_reseller or perms.hosting.view_webprovisioningplan %} {% if is_reseller or is_operator and perms.hosting.view_webprovisioningplan %}
<a href="{% url 'panel:plans' %}"{% if current == 'plans' or current == 'plan' %} aria-current="page"{% endif %}> <a href="{% url 'panel:plans' %}"{% if current == 'plans' or current == 'plan' %} aria-current="page"{% endif %}>
<span class="nav-icon nav-icon-plans" aria-hidden="true"></span> <span class="nav-icon nav-icon-plans" aria-hidden="true"></span>
Web provisioning Web provisioning
+189
View File
@@ -0,0 +1,189 @@
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import TestCase
from django.urls import reverse
from .models import (
Customer,
HostingAccount,
HostingDatabase,
HostingDnsZone,
HostingMailbox,
HostingMailDomain,
HostingPlan,
Reseller,
WebProvisioningPlan,
)
class CustomerAccessTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_superuser("operator")
cls.alice = users.create_user("alice", password="test-customer-password")
cls.bob = users.create_user("bob")
cls.customer = Customer.objects.create(user=cls.alice)
cls.other_customer = Customer.objects.create(user=cls.bob)
cls.package = HostingPlan.objects.create(name="Starter")
cls.account = HostingAccount.objects.create(
name="Alice website",
primary_domain="alice.example",
customer=cls.customer,
hosting_plan=cls.package,
)
cls.other_account = HostingAccount.objects.create(
name="Bob website",
primary_domain="bob.example",
customer=cls.other_customer,
)
cls.unassigned_account = HostingAccount.objects.create(
name="Unassigned website",
primary_domain="unassigned.example",
)
cls.database = HostingDatabase.objects.create(account=cls.account, suffix="cms")
cls.zone = HostingDnsZone.objects.create(
account=cls.account,
domain="alice.example",
serial=123456789,
nameservers=["ns1.provider.example", "ns2.provider.example"],
responsible_name="hostmaster.alice.example",
)
mail_domain = HostingMailDomain.objects.create(
account=cls.account, domain="alice.example"
)
cls.mailbox = HostingMailbox.objects.create(
mail_domain=mail_domain, local_part="support"
)
cls.preview = WebProvisioningPlan.for_account(cls.account)
cls.preview.save()
def test_customer_can_sign_in_and_see_only_assigned_accounts(self):
additional = HostingAccount.objects.create(
name="Alice blog", primary_domain="blog.example", customer=self.customer
)
self.assertRedirects(
self.client.post(
reverse("panel:login"),
{"username": "alice", "password": "test-customer-password"},
),
reverse("panel:accounts"),
)
accounts = self.client.get(reverse("panel:accounts"))
self.assertContains(accounts, self.account.name)
self.assertContains(accounts, additional.name)
self.assertContains(accounts, self.package.name)
self.assertNotContains(accounts, self.other_account.name)
self.assertNotContains(accounts, self.unassigned_account.name)
self.assertContains(
self.client.get(reverse("panel:accounts"), {"q": "bob.example"}),
"No hosting accounts match this search.",
)
detail = self.client.get(self.account.get_absolute_url())
self.assertContains(detail, str(self.database))
self.assertContains(detail, str(self.zone.serial))
self.assertContains(detail, "support@alice.example")
for account in (self.other_account, self.unassigned_account):
with self.subTest(account=account):
self.assertEqual(
self.client.get(account.get_absolute_url()).status_code, 404
)
def test_operator_permissions_do_not_widen_customer_access(self):
self.alice.is_staff = True
self.alice.save(update_fields=["is_staff"])
self.alice.user_permissions.add(
*Permission.objects.filter(content_type__app_label="hosting")
)
reseller = Reseller.objects.create(user=self.alice, account_limit=2)
self.unassigned_account.reseller = reseller
self.unassigned_account.save(update_fields=["reseller"])
self.client.force_login(self.alice)
accounts = self.client.get(reverse("panel:accounts"))
self.assertContains(accounts, self.account.name)
for label in (
self.unassigned_account.name,
"Add hosting account",
"Web provisioning",
):
self.assertNotContains(accounts, label)
detail = self.client.get(self.account.get_absolute_url())
for label in (
"Edit account",
"Recent Apache previews",
"Request database",
"Request mailbox",
"Download manifest",
):
self.assertNotContains(detail, label)
for route, args in (
("panel:plans", ()),
("panel:plan", (self.preview.pk,)),
("panel:download_deployment_manifest", (self.preview.pk,)),
("panel:download_smoke_bundle", (self.preview.pk,)),
("panel:database_manifest", (self.database.pk,)),
("panel:dns_zone_manifest", (self.zone.pk,)),
("panel:mailbox_manifest", (self.mailbox.pk,)),
("panel:hosting_plans", ()),
):
with self.subTest(route=route):
self.assertEqual(
self.client.get(reverse(route, args=args)).status_code, 403
)
for route, args in (
("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(
self.client.post(reverse(route, args=args)).status_code, 403
)
admin_url = reverse("admin:hosting_hostingaccount_changelist")
self.assertRedirects(
self.client.get(admin_url), f"{reverse('admin:login')}?next={admin_url}"
)
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)
self.assertRedirects(
self.client.post(reverse("admin:hosting_customer_add"), {"user": user.pk}),
reverse("admin:hosting_customer_changelist"),
)
customer = Customer.objects.get(user=user)
self.assertRedirects(
self.client.post(
reverse("panel:account_edit", args=[self.account.pk]),
{
"name": self.account.name,
"primary_domain": self.account.primary_domain,
"hosting_plan": self.package.pk,
"customer": customer.pk,
},
),
self.account.get_absolute_url(),
)
view_accounts = Permission.objects.get(codename="view_hostingaccount")
self.alice.user_permissions.add(view_accounts)
self.client.force_login(self.alice)
self.assertEqual(
self.client.get(self.account.get_absolute_url()).status_code, 404
)
self.assertContains(
self.client.get(reverse("panel:accounts")), "No hosting accounts yet."
)
self.client.force_login(user)
self.assertContains(
self.client.get(self.account.get_absolute_url()), self.account.name
)
+32 -16
View File
@@ -13,7 +13,12 @@ from django.views.generic.detail import SingleObjectMixin
from coulobre.dns_node import MAX_SOA_SERIAL 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, MailboxSpec
from .access import OperatorOnlyMixin, ResellerScopeMixin, reseller_for_user from .access import (
OperatorOnlyMixin,
TenantScopeMixin,
customer_for_user,
reseller_for_user,
)
from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record
from .models import ( from .models import (
HostingAccount, HostingAccount,
@@ -32,12 +37,13 @@ CHANGE_ACCOUNTS = "hosting.change_hostingaccount"
VIEW_PLANS = "hosting.view_webprovisioningplan" VIEW_PLANS = "hosting.view_webprovisioningplan"
VIEW_HOSTING_PLANS = "hosting.view_hostingplan" VIEW_HOSTING_PLANS = "hosting.view_hostingplan"
VIEW_RESELLERS = "hosting.view_reseller" VIEW_RESELLERS = "hosting.view_reseller"
VIEW_CUSTOMERS = "hosting.view_customer"
VIEW_DATABASES = "hosting.view_hostingdatabase" VIEW_DATABASES = "hosting.view_hostingdatabase"
VIEW_DNS_ZONES = "hosting.view_hostingdnszone" VIEW_DNS_ZONES = "hosting.view_hostingdnszone"
VIEW_MAILBOXES = "hosting.view_hostingmailbox" VIEW_MAILBOXES = "hosting.view_hostingmailbox"
class AccountList(ResellerScopeMixin, PermissionRequiredMixin, ListView): class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView):
queryset = HostingAccount.objects.select_related("hosting_plan").order_by( queryset = HostingAccount.objects.select_related("hosting_plan").order_by(
"primary_domain" "primary_domain"
) )
@@ -45,6 +51,7 @@ class AccountList(ResellerScopeMixin, PermissionRequiredMixin, ListView):
template_name = "hosting/account_list.html" template_name = "hosting/account_list.html"
context_object_name = "accounts" context_object_name = "accounts"
paginate_by = 20 paginate_by = 20
customer_relation = "customer"
def get_queryset(self): def get_queryset(self):
self.search = self.request.GET.get("q", "").strip()[:253] self.search = self.request.GET.get("q", "").strip()[:253]
@@ -78,6 +85,8 @@ class AccountEditor:
self.fields += ("hosting_plan",) self.fields += ("hosting_plan",)
if reseller is None and self.request.user.has_perm(VIEW_RESELLERS): if reseller is None and self.request.user.has_perm(VIEW_RESELLERS):
self.fields += ("reseller",) self.fields += ("reseller",)
if reseller is None and self.request.user.has_perm(VIEW_CUSTOMERS):
self.fields += ("customer",)
return super().get_form_class() return super().get_form_class()
def get_form(self, form_class=None): def get_form(self, form_class=None):
@@ -91,12 +100,12 @@ class AccountEditor:
field.queryset = reseller.hosting_plans.all() field.queryset = reseller.hosting_plans.all()
field.required = True field.required = True
field.empty_label = "Select a hosting plan" field.empty_label = "Select a hosting plan"
if "reseller" in form.fields: for name in ("reseller", "customer"):
form.fields["reseller"].empty_label = "Unassigned" if name in form.fields:
form.fields["reseller"].queryset = ( field = form.fields[name]
form.fields["reseller"] field.empty_label = "Unassigned"
.queryset.select_related("user") field.queryset = field.queryset.select_related("user").order_by(
.order_by("user__username") "user__username"
) )
return form return form
@@ -106,6 +115,8 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView):
extra_context = {"page_title": "Add hosting account", "submit_label": "Add account"} extra_context = {"page_title": "Add hosting account", "submit_label": "Add account"}
def has_permission(self): def has_permission(self):
if customer_for_user(self.request.user) is not None:
return False
reseller = reseller_for_user(self.request.user) reseller = reseller_for_user(self.request.user)
if reseller is not None: if reseller is not None:
return reseller.may_create_accounts() return reseller.may_create_accounts()
@@ -148,29 +159,34 @@ class AccountEdit(
return redirect(self.object) return redirect(self.object)
class AccountDetail(ResellerScopeMixin, PermissionRequiredMixin, DetailView): class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
queryset = HostingAccount.objects.select_related("hosting_plan", "reseller__user") queryset = HostingAccount.objects.select_related(
"hosting_plan", "reseller__user", "customer__user"
)
permission_required = VIEW_ACCOUNTS permission_required = VIEW_ACCOUNTS
template_name = "hosting/account_detail.html" template_name = "hosting/account_detail.html"
context_object_name = "account" context_object_name = "account"
customer_relation = "customer"
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs) context = super().get_context_data(**kwargs)
user = self.request.user user = self.request.user
reseller = reseller_for_user(user) reseller = reseller_for_user(user)
if reseller is not None or user.has_perm(VIEW_PLANS): customer = customer_for_user(user)
tenant = reseller is not None or customer is not None
if reseller is not None or (customer is None and user.has_perm(VIEW_PLANS)):
context["plans"] = self.object.webprovisioningplan_set.order_by( context["plans"] = self.object.webprovisioningplan_set.order_by(
"-requested_at", "-pk" "-requested_at", "-pk"
)[:10] )[:10]
if reseller is not None or user.has_perm(VIEW_DATABASES): if tenant or user.has_perm(VIEW_DATABASES):
context["databases"] = self.object.databases.all() context["databases"] = self.object.databases.all()
if reseller is not None or user.has_perm(VIEW_DNS_ZONES): if tenant or user.has_perm(VIEW_DNS_ZONES):
zones = list(self.object.dns_zones.all()) zones = list(self.object.dns_zones.all())
context["dns_zones"] = zones context["dns_zones"] = zones
context["has_primary_zone"] = any( context["has_primary_zone"] = any(
zone.domain == self.object.primary_domain for zone in zones zone.domain == self.object.primary_domain for zone in zones
) )
if reseller is not None or user.has_perm(VIEW_MAILBOXES): if tenant or user.has_perm(VIEW_MAILBOXES):
context["mailboxes"] = HostingMailbox.objects.filter( context["mailboxes"] = HostingMailbox.objects.filter(
mail_domain__account=self.object mail_domain__account=self.object
).select_related("mail_domain") ).select_related("mail_domain")
@@ -441,7 +457,7 @@ class RequestWebPlan(
return redirect("panel:plan", pk=plan.pk) return redirect("panel:plan", pk=plan.pk)
class PlanList(ResellerScopeMixin, PermissionRequiredMixin, ListView): class PlanList(TenantScopeMixin, PermissionRequiredMixin, ListView):
queryset = WebProvisioningPlan.objects.select_related("account").order_by( queryset = WebProvisioningPlan.objects.select_related("account").order_by(
"-requested_at", "-pk" "-requested_at", "-pk"
) )
@@ -452,7 +468,7 @@ class PlanList(ResellerScopeMixin, PermissionRequiredMixin, ListView):
paginate_by = 20 paginate_by = 20
class PlanDetail(ResellerScopeMixin, PermissionRequiredMixin, DetailView): class PlanDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
queryset = WebProvisioningPlan.objects.select_related("account") queryset = WebProvisioningPlan.objects.select_related("account")
permission_required = VIEW_PLANS permission_required = VIEW_PLANS
reseller_relation = "account__reseller" reseller_relation = "account__reseller"