Merge pull request 'Add hosting plans and reseller account self-service' (#4) from feature/hosting-plans into main

Reviewed-on: #4
This commit was merged in pull request #4.
This commit is contained in:
parkel committed 2026-11-19 22:32:49 +01:00
commit e1dc9a26cb
21 files changed
+894 -33

No files matched your search

+23
View File
@@ -19,6 +19,29 @@ Select **Add hosting account** and enter a name and a primary domain such as
`example.org`. Open an account from the list to edit its details or request an `example.org`. Open an account from the list to edit its details or request an
Apache preview. Manage users, groups, and permissions at `/admin/`. Apache preview. Manage users, groups, and permissions at `/admin/`.
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.
## Give a reseller access to assigned accounts
In `/admin/`, create a normal user and add a **Reseller** record for that user.
Then open a hosting account in Coulobre Panel and select the reseller when
editing the account. Existing accounts start with no reseller assigned.
The reseller can sign in to Coulobre Panel to see their assigned accounts,
each account's hosting plan, and its web provisioning previews.
To let the reseller add accounts, set a positive account limit and select the
available hosting plans in the reseller's admin record. The reseller's account
list shows their allowance. The limit applies to self-service creation, and
operator assignments also count toward the allowance. New reseller accounts
automatically belong to that reseller and require an allowed plan. A limit of
zero keeps the reseller's access read-only.
Platform operators manage existing accounts, assignments, reseller allowances,
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.
+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
+35 -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, WebProvisioningPlan from .models import HostingAccount, HostingPlan, Reseller, WebProvisioningPlan
@admin.register(HostingAccount) @admin.register(HostingAccount)
@@ -11,6 +11,20 @@ class HostingAccountAdmin(admin.ModelAdmin):
ordering = ("primary_domain",) ordering = ("primary_domain",)
actions = ("request_web_plans",) 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"):
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:
obj.save(update_fields=form.changed_data)
else:
super().save_model(request, obj, form, change)
@admin.action(permissions=["change"], description="Request Apache plans") @admin.action(permissions=["change"], description="Request Apache plans")
def request_web_plans(self, request, queryset): def request_web_plans(self, request, queryset):
plans = WebProvisioningPlan.objects.bulk_create( plans = WebProvisioningPlan.objects.bulk_create(
@@ -20,6 +34,26 @@ class HostingAccountAdmin(admin.ModelAdmin):
self.message_user(request, f"Queued {len(plans)} Apache plan(s).") self.message_user(request, f"Queued {len(plans)} Apache plan(s).")
@admin.register(HostingPlan)
class HostingPlanAdmin(admin.ModelAdmin):
list_display = ("name", "description")
search_fields = ("name",)
@admin.register(Reseller)
class ResellerAdmin(admin.ModelAdmin):
list_display = ("user", "account_limit")
list_select_related = ("user",)
search_fields = ("user__username",)
filter_horizontal = ("hosting_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"):
excluded.append("hosting_plans")
return excluded
@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,42 @@
# Generated by Django 5.2.19 on 2026-11-19 21:07
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0002_webprovisioningplan"),
]
operations = [
migrations.CreateModel(
name="HostingPlan",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=120, unique=True)),
("description", models.CharField(blank=True, max_length=240)),
],
options={
"ordering": ("name", "pk"),
},
),
migrations.AddField(
model_name="hostingaccount",
name="hosting_plan",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.PROTECT,
to="hosting.hostingplan",
),
),
]
@@ -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",
),
),
]
@@ -0,0 +1,22 @@
# Generated by Django 5.2.19 on 2026-11-19 21:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0004_reseller_hostingaccount_reseller"),
]
operations = [
migrations.AddField(
model_name="reseller",
name="account_limit",
field=models.PositiveIntegerField(default=0),
),
migrations.AddField(
model_name="reseller",
name="hosting_plans",
field=models.ManyToManyField(blank=True, to="hosting.hostingplan"),
),
]
+35
View File
@@ -1,12 +1,47 @@
from django.conf import settings
from django.db import models from django.db import models
from django.urls import reverse from django.urls import reverse
from .fields import DomainNameField 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},
)
account_limit = models.PositiveIntegerField(default=0)
hosting_plans = models.ManyToManyField("HostingPlan", blank=True)
def may_create_accounts(self):
return self.account_limit > 0 and self.hosting_plans.exists()
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)
class Meta:
ordering = ("name", "pk")
def __str__(self):
return self.name
class HostingAccount(models.Model): class HostingAccount(models.Model):
name = models.CharField(max_length=120) name = models.CharField(max_length=120)
primary_domain = DomainNameField(max_length=253, unique=True) primary_domain = DomainNameField(max_length=253, unique=True)
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) created_at = models.DateTimeField(auto_now_add=True)
def get_absolute_url(self): def get_absolute_url(self):
+27
View File
@@ -0,0 +1,27 @@
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
from django.db import connection, transaction
from django.db.models import F
from .models import Reseller
@transaction.atomic
def create_reseller_account(access, account):
candidates = Reseller.objects.filter(pk=access.pk, user_id=access.user_id)
if connection.vendor == "sqlite":
# SQLite needs a write before the quota read to serialize writers.
candidates.update(account_limit=F("account_limit"))
reseller = candidates.select_for_update().first()
if reseller is None:
raise ValidationError({NON_FIELD_ERRORS: "Your reseller access has changed."})
if reseller.hostingaccount_set.count() >= reseller.account_limit:
raise ValidationError(
{NON_FIELD_ERRORS: "Your hosting account limit has been reached."}
)
if not reseller.hosting_plans.filter(pk=account.hosting_plan_id).exists():
raise ValidationError(
{"hosting_plan": "This hosting plan is no longer available to you."}
)
account.reseller = reseller
account.save(force_insert=True)
@@ -29,7 +29,7 @@ a {
text-underline-offset: 0.2em; text-underline-offset: 0.2em;
} }
button, input { button, input, select {
font: inherit; font: inherit;
} }
@@ -155,6 +155,10 @@ button, input {
linear-gradient(currentColor, currentColor) center 65% / 55% 1px no-repeat; linear-gradient(currentColor, currentColor) center 65% / 55% 1px no-repeat;
} }
.nav-icon-packages {
background: linear-gradient(currentColor, currentColor) center 35% / 40% 1px no-repeat;
}
.sidebar-account { .sidebar-account {
display: grid; display: grid;
gap: 0.3rem; gap: 0.3rem;
@@ -288,7 +292,7 @@ h2 {
font-size: 0.88rem; font-size: 0.88rem;
} }
input:not([type="hidden"]) { input:not([type="hidden"]), select {
min-width: 0; min-width: 0;
height: 2.55rem; height: 2.55rem;
padding: 0.48rem 0.68rem; padding: 0.48rem 0.68rem;
@@ -463,7 +467,7 @@ dd {
font-weight: 680; font-weight: 680;
} }
.editor input:not([type="hidden"]) { .editor input:not([type="hidden"]), .editor select {
width: 100%; width: 100%;
} }
@@ -7,19 +7,25 @@
<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 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> <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 %}
<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> <div><dt>Added</dt><dd>{{ account.created_at|date:"j M Y, H:i" }} UTC</dd></div>
</dl> </dl>
{% if perms.hosting.view_webprovisioningplan %} {% if is_reseller or 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 perms.hosting.change_hostingaccount %} {% if not is_reseller 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>
@@ -5,8 +5,9 @@
<div> <div>
<h1>Hosting accounts</h1> <h1>Hosting accounts</h1>
<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 %}
</div> </div>
{% if perms.hosting.add_hostingaccount %} {% if account_allowance and account_allowance.used < account_allowance.limit or not is_reseller 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>
@@ -21,13 +22,21 @@
<div class="table-scroll"> <div class="table-scroll">
<table> <table>
<thead> <thead>
<tr><th scope="col">Account</th><th scope="col">Primary domain</th><th scope="col" class="cell-date">Added</th></tr> <tr>
<th scope="col">Account</th>
<th scope="col">Primary domain</th>
{% 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> </thead>
<tbody> <tbody>
{% for account in accounts %} {% for account in accounts %}
<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 %}
<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> <td class="cell-date muted">{{ account.created_at|date:"j M Y" }}</td>
</tr> </tr>
{% endfor %} {% endfor %}
@@ -17,13 +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 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 %}> <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> <span class="nav-icon nav-icon-accounts" aria-hidden="true"></span>
Hosting accounts Hosting accounts
</a> </a>
{% endif %} {% endif %}
{% if perms.hosting.view_webprovisioningplan %} {% 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 is_reseller or 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
@@ -0,0 +1,16 @@
{% extends "hosting/base.html" %}
{% block title %}{{ page_title }} · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{% url 'panel:hosting_plans' %}">← Hosting plans</a>
<header class="page-heading"><h1>{{ page_title }}</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">{{ submit_label }}</button>
<a class="button secondary" href="{% url 'panel:hosting_plans' %}">Cancel</a>
</div>
</form>
</section>
{% endblock %}
@@ -0,0 +1,36 @@
{% extends "hosting/base.html" %}
{% block title %}Hosting plans · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading">
<h1>Hosting plans</h1>
{% if perms.hosting.add_hostingplan %}
<a class="button primary" href="{% url 'panel:hosting_plan_create' %}">Add hosting plan</a>
{% endif %}
</header>
<section class="surface" aria-label="Hosting plans">
{% if hosting_plans %}
<div class="table-scroll">
<table>
<thead><tr><th scope="col">Plan</th><th scope="col">Description</th></tr></thead>
<tbody>
{% for hosting_plan in hosting_plans %}
<tr>
<td>
{% if perms.hosting.change_hostingplan %}
<a class="record-link" href="{% url 'panel:hosting_plan_edit' hosting_plan.pk %}">{{ hosting_plan.name }}</a>
{% else %}
<strong>{{ hosting_plan.name }}</strong>
{% endif %}
</td>
<td>{{ hosting_plan.description|default:"—" }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p class="empty">No hosting plans yet.</p>
{% endif %}
{% include "hosting/pagination.html" %}
</section>
{% endblock %}
@@ -13,7 +13,7 @@
</header> </header>
<dl class="details surface"> <dl class="details surface">
<div><dt>Status</dt><dd>{% include "hosting/plan_status.html" %}</dd></div> <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> <div><dt>Requested</dt><dd>{{ plan.requested_at|date:"j M Y, H:i" }} UTC</dd></div>
</dl> </dl>
{% if plan.primary_domain != plan.account.primary_domain %} {% if plan.primary_domain != plan.account.primary_domain %}
@@ -23,7 +23,7 @@
<section class="surface" aria-labelledby="configuration-heading"> <section class="surface" aria-labelledby="configuration-heading">
<header class="section-heading"> <header class="section-heading">
<h2 id="configuration-heading">Virtual host configuration</h2> <h2 id="configuration-heading">Virtual host configuration</h2>
{% if plan.can_export %} {% if not is_reseller and plan.can_export %}
<div class="form-actions"> <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_deployment_manifest' plan.pk %}">Download deployment manifest</a>
<a class="button secondary" href="{% url 'panel:download_smoke_bundle' plan.pk %}">Download test bundle</a> <a class="button secondary" href="{% url 'panel:download_smoke_bundle' plan.pk %}">Download test bundle</a>
+125
View File
@@ -0,0 +1,125 @@
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.db.models.deletion import ProtectedError
from django.test import TestCase
from django.urls import reverse
from .models import HostingAccount, HostingPlan
class HostingPlanTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_superuser("operator")
cls.editor = users.create_user("editor", is_staff=True)
cls.editor.user_permissions.add(
*Permission.objects.filter(
content_type__app_label="hosting",
codename__in=("view_hostingaccount", "change_hostingaccount"),
)
)
cls.account = HostingAccount.objects.create(
name="Example hosting", primary_domain="example.org"
)
def test_operator_can_create_assign_and_edit_a_plan(self):
self.client.force_login(self.operator)
list_url = reverse("panel:hosting_plans")
response = self.client.post(
reverse("panel:hosting_plan_create"),
{"name": "Starter", "description": "Shared hosting for small sites"},
)
self.assertRedirects(response, list_url)
plan = HostingPlan.objects.get()
self.assertContains(
self.client.get(self.account.get_absolute_url()), "Unassigned"
)
response = self.client.post(
reverse("panel:account_edit", args=[self.account.pk]),
{
"name": self.account.name,
"primary_domain": "example.org",
"hosting_plan": plan.pk,
},
)
self.assertRedirects(response, self.account.get_absolute_url())
self.account.refresh_from_db()
self.assertEqual(self.account.hosting_plan_id, plan.pk)
response = self.client.post(
reverse("panel:hosting_plan_edit", args=[plan.pk]),
{"name": "Standard", "description": "Updated description"},
)
self.assertRedirects(response, list_url)
self.assertContains(self.client.get(reverse("panel:accounts")), "Standard")
response = self.client.post(
reverse("panel:account_create"),
{
"name": "New hosting",
"primary_domain": "new.example",
"hosting_plan": plan.pk,
},
)
new_account = HostingAccount.objects.get(primary_domain="new.example")
self.assertRedirects(response, new_account.get_absolute_url())
self.assertEqual(new_account.hosting_plan_id, plan.pk)
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")
HostingAccount.objects.filter(pk=self.account.pk).update(hosting_plan=current)
self.client.force_login(self.editor)
self.assertEqual(
self.client.get(reverse("panel:hosting_plans")).status_code, 403
)
self.assertNotContains(
self.client.get(self.account.get_absolute_url()), current.name
)
for route in ("panel:account_edit", "admin:hosting_hostingaccount_change"):
with self.subTest(route=route):
url = reverse(route, args=[self.account.pk])
self.assertNotContains(self.client.get(url), 'name="hosting_plan"')
response = self.client.post(
url,
{
"name": route,
"primary_domain": "example.org",
"hosting_plan": other.pk,
},
)
self.assertEqual(response.status_code, 302)
self.account.refresh_from_db()
self.assertEqual(self.account.name, route)
self.assertEqual(self.account.hosting_plan_id, current.pk)
def test_unrelated_account_edit_preserves_a_concurrent_plan_assignment(self):
plan = HostingPlan.objects.create(name="Starter")
self.client.force_login(self.editor)
save = HostingAccount.save
def assign_then_save(account, *args, **kwargs):
HostingAccount.objects.filter(pk=account.pk).update(hosting_plan=plan)
return save(account, *args, **kwargs)
with patch.object(HostingAccount, "save", assign_then_save):
response = self.client.post(
reverse("panel:account_edit", args=[self.account.pk]),
{"name": "Renamed hosting", "primary_domain": "example.org"},
)
self.assertRedirects(response, self.account.get_absolute_url())
self.account.refresh_from_db()
self.assertEqual(self.account.name, "Renamed hosting")
self.assertEqual(self.account.hosting_plan_id, plan.pk)
def test_cannot_delete_an_assigned_plan(self):
plan = HostingPlan.objects.create(name="Assigned plan")
HostingAccount.objects.filter(pk=self.account.pk).update(hosting_plan=plan)
with self.assertRaises(ProtectedError):
plan.delete()
+258
View File
@@ -0,0 +1,258 @@
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
from django.urls import reverse
from .models import HostingAccount, HostingPlan, Reseller, WebProvisioningPlan
from .reseller_accounts import create_reseller_account
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")
class ResellerAccountCreationTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.user = users.create_user("reseller")
cls.operator = users.create_superuser("operator")
cls.reseller = Reseller.objects.create(user=cls.user, account_limit=2)
cls.other = Reseller.objects.create(user=users.create_user("other"))
cls.allowed = HostingPlan.objects.create(name="Starter")
cls.unavailable = HostingPlan.objects.create(name="Other package")
cls.reseller.hosting_plans.add(cls.allowed)
HostingAccount.objects.create(
name="Existing hosting",
primary_domain="existing.example",
reseller=cls.reseller,
)
def setUp(self):
self.client.force_login(self.user)
self.create_url = reverse("panel:account_create")
def test_creation_uses_own_reseller_and_stops_at_limit(self):
payload = {
"name": "New hosting",
"primary_domain": "new.example",
"hosting_plan": self.allowed.pk,
}
response = self.client.post(
self.create_url, payload | {"reseller": self.other.pk}
)
account = HostingAccount.objects.get(primary_domain="new.example")
self.assertRedirects(response, account.get_absolute_url())
self.assertEqual(account.reseller_id, self.reseller.pk)
self.assertEqual(account.hosting_plan_id, self.allowed.pk)
overview = self.client.get(reverse("panel:accounts"))
self.assertContains(overview, "2 of 2 accounts allocated")
self.assertNotContains(overview, "Add hosting account")
response = self.client.post(
self.create_url, payload | {"primary_domain": "overflow.example"}
)
self.assertContains(response, "Your hosting account limit has been reached.")
self.assertFalse(
HostingAccount.objects.filter(primary_domain="overflow.example").exists()
)
def test_form_rejects_unavailable_or_missing_plan(self):
form = self.client.get(self.create_url)
self.assertContains(form, self.allowed.name)
self.assertNotContains(form, self.unavailable.name)
for plan in (self.unavailable.pk, ""):
with self.subTest(plan=plan):
response = self.client.post(
self.create_url,
{
"name": "Invalid hosting",
"primary_domain": "invalid.example",
"hosting_plan": plan,
},
)
self.assertIn("hosting_plan", response.context["form"].errors)
self.assertEqual(self.reseller.hostingaccount_set.count(), 1)
def test_plan_revoked_after_form_validation_is_rejected(self):
def revoke_before_create(access, account):
self.reseller.hosting_plans.remove(self.allowed)
create_reseller_account(access, account)
with patch(
"coulobre.hosting.views.create_reseller_account",
side_effect=revoke_before_create,
):
response = self.client.post(
self.create_url,
{
"name": "New hosting",
"primary_domain": "new.example",
"hosting_plan": self.allowed.pk,
},
)
self.assertContains(
response, "This hosting plan is no longer available to you."
)
self.assertEqual(self.reseller.hostingaccount_set.count(), 1)
def test_changed_reseller_owner_cannot_receive_an_in_flight_creation(self):
replacement = get_user_model().objects.create_user("replacement")
def change_owner_before_create(access, account):
Reseller.objects.filter(pk=access.pk).update(user=replacement)
create_reseller_account(access, account)
with patch(
"coulobre.hosting.views.create_reseller_account",
side_effect=change_owner_before_create,
):
response = self.client.post(
self.create_url,
{
"name": "New hosting",
"primary_domain": "new.example",
"hosting_plan": self.allowed.pk,
},
)
self.assertContains(response, "Your reseller access has changed.")
self.assertEqual(self.reseller.hostingaccount_set.count(), 1)
def test_operator_can_configure_limit_and_allowed_plans(self):
self.client.force_login(self.operator)
response = self.client.post(
reverse("admin:hosting_reseller_change", args=[self.reseller.pk]),
{
"user": self.user.pk,
"account_limit": 6,
"hosting_plans": [self.unavailable.pk],
},
)
self.assertRedirects(response, reverse("admin:hosting_reseller_changelist"))
self.reseller.refresh_from_db()
self.assertEqual(self.reseller.account_limit, 6)
self.assertEqual(list(self.reseller.hosting_plans.all()), [self.unavailable])
+11
View File
@@ -22,6 +22,17 @@ urlpatterns = [
path( path(
"accounts/<int:pk>/plans/", views.RequestWebPlan.as_view(), name="request_plan" "accounts/<int:pk>/plans/", views.RequestWebPlan.as_view(), name="request_plan"
), ),
path("hosting-plans/", views.HostingPlanList.as_view(), name="hosting_plans"),
path(
"hosting-plans/new/",
views.HostingPlanCreate.as_view(),
name="hosting_plan_create",
),
path(
"hosting-plans/<int:pk>/edit/",
views.HostingPlanEdit.as_view(),
name="hosting_plan_edit",
),
path("plans/", views.PlanList.as_view(), name="plans"), path("plans/", views.PlanList.as_view(), name="plans"),
path("plans/<int:pk>/", views.PlanDetail.as_view(), name="plan"), path("plans/<int:pk>/", views.PlanDetail.as_view(), name="plan"),
path( path(
+131 -19
View File
@@ -1,21 +1,30 @@
from django.contrib.auth.mixins import PermissionRequiredMixin from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import ValidationError
from django.db import IntegrityError
from django.db.models import Q from django.db.models import Q
from django.http import HttpResponse from django.http import HttpResponse
from django.shortcuts import redirect from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.views import View from django.views import View
from django.views.generic import CreateView, DetailView, ListView, UpdateView from django.views.generic import CreateView, DetailView, ListView, UpdateView
from django.views.generic.detail import SingleObjectMixin from django.views.generic.detail import SingleObjectMixin
from .models import HostingAccount, WebProvisioningPlan from .access import OperatorOnlyMixin, ResellerScopeMixin, reseller_for_user
from .models import HostingAccount, HostingPlan, WebProvisioningPlan
from .reseller_accounts import create_reseller_account
from .web_node import build_web_smoke_bundle, serialize_deployment_manifest from .web_node import build_web_smoke_bundle, serialize_deployment_manifest
VIEW_ACCOUNTS = "hosting.view_hostingaccount" VIEW_ACCOUNTS = "hosting.view_hostingaccount"
CHANGE_ACCOUNTS = "hosting.change_hostingaccount" CHANGE_ACCOUNTS = "hosting.change_hostingaccount"
VIEW_PLANS = "hosting.view_webprovisioningplan" VIEW_PLANS = "hosting.view_webprovisioningplan"
VIEW_HOSTING_PLANS = "hosting.view_hostingplan"
VIEW_RESELLERS = "hosting.view_reseller"
class AccountList(PermissionRequiredMixin, ListView): class AccountList(ResellerScopeMixin, PermissionRequiredMixin, ListView):
model = HostingAccount queryset = HostingAccount.objects.select_related("hosting_plan").order_by(
"primary_domain"
)
permission_required = VIEW_ACCOUNTS permission_required = VIEW_ACCOUNTS
template_name = "hosting/account_list.html" template_name = "hosting/account_list.html"
context_object_name = "accounts" context_object_name = "accounts"
@@ -23,7 +32,7 @@ class AccountList(PermissionRequiredMixin, ListView):
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]
accounts = HostingAccount.objects.order_by("primary_domain") accounts = super().get_queryset()
if self.search: if self.search:
accounts = accounts.filter( accounts = accounts.filter(
Q(name__icontains=self.search) Q(name__icontains=self.search)
@@ -32,45 +41,146 @@ class AccountList(PermissionRequiredMixin, ListView):
return accounts return accounts
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
return super().get_context_data(search=self.search, **kwargs) context = super().get_context_data(search=self.search, **kwargs)
reseller = reseller_for_user(self.request.user)
if reseller is not None and reseller.may_create_accounts():
context["account_allowance"] = {
"used": reseller.hostingaccount_set.count(),
"limit": reseller.account_limit,
}
return context
class AccountCreate(PermissionRequiredMixin, CreateView): class AccountEditor:
model = HostingAccount model = HostingAccount
permission_required = (VIEW_ACCOUNTS, "hosting.add_hostingaccount")
template_name = "hosting/account_form.html" template_name = "hosting/account_form.html"
fields = ("name", "primary_domain")
def get_form_class(self):
self.fields = ("name", "primary_domain")
reseller = reseller_for_user(self.request.user)
if reseller is not None or self.request.user.has_perm(VIEW_HOSTING_PLANS):
self.fields += ("hosting_plan",)
if reseller is None and 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:
field = form.fields["hosting_plan"]
reseller = reseller_for_user(self.request.user)
if reseller is None:
field.empty_label = "Unassigned"
else:
field.queryset = reseller.hosting_plans.all()
field.required = True
field.empty_label = "Select a hosting plan"
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):
permission_required = (VIEW_ACCOUNTS, "hosting.add_hostingaccount")
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):
reseller = reseller_for_user(self.request.user)
if reseller is not None:
return reseller.may_create_accounts()
return super().has_permission()
class AccountEdit(PermissionRequiredMixin, UpdateView): def form_valid(self, form):
model = HostingAccount reseller = reseller_for_user(self.request.user)
if reseller is None:
return super().form_valid(form)
self.object = form.save(commit=False)
try:
create_reseller_account(reseller, self.object)
except ValidationError as error:
form.add_error(None, error)
return self.form_invalid(form)
except IntegrityError:
if not HostingAccount.objects.filter(
primary_domain=self.object.primary_domain
).exists():
raise
form.add_error("primary_domain", "This domain is unavailable.")
return self.form_invalid(form)
return redirect(self.object)
class AccountEdit(
OperatorOnlyMixin, PermissionRequiredMixin, AccountEditor, UpdateView
):
permission_required = (VIEW_ACCOUNTS, CHANGE_ACCOUNTS) permission_required = (VIEW_ACCOUNTS, CHANGE_ACCOUNTS)
template_name = "hosting/account_form.html"
context_object_name = "account" context_object_name = "account"
fields = ("name", "primary_domain")
extra_context = { extra_context = {
"page_title": "Edit hosting account", "page_title": "Edit hosting account",
"submit_label": "Save changes", "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.object)
class AccountDetail(PermissionRequiredMixin, DetailView):
model = HostingAccount class AccountDetail(ResellerScopeMixin, PermissionRequiredMixin, DetailView):
queryset = HostingAccount.objects.select_related("hosting_plan", "reseller__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"
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super().get_context_data(**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( context["plans"] = self.object.webprovisioningplan_set.order_by(
"-requested_at", "-pk" "-requested_at", "-pk"
)[:10] )[:10]
return context return context
class RequestWebPlan(PermissionRequiredMixin, SingleObjectMixin, View): class HostingPlanList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
model = HostingPlan
permission_required = VIEW_HOSTING_PLANS
template_name = "hosting/hosting_plan_list.html"
context_object_name = "hosting_plans"
paginate_by = 20
class HostingPlanEditor:
model = HostingPlan
fields = ("name", "description")
template_name = "hosting/hosting_plan_form.html"
success_url = reverse_lazy("panel:hosting_plans")
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(
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(
OperatorOnlyMixin, PermissionRequiredMixin, SingleObjectMixin, View
):
model = HostingAccount model = HostingAccount
permission_required = (VIEW_ACCOUNTS, CHANGE_ACCOUNTS, VIEW_PLANS) permission_required = (VIEW_ACCOUNTS, CHANGE_ACCOUNTS, VIEW_PLANS)
@@ -80,24 +190,26 @@ class RequestWebPlan(PermissionRequiredMixin, SingleObjectMixin, View):
return redirect("panel:plan", pk=plan.pk) return redirect("panel:plan", pk=plan.pk)
class PlanList(PermissionRequiredMixin, ListView): class PlanList(ResellerScopeMixin, PermissionRequiredMixin, ListView):
queryset = WebProvisioningPlan.objects.select_related("account").order_by( queryset = WebProvisioningPlan.objects.select_related("account").order_by(
"-requested_at", "-pk" "-requested_at", "-pk"
) )
permission_required = VIEW_PLANS permission_required = VIEW_PLANS
reseller_relation = "account__reseller"
template_name = "hosting/plan_list.html" template_name = "hosting/plan_list.html"
context_object_name = "plans" context_object_name = "plans"
paginate_by = 20 paginate_by = 20
class PlanDetail(PermissionRequiredMixin, DetailView): class PlanDetail(ResellerScopeMixin, 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"
template_name = "hosting/plan_detail.html" template_name = "hosting/plan_detail.html"
context_object_name = "plan" context_object_name = "plan"
class DownloadWebPlan(PlanDetail): class DownloadWebPlan(OperatorOnlyMixin, PlanDetail):
manifest = False manifest = False
def render_to_response(self, context, **response_kwargs): def render_to_response(self, context, **response_kwargs):
+2 -1
View File
@@ -18,7 +18,7 @@ ALLOWED_HOSTS = os.environ.get(
).split(",") ).split(",")
INSTALLED_APPS = [ INSTALLED_APPS = [
"django.contrib.admin", "coulobre.admin.CoulobreAdminConfig",
"django.contrib.auth", "django.contrib.auth",
"django.contrib.contenttypes", "django.contrib.contenttypes",
"django.contrib.sessions", "django.contrib.sessions",
@@ -47,6 +47,7 @@ TEMPLATES = [
"django.template.context_processors.request", "django.template.context_processors.request",
"django.contrib.auth.context_processors.auth", "django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages", "django.contrib.messages.context_processors.messages",
"coulobre.hosting.access.panel_access",
], ],
}, },
}, },