diff --git a/docs/development.md b/docs/development.md index bbaab14..907f516 100644 --- a/docs/development.md +++ b/docs/development.md @@ -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 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 different file. Keep `COULOBRE_DEBUG` for local development. diff --git a/src/coulobre/admin.py b/src/coulobre/admin.py new file mode 100644 index 0000000..59e9741 --- /dev/null +++ b/src/coulobre/admin.py @@ -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" diff --git a/src/coulobre/hosting/access.py b/src/coulobre/hosting/access.py new file mode 100644 index 0000000..05b7d51 --- /dev/null +++ b/src/coulobre/hosting/access.py @@ -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 diff --git a/src/coulobre/hosting/admin.py b/src/coulobre/hosting/admin.py index 395052b..43439ae 100644 --- a/src/coulobre/hosting/admin.py +++ b/src/coulobre/hosting/admin.py @@ -1,7 +1,7 @@ from django.contrib import admin from django.utils.html import format_html -from .models import HostingAccount, WebProvisioningPlan +from .models import HostingAccount, HostingPlan, Reseller, WebProvisioningPlan @admin.register(HostingAccount) @@ -11,6 +11,20 @@ class HostingAccountAdmin(admin.ModelAdmin): ordering = ("primary_domain",) 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") def request_web_plans(self, request, queryset): plans = WebProvisioningPlan.objects.bulk_create( @@ -20,6 +34,26 @@ class HostingAccountAdmin(admin.ModelAdmin): 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) class WebProvisioningPlanAdmin(admin.ModelAdmin): list_display = ("primary_domain", "account", "requested_at", "completed_at") diff --git a/src/coulobre/hosting/migrations/0003_hostingplan_hostingaccount_hosting_plan.py b/src/coulobre/hosting/migrations/0003_hostingplan_hostingaccount_hosting_plan.py new file mode 100644 index 0000000..12fbd4f --- /dev/null +++ b/src/coulobre/hosting/migrations/0003_hostingplan_hostingaccount_hosting_plan.py @@ -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", + ), + ), + ] diff --git a/src/coulobre/hosting/migrations/0004_reseller_hostingaccount_reseller.py b/src/coulobre/hosting/migrations/0004_reseller_hostingaccount_reseller.py new file mode 100644 index 0000000..385b22a --- /dev/null +++ b/src/coulobre/hosting/migrations/0004_reseller_hostingaccount_reseller.py @@ -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", + ), + ), + ] diff --git a/src/coulobre/hosting/migrations/0005_reseller_account_limit_reseller_hosting_plans.py b/src/coulobre/hosting/migrations/0005_reseller_account_limit_reseller_hosting_plans.py new file mode 100644 index 0000000..7653dc4 --- /dev/null +++ b/src/coulobre/hosting/migrations/0005_reseller_account_limit_reseller_hosting_plans.py @@ -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"), + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 23eb19a..9336f68 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -1,12 +1,47 @@ +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}, + ) + 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): name = models.CharField(max_length=120) 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) def get_absolute_url(self): diff --git a/src/coulobre/hosting/reseller_accounts.py b/src/coulobre/hosting/reseller_accounts.py new file mode 100644 index 0000000..f685312 --- /dev/null +++ b/src/coulobre/hosting/reseller_accounts.py @@ -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) diff --git a/src/coulobre/hosting/static/hosting/panel.css b/src/coulobre/hosting/static/hosting/panel.css index 4985ffe..986d254 100644 --- a/src/coulobre/hosting/static/hosting/panel.css +++ b/src/coulobre/hosting/static/hosting/panel.css @@ -29,7 +29,7 @@ a { text-underline-offset: 0.2em; } -button, input { +button, input, select { font: inherit; } @@ -155,6 +155,10 @@ button, input { 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 { display: grid; gap: 0.3rem; @@ -288,7 +292,7 @@ h2 { font-size: 0.88rem; } -input:not([type="hidden"]) { +input:not([type="hidden"]), select { min-width: 0; height: 2.55rem; padding: 0.48rem 0.68rem; @@ -463,7 +467,7 @@ dd { font-weight: 680; } -.editor input:not([type="hidden"]) { +.editor input:not([type="hidden"]), .editor select { width: 100%; } diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index 2865053..248e494 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -7,19 +7,25 @@

{{ account.name }}

{{ account.primary_domain }}

- {% if perms.hosting.change_hostingaccount %} + {% if not is_reseller and perms.hosting.change_hostingaccount %} Edit account {% endif %}
Primary domain
{{ account.primary_domain }}
+ {% if is_reseller or perms.hosting.view_hostingplan %} +
Hosting plan
{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}Unassigned{% endif %}
+ {% endif %} + {% if not is_reseller and perms.hosting.view_reseller %} +
Reseller
{{ account.reseller|default_if_none:"Unassigned" }}
+ {% endif %}
Added
{{ account.created_at|date:"j M Y, H:i" }} UTC
- {% if perms.hosting.view_webprovisioningplan %} + {% if is_reseller or perms.hosting.view_webprovisioningplan %}

Recent Apache previews

