diff --git a/docs/development.md b/docs/development.md index 95d7833..907f516 100644 --- a/docs/development.md +++ b/docs/development.md @@ -30,9 +30,17 @@ 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. Platform -operators manage assignments and node deployment files. Reseller access in -this release is read-only. +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/hosting/admin.py b/src/coulobre/hosting/admin.py index 24ad0b5..43439ae 100644 --- a/src/coulobre/hosting/admin.py +++ b/src/coulobre/hosting/admin.py @@ -42,9 +42,16 @@ class HostingPlanAdmin(admin.ModelAdmin): @admin.register(Reseller) class ResellerAdmin(admin.ModelAdmin): - list_display = ("user",) + 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) 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 a33b4d6..9336f68 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -12,6 +12,11 @@ class Reseller(models.Model): 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() 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/templates/hosting/account_list.html b/src/coulobre/hosting/templates/hosting/account_list.html index 748ca07..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 not is_reseller and 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 %} diff --git a/src/coulobre/hosting/test_resellers.py b/src/coulobre/hosting/test_resellers.py index 7f89566..0952322 100644 --- a/src/coulobre/hosting/test_resellers.py +++ b/src/coulobre/hosting/test_resellers.py @@ -1,9 +1,12 @@ +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 @@ -130,3 +133,126 @@ class ResellerAccessTests(TestCase): 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/views.py b/src/coulobre/hosting/views.py index 62ce161..bd464bd 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -1,4 +1,6 @@ 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 @@ -9,6 +11,7 @@ from django.views.generic.detail import SingleObjectMixin 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" @@ -38,7 +41,14 @@ class AccountList(ResellerScopeMixin, 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 AccountEditor: @@ -47,16 +57,24 @@ class AccountEditor: def get_form_class(self): self.fields = ("name", "primary_domain") - if self.request.user.has_perm(VIEW_HOSTING_PLANS): + 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 self.request.user.has_perm(VIEW_RESELLERS): + 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: - form.fields["hosting_plan"].empty_label = "Unassigned" + 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 = ( @@ -67,12 +85,36 @@ class AccountEditor: return form -class AccountCreate( - OperatorOnlyMixin, PermissionRequiredMixin, AccountEditor, CreateView -): +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() + + 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