Scope reseller access to assigned hosting accounts

Allow operators to assign accounts to resellers and give each reseller
read-only access to their own accounts and Apache previews.
This commit is contained in:
parkel committed 2026-11-19 22:16:29 +01:00
1 parent bb95b86173
commit 39243a8ab3
13 files changed
+325 -33

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
from django.contrib.admin import AdminSite
from django.contrib.admin.apps import AdminConfig
from .hosting.access import reseller_for_user
class CoulobreAdminSite(AdminSite):
def has_permission(self, request):
return (
super().has_permission(request) and reseller_for_user(request.user) is None
)
class CoulobreAdminConfig(AdminConfig):
default_site = "coulobre.admin.CoulobreAdminSite"
+31
View File
@@ -0,0 +1,31 @@
def reseller_for_user(user):
if not user.is_authenticated or user.is_superuser:
return None
return getattr(user, "hosting_reseller", None)
def panel_access(request):
return {"is_reseller": reseller_for_user(request.user) is not None}
class OperatorOnlyMixin:
def dispatch(self, request, *args, **kwargs):
if reseller_for_user(request.user) is not None:
return self.handle_no_permission()
return super().dispatch(request, *args, **kwargs)
class ResellerScopeMixin:
reseller_relation = "reseller"
def has_permission(self):
return (
reseller_for_user(self.request.user) is not None or super().has_permission()
)
def get_queryset(self):
queryset = super().get_queryset()
reseller = reseller_for_user(self.request.user)
if reseller is not None:
return queryset.filter(**{f"{self.reseller_relation}_id": reseller.pk})
return queryset
+13 -3
View File
@@ -1,7 +1,7 @@
from django.contrib import admin
from django.utils.html import format_html
from .models import HostingAccount, HostingPlan, WebProvisioningPlan
from .models import HostingAccount, HostingPlan, Reseller, WebProvisioningPlan
@admin.register(HostingAccount)
@@ -12,9 +12,12 @@ class HostingAccountAdmin(admin.ModelAdmin):
actions = ("request_web_plans",)
def get_exclude(self, request, obj=None):
excluded = list(super().get_exclude(request, obj) or ())
if not request.user.has_perm("hosting.view_hostingplan"):
return ("hosting_plan",)
return super().get_exclude(request, obj)
excluded.append("hosting_plan")
if not request.user.has_perm("hosting.view_reseller"):
excluded.append("reseller")
return excluded
def save_model(self, request, obj, form, change):
if change:
@@ -37,6 +40,13 @@ class HostingPlanAdmin(admin.ModelAdmin):
search_fields = ("name",)
@admin.register(Reseller)
class ResellerAdmin(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")
@@ -0,0 +1,48 @@
# Generated by Django 5.2.19 on 2026-11-19 21:13
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0003_hostingplan_hostingaccount_hosting_plan"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="Reseller",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"user",
models.OneToOneField(
limit_choices_to={"is_superuser": False},
on_delete=django.db.models.deletion.PROTECT,
related_name="hosting_reseller",
to=settings.AUTH_USER_MODEL,
),
),
],
),
migrations.AddField(
model_name="hostingaccount",
name="reseller",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.PROTECT,
to="hosting.reseller",
),
),
]
+16
View File
@@ -1,9 +1,22 @@
from django.conf import settings
from django.db import models
from django.urls import reverse
from .fields import DomainNameField
class Reseller(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.PROTECT,
related_name="hosting_reseller",
limit_choices_to={"is_superuser": False},
)
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)
@@ -21,6 +34,9 @@ class HostingAccount(models.Model):
hosting_plan = models.ForeignKey(
HostingPlan, on_delete=models.PROTECT, null=True, blank=True
)
reseller = models.ForeignKey(
Reseller, on_delete=models.PROTECT, null=True, blank=True
)
created_at = models.DateTimeField(auto_now_add=True)
def get_absolute_url(self):
@@ -7,22 +7,25 @@
<h1>{{ account.name }}</h1>
<p class="heading-meta domain">{{ account.primary_domain }}</p>
</div>
{% if perms.hosting.change_hostingaccount %}
{% if not is_reseller and perms.hosting.change_hostingaccount %}
<a class="button secondary" href="{% url 'panel:account_edit' account.pk %}">Edit account</a>
{% endif %}
</header>
<dl class="details surface">
<div><dt>Primary domain</dt><dd class="domain">{{ account.primary_domain }}</dd></div>
{% if perms.hosting.view_hostingplan %}
{% if is_reseller or perms.hosting.view_hostingplan %}
<div><dt>Hosting plan</dt><dd>{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}Unassigned{% endif %}</dd></div>
{% endif %}
{% if not is_reseller and perms.hosting.view_reseller %}
<div><dt>Reseller</dt><dd>{{ account.reseller|default_if_none:"Unassigned" }}</dd></div>
{% endif %}
<div><dt>Added</dt><dd>{{ account.created_at|date:"j M Y, H:i" }} UTC</dd></div>
</dl>
{% if perms.hosting.view_webprovisioningplan %}
{% if is_reseller or perms.hosting.view_webprovisioningplan %}
<section class="surface" aria-labelledby="previews-heading">
<header class="section-heading">
<h2 id="previews-heading">Recent Apache previews</h2>
{% if perms.hosting.change_hostingaccount %}
{% if not is_reseller and perms.hosting.change_hostingaccount %}
<form method="post" action="{% url 'panel:request_plan' account.pk %}">
{% csrf_token %}
<button class="button primary" type="submit">Request Apache preview</button>
@@ -6,7 +6,7 @@
<h1>Hosting accounts</h1>
<p class="heading-meta">{{ paginator.count }} account{{ paginator.count|pluralize }}{% if search %} matching your search{% endif %}</p>
</div>
{% if perms.hosting.add_hostingaccount %}
{% if not is_reseller and perms.hosting.add_hostingaccount %}
<a class="button primary" href="{% url 'panel:account_create' %}">Add hosting account</a>
{% endif %}
</header>
@@ -24,7 +24,7 @@
<tr>
<th scope="col">Account</th>
<th scope="col">Primary domain</th>
{% if perms.hosting.view_hostingplan %}<th scope="col">Hosting plan</th>{% endif %}
{% if is_reseller or perms.hosting.view_hostingplan %}<th scope="col">Hosting plan</th>{% endif %}
<th scope="col" class="cell-date">Added</th>
</tr>
</thead>
@@ -33,7 +33,7 @@
<tr>
<td><a class="record-link" href="{{ account.get_absolute_url }}">{{ account.name }}</a></td>
<td class="domain">{{ account.primary_domain }}</td>
{% if perms.hosting.view_hostingplan %}
{% if is_reseller or perms.hosting.view_hostingplan %}
<td>{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}<span class="muted">Unassigned</span>{% endif %}</td>
{% endif %}
<td class="cell-date muted">{{ account.created_at|date:"j M Y" }}</td>
@@ -17,19 +17,19 @@
</a>
<nav class="navigation" aria-label="Main navigation">
{% with current=request.resolver_match.url_name %}
{% if perms.hosting.view_hostingaccount %}
{% if is_reseller or perms.hosting.view_hostingaccount %}
<a href="{% url 'panel:accounts' %}"{% if current == 'accounts' or current == 'account' or current == 'account_create' or current == 'account_edit' %} aria-current="page"{% endif %}>
<span class="nav-icon nav-icon-accounts" aria-hidden="true"></span>
Hosting accounts
</a>
{% endif %}
{% if perms.hosting.view_hostingplan %}
{% if not is_reseller 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>
Hosting plans
</a>
{% endif %}
{% if perms.hosting.view_webprovisioningplan %}
{% if is_reseller or perms.hosting.view_webprovisioningplan %}
<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>
Web provisioning
@@ -13,7 +13,7 @@
</header>
<dl class="details surface">
<div><dt>Status</dt><dd>{% include "hosting/plan_status.html" %}</dd></div>
<div><dt>Hosting account</dt><dd>{% if perms.hosting.view_hostingaccount %}<a class="record-link" href="{{ plan.account.get_absolute_url }}">{{ plan.account.name }}</a>{% else %}{{ plan.account.name }}{% endif %}</dd></div>
<div><dt>Hosting account</dt><dd>{% if is_reseller or perms.hosting.view_hostingaccount %}<a class="record-link" href="{{ plan.account.get_absolute_url }}">{{ plan.account.name }}</a>{% else %}{{ plan.account.name }}{% endif %}</dd></div>
<div><dt>Requested</dt><dd>{{ plan.requested_at|date:"j M Y, H:i" }} UTC</dd></div>
</dl>
{% if plan.primary_domain != plan.account.primary_domain %}
@@ -23,7 +23,7 @@
<section class="surface" aria-labelledby="configuration-heading">
<header class="section-heading">
<h2 id="configuration-heading">Virtual host configuration</h2>
{% if plan.can_export %}
{% if not is_reseller and plan.can_export %}
<div class="form-actions">
<a class="button secondary" href="{% url 'panel:download_deployment_manifest' plan.pk %}">Download deployment manifest</a>
<a class="button secondary" href="{% url 'panel:download_smoke_bundle' plan.pk %}">Download test bundle</a>
+132
View File
@@ -0,0 +1,132 @@
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 HostingAccount, HostingPlan, Reseller, WebProvisioningPlan
from .tasks import render_web_plan
class ResellerAccessTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_superuser("operator")
cls.alice = users.create_user("alice")
cls.bob = users.create_user("bob", is_staff=True)
cls.bob.user_permissions.add(
*Permission.objects.filter(content_type__app_label="hosting")
)
cls.alice_reseller = Reseller.objects.create(user=cls.alice)
cls.bob_reseller = Reseller.objects.create(user=cls.bob)
cls.package = HostingPlan.objects.create(name="Starter")
cls.alice_account = HostingAccount.objects.create(
name="Alice hosting",
primary_domain="alice.example",
hosting_plan=cls.package,
reseller=cls.alice_reseller,
)
cls.bob_account = HostingAccount.objects.create(
name="Bob hosting",
primary_domain="bob.example",
reseller=cls.bob_reseller,
)
cls.unassigned_account = HostingAccount.objects.create(
name="Platform hosting",
primary_domain="platform.example",
)
cls.alice_plan = WebProvisioningPlan.for_account(cls.alice_account)
cls.alice_plan.save()
cls.bob_plan = WebProvisioningPlan.for_account(cls.bob_account)
cls.bob_plan.save()
render_web_plan.run(cls.alice_plan.pk)
render_web_plan.run(cls.bob_plan.pk)
def test_reseller_can_see_only_assigned_accounts_and_previews(self):
self.client.force_login(self.alice)
accounts = self.client.get(reverse("panel:accounts"))
self.assertContains(accounts, self.alice_account.name)
self.assertContains(accounts, self.package.name)
self.assertNotContains(accounts, self.bob_account.name)
self.assertNotContains(accounts, self.unassigned_account.name)
search = self.client.get(reverse("panel:accounts"), {"q": "bob.example"})
self.assertContains(search, "No hosting accounts match this search.")
self.assertContains(
self.client.get(self.alice_account.get_absolute_url()), "alice.example"
)
for account in (self.bob_account, self.unassigned_account):
self.assertEqual(
self.client.get(account.get_absolute_url()).status_code, 404
)
previews = self.client.get(reverse("panel:plans"))
self.assertContains(previews, "alice.example")
self.assertNotContains(previews, "bob.example")
preview = self.client.get(reverse("panel:plan", args=[self.alice_plan.pk]))
self.assertContains(preview, "ServerName alice.example")
self.assertNotContains(preview, "Download deployment manifest")
self.assertEqual(
self.client.get(reverse("panel:plan", args=[self.bob_plan.pk])).status_code,
404,
)
def test_staff_reseller_permissions_cannot_open_operator_routes(self):
self.client.force_login(self.bob)
self.assertContains(
self.client.get(reverse("panel:accounts")), self.bob_account.name
)
self.assertEqual(
self.client.get(self.alice_account.get_absolute_url()).status_code, 404
)
for route, args in (
("panel:account_create", ()),
("panel:account_edit", (self.bob_account.pk,)),
("panel:request_plan", (self.bob_account.pk,)),
("panel:hosting_plans", ()),
("panel:hosting_plan_create", ()),
("panel:hosting_plan_edit", (self.package.pk,)),
("panel:download_deployment_manifest", (self.bob_plan.pk,)),
("panel:download_smoke_bundle", (self.bob_plan.pk,)),
):
with self.subTest(route=route):
self.assertEqual(
self.client.post(reverse(route, args=args)).status_code, 403
)
self.assertEqual(
self.client.get(
reverse("panel:download_deployment_manifest", args=[self.bob_plan.pk])
).status_code,
403,
)
self.assertRedirects(
self.client.get(reverse("admin:hosting_hostingaccount_changelist")),
reverse("admin:login") + "?next=/admin/hosting/hostingaccount/",
)
self.assertEqual(WebProvisioningPlan.objects.count(), 2)
def test_operator_assignment_takes_effect_on_the_next_reseller_request(self):
self.client.force_login(self.operator)
account = self.alice_account
response = self.client.post(
reverse("panel:account_edit", args=[account.pk]),
{
"name": account.name,
"primary_domain": account.primary_domain,
"hosting_plan": self.package.pk,
"reseller": self.bob_reseller.pk,
},
)
self.assertRedirects(response, account.get_absolute_url())
self.assertContains(
self.client.get(account.get_absolute_url()), "<dd>bob</dd>", html=True
)
self.client.force_login(self.alice)
self.assertEqual(self.client.get(account.get_absolute_url()).status_code, 404)
preview_url = reverse("panel:plan", args=[self.alice_plan.pk])
self.assertEqual(self.client.get(preview_url).status_code, 404)
self.client.force_login(self.bob)
self.assertContains(self.client.get(account.get_absolute_url()), account.name)
self.assertContains(self.client.get(preview_url), "ServerName alice.example")
+42 -17
View File
@@ -7,6 +7,7 @@ from django.views import View
from django.views.generic import CreateView, DetailView, ListView, UpdateView
from django.views.generic.detail import SingleObjectMixin
from .access import OperatorOnlyMixin, ResellerScopeMixin, reseller_for_user
from .models import HostingAccount, HostingPlan, WebProvisioningPlan
from .web_node import build_web_smoke_bundle, serialize_deployment_manifest
@@ -14,10 +15,13 @@ VIEW_ACCOUNTS = "hosting.view_hostingaccount"
CHANGE_ACCOUNTS = "hosting.change_hostingaccount"
VIEW_PLANS = "hosting.view_webprovisioningplan"
VIEW_HOSTING_PLANS = "hosting.view_hostingplan"
VIEW_RESELLERS = "hosting.view_reseller"
class AccountList(PermissionRequiredMixin, ListView):
model = HostingAccount
class AccountList(ResellerScopeMixin, PermissionRequiredMixin, ListView):
queryset = HostingAccount.objects.select_related("hosting_plan").order_by(
"primary_domain"
)
permission_required = VIEW_ACCOUNTS
template_name = "hosting/account_list.html"
context_object_name = "accounts"
@@ -25,9 +29,7 @@ class AccountList(PermissionRequiredMixin, ListView):
def get_queryset(self):
self.search = self.request.GET.get("q", "").strip()[:253]
accounts = HostingAccount.objects.select_related("hosting_plan").order_by(
"primary_domain"
)
accounts = super().get_queryset()
if self.search:
accounts = accounts.filter(
Q(name__icontains=self.search)
@@ -47,21 +49,34 @@ class AccountEditor:
self.fields = ("name", "primary_domain")
if self.request.user.has_perm(VIEW_HOSTING_PLANS):
self.fields += ("hosting_plan",)
if self.request.user.has_perm(VIEW_RESELLERS):
self.fields += ("reseller",)
return super().get_form_class()
def get_form(self, form_class=None):
form = super().get_form(form_class)
if "hosting_plan" in form.fields:
form.fields["hosting_plan"].empty_label = "Unassigned"
if "reseller" in form.fields:
form.fields["reseller"].empty_label = "Unassigned"
form.fields["reseller"].queryset = (
form.fields["reseller"]
.queryset.select_related("user")
.order_by("user__username")
)
return form
class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView):
class AccountCreate(
OperatorOnlyMixin, PermissionRequiredMixin, AccountEditor, CreateView
):
permission_required = (VIEW_ACCOUNTS, "hosting.add_hostingaccount")
extra_context = {"page_title": "Add hosting account", "submit_label": "Add account"}
class AccountEdit(PermissionRequiredMixin, AccountEditor, UpdateView):
class AccountEdit(
OperatorOnlyMixin, PermissionRequiredMixin, AccountEditor, UpdateView
):
permission_required = (VIEW_ACCOUNTS, CHANGE_ACCOUNTS)
context_object_name = "account"
extra_context = {
@@ -75,22 +90,24 @@ class AccountEdit(PermissionRequiredMixin, AccountEditor, UpdateView):
return redirect(self.object)
class AccountDetail(PermissionRequiredMixin, DetailView):
queryset = HostingAccount.objects.select_related("hosting_plan")
class AccountDetail(ResellerScopeMixin, PermissionRequiredMixin, DetailView):
queryset = HostingAccount.objects.select_related("hosting_plan", "reseller__user")
permission_required = VIEW_ACCOUNTS
template_name = "hosting/account_detail.html"
context_object_name = "account"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if self.request.user.has_perm(VIEW_PLANS):
if reseller_for_user(
self.request.user
) is not None or self.request.user.has_perm(VIEW_PLANS):
context["plans"] = self.object.webprovisioningplan_set.order_by(
"-requested_at", "-pk"
)[:10]
return context
class HostingPlanList(PermissionRequiredMixin, ListView):
class HostingPlanList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
model = HostingPlan
permission_required = VIEW_HOSTING_PLANS
template_name = "hosting/hosting_plan_list.html"
@@ -105,17 +122,23 @@ class HostingPlanEditor:
success_url = reverse_lazy("panel:hosting_plans")
class HostingPlanCreate(PermissionRequiredMixin, HostingPlanEditor, CreateView):
class HostingPlanCreate(
OperatorOnlyMixin, PermissionRequiredMixin, HostingPlanEditor, CreateView
):
permission_required = (VIEW_HOSTING_PLANS, "hosting.add_hostingplan")
extra_context = {"page_title": "Add hosting plan", "submit_label": "Add plan"}
class HostingPlanEdit(PermissionRequiredMixin, HostingPlanEditor, UpdateView):
class HostingPlanEdit(
OperatorOnlyMixin, PermissionRequiredMixin, HostingPlanEditor, UpdateView
):
permission_required = (VIEW_HOSTING_PLANS, "hosting.change_hostingplan")
extra_context = {"page_title": "Edit hosting plan", "submit_label": "Save changes"}
class RequestWebPlan(PermissionRequiredMixin, SingleObjectMixin, View):
class RequestWebPlan(
OperatorOnlyMixin, PermissionRequiredMixin, SingleObjectMixin, View
):
model = HostingAccount
permission_required = (VIEW_ACCOUNTS, CHANGE_ACCOUNTS, VIEW_PLANS)
@@ -125,24 +148,26 @@ class RequestWebPlan(PermissionRequiredMixin, SingleObjectMixin, View):
return redirect("panel:plan", pk=plan.pk)
class PlanList(PermissionRequiredMixin, ListView):
class PlanList(ResellerScopeMixin, PermissionRequiredMixin, ListView):
queryset = WebProvisioningPlan.objects.select_related("account").order_by(
"-requested_at", "-pk"
)
permission_required = VIEW_PLANS
reseller_relation = "account__reseller"
template_name = "hosting/plan_list.html"
context_object_name = "plans"
paginate_by = 20
class PlanDetail(PermissionRequiredMixin, DetailView):
class PlanDetail(ResellerScopeMixin, PermissionRequiredMixin, DetailView):
queryset = WebProvisioningPlan.objects.select_related("account")
permission_required = VIEW_PLANS
reseller_relation = "account__reseller"
template_name = "hosting/plan_detail.html"
context_object_name = "plan"
class DownloadWebPlan(PlanDetail):
class DownloadWebPlan(OperatorOnlyMixin, PlanDetail):
manifest = False
def render_to_response(self, context, **response_kwargs):
+2 -1
View File
@@ -18,7 +18,7 @@ ALLOWED_HOSTS = os.environ.get(
).split(",")
INSTALLED_APPS = [
"django.contrib.admin",
"coulobre.admin.CoulobreAdminConfig",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
@@ -47,6 +47,7 @@ TEMPLATES = [
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
"coulobre.hosting.access.panel_access",
],
},
},