- {% if perms.hosting.change_hostingaccount %} + {% if not is_reseller and perms.hosting.change_hostingaccount %}
{% csrf_token %} diff --git a/src/coulobre/hosting/templates/hosting/account_list.html b/src/coulobre/hosting/templates/hosting/account_list.html index 51936b4..ba3a507 100644 --- a/src/coulobre/hosting/templates/hosting/account_list.html +++ b/src/coulobre/hosting/templates/hosting/account_list.html @@ -5,8 +5,9 @@

Hosting accounts

{{ paginator.count }} account{{ paginator.count|pluralize }}{% if search %} matching your search{% endif %}

+ {% if account_allowance %}

{{ account_allowance.used }} of {{ account_allowance.limit }} accounts allocated

{% endif %}
- {% if perms.hosting.add_hostingaccount %} + {% if account_allowance and account_allowance.used < account_allowance.limit or not is_reseller and perms.hosting.add_hostingaccount %} Add hosting account {% endif %}
@@ -21,13 +22,21 @@
- + + + + {% if is_reseller or perms.hosting.view_hostingplan %}{% endif %} + + {% for account in accounts %} + {% if is_reseller or perms.hosting.view_hostingplan %} + + {% endif %} {% endfor %} diff --git a/src/coulobre/hosting/templates/hosting/base.html b/src/coulobre/hosting/templates/hosting/base.html index 7e39373..4b8b73a 100644 --- a/src/coulobre/hosting/templates/hosting/base.html +++ b/src/coulobre/hosting/templates/hosting/base.html @@ -17,13 +17,19 @@
AccountPrimary domainAdded
AccountPrimary domainHosting planAdded
{{ account.name }} {{ account.primary_domain }}{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}Unassigned{% endif %}{{ account.created_at|date:"j M Y" }}
+ + + {% for hosting_plan in hosting_plans %} + + + + + {% endfor %} + +
PlanDescription
+ {% if perms.hosting.change_hostingplan %} + {{ hosting_plan.name }} + {% else %} + {{ hosting_plan.name }} + {% endif %} + {{ hosting_plan.description|default:"—" }}
+
+ {% else %} +

No hosting plans yet.

+ {% endif %} + {% include "hosting/pagination.html" %} +
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/plan_detail.html b/src/coulobre/hosting/templates/hosting/plan_detail.html index 6978de0..ea8d91b 100644 --- a/src/coulobre/hosting/templates/hosting/plan_detail.html +++ b/src/coulobre/hosting/templates/hosting/plan_detail.html @@ -13,7 +13,7 @@
Status
{% include "hosting/plan_status.html" %}
-
Hosting account
{% if perms.hosting.view_hostingaccount %}{{ plan.account.name }}{% else %}{{ plan.account.name }}{% endif %}
+
Hosting account
{% if is_reseller or perms.hosting.view_hostingaccount %}{{ plan.account.name }}{% else %}{{ plan.account.name }}{% endif %}
Requested
{{ plan.requested_at|date:"j M Y, H:i" }} UTC
{% if plan.primary_domain != plan.account.primary_domain %} @@ -23,7 +23,7 @@

Virtual host configuration

- {% if plan.can_export %} + {% if not is_reseller and plan.can_export %}
Download deployment manifest Download test bundle diff --git a/src/coulobre/hosting/test_hosting_plans.py b/src/coulobre/hosting/test_hosting_plans.py new file mode 100644 index 0000000..7a3e745 --- /dev/null +++ b/src/coulobre/hosting/test_hosting_plans.py @@ -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() diff --git a/src/coulobre/hosting/test_resellers.py b/src/coulobre/hosting/test_resellers.py new file mode 100644 index 0000000..0952322 --- /dev/null +++ b/src/coulobre/hosting/test_resellers.py @@ -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()), "
bob
", 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]) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 71f798b..dc62262 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -22,6 +22,17 @@ urlpatterns = [ path( "accounts//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//edit/", + views.HostingPlanEdit.as_view(), + name="hosting_plan_edit", + ), path("plans/", views.PlanList.as_view(), name="plans"), path("plans//", views.PlanDetail.as_view(), name="plan"), path( diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 8337bb0..bd464bd 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -1,21 +1,30 @@ 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.http import HttpResponse from django.shortcuts import redirect +from django.urls import reverse_lazy from django.views import View from django.views.generic import CreateView, DetailView, ListView, UpdateView 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 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" @@ -23,7 +32,7 @@ class AccountList(PermissionRequiredMixin, ListView): def get_queryset(self): self.search = self.request.GET.get("q", "").strip()[:253] - accounts = HostingAccount.objects.order_by("primary_domain") + accounts = super().get_queryset() if self.search: accounts = accounts.filter( Q(name__icontains=self.search) @@ -32,45 +41,146 @@ class AccountList(PermissionRequiredMixin, ListView): return accounts 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 - permission_required = (VIEW_ACCOUNTS, "hosting.add_hostingaccount") 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"} + 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): - model = HostingAccount + def form_valid(self, form): + 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) - template_name = "hosting/account_form.html" context_object_name = "account" - fields = ("name", "primary_domain") extra_context = { "page_title": "Edit hosting account", "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 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 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 permission_required = (VIEW_ACCOUNTS, CHANGE_ACCOUNTS, VIEW_PLANS) @@ -80,24 +190,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): diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index d6ce52e..aa19cac 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -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", ], }, },