diff --git a/src/coulobre/hosting/admin.py b/src/coulobre/hosting/admin.py index 30acb90..9763dc7 100644 --- a/src/coulobre/hosting/admin.py +++ b/src/coulobre/hosting/admin.py @@ -77,7 +77,7 @@ class HostingPlanAdmin(admin.ModelAdmin): @admin.register(Reseller) class ResellerAdmin(admin.ModelAdmin): - list_display = ("user", "account_limit") + list_display = ("user", "account_limit", "manage_resources") list_select_related = ("user",) search_fields = ("user__username",) filter_horizontal = ("hosting_plans",) @@ -91,10 +91,21 @@ class ResellerAdmin(admin.ModelAdmin): @admin.register(Customer) class CustomerAdmin(admin.ModelAdmin): - list_display = ("user",) - list_select_related = ("user",) + list_display = ("user", "reseller") + list_select_related = ("user", "reseller__user") search_fields = ("user__username",) + def get_list_display(self, request): + if not request.user.has_perm("hosting.view_reseller"): + return ("user",) + return super().get_list_display(request) + + def get_exclude(self, request, obj=None): + excluded = list(super().get_exclude(request, obj) or ()) + if not request.user.has_perm("hosting.view_reseller"): + excluded.append("reseller") + return excluded + @admin.register(CustomerImpersonation) class CustomerImpersonationAdmin(admin.ModelAdmin): diff --git a/src/coulobre/hosting/migrations/0046_reseller_onboarding.py b/src/coulobre/hosting/migrations/0046_reseller_onboarding.py new file mode 100644 index 0000000..b8bf00d --- /dev/null +++ b/src/coulobre/hosting/migrations/0046_reseller_onboarding.py @@ -0,0 +1,52 @@ +# Generated by Django 5.2.19 on 2026-11-22 10:39 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0045_panel_authentication"), + ] + + operations = [ + migrations.AddField( + model_name="customer", + name="reseller", + field=models.ForeignKey( + blank=True, + null=True, + on_delete=django.db.models.deletion.SET_NULL, + related_name="managed_customers", + to="hosting.reseller", + ), + ), + migrations.AddField( + model_name="reseller", + name="manage_resources", + field=models.BooleanField( + default=False, + help_text=( + "Allow database and mailbox requests and provisioning." + ), + ), + ), + migrations.AlterField( + model_name="resellerauditevent", + name="action", + field=models.CharField( + choices=[ + ("create", "Created reseller"), + ("update", "Updated reseller"), + ("assign", "Assigned hosting account"), + ("unassign", "Unassigned hosting account"), + ("plan", "Changed hosting account plan"), + ("cust_add", "Created customer login"), + ("cust_lnk", "Linked customer login"), + ("request", "Requested hosting resource"), + ("deploy", "Queued resource provisioning"), + ], + max_length=8, + ), + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index f7f3cb8..02214f4 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -55,6 +55,10 @@ class Reseller(models.Model): }, ) account_limit = models.PositiveIntegerField(default=0) + manage_resources = models.BooleanField( + default=False, + help_text="Allow database and mailbox requests and provisioning.", + ) hosting_plans = models.ManyToManyField("HostingPlan", blank=True) def __str__(self): @@ -74,6 +78,10 @@ class ResellerAuditEvent(models.Model): ASSIGN = "assign", "Assigned hosting account" UNASSIGN = "unassign", "Unassigned hosting account" PLAN = "plan", "Changed hosting account plan" + CUSTOMER_CREATE = "cust_add", "Created customer login" + CUSTOMER_LINK = "cust_lnk", "Linked customer login" + RESOURCE_REQUEST = "request", "Requested hosting resource" + RESOURCE_PROVISION = "deploy", "Queued resource provisioning" reseller = models.ForeignKey( Reseller, @@ -104,6 +112,14 @@ class Customer(models.Model): }, ) + reseller = models.ForeignKey( + Reseller, + on_delete=models.SET_NULL, + null=True, + blank=True, + related_name="managed_customers", + ) + def __str__(self): return self.user.get_username() @@ -663,11 +679,12 @@ class WebProvisioningPlan(models.Model): class ProvisioningJobManager(models.Manager): def queue(self, **target): job, created = self.get_or_create(**target) - if not created: + return created or bool( self.requeue(self.filter(pk=job.pk).exclude(problem="")) + ) def requeue(self, jobs, **updates): - jobs.filter(finished_at__isnull=False).update( + return jobs.filter(finished_at__isnull=False).update( requested_at=timezone.now(), last_dispatched_at=None, started_at=None, diff --git a/src/coulobre/hosting/reseller_accounts.py b/src/coulobre/hosting/reseller_accounts.py index f64b884..974c781 100644 --- a/src/coulobre/hosting/reseller_accounts.py +++ b/src/coulobre/hosting/reseller_accounts.py @@ -29,6 +29,7 @@ def plan_reference(plan): def policy_snapshot(reseller): return { "account_limit": reseller.account_limit, + "manage_resources": reseller.manage_resources, "hosting_plans": [ plan_reference(plan) for plan in reseller.hosting_plans.order_by("pk") @@ -70,7 +71,9 @@ def create_reseller(login_form, policy, actor): user.is_active = policy["is_active"] user.save() reseller = Reseller.objects.create( - user=user, account_limit=policy["account_limit"] + user=user, + account_limit=policy["account_limit"], + manage_resources=policy.get("manage_resources", False), ) if "hosting_plans" in policy: reseller.hosting_plans.set(policy["hosting_plans"]) @@ -102,6 +105,9 @@ def update_reseller(reseller_id, policy, actor): if reseller.account_limit != policy["account_limit"]: reseller.account_limit = policy["account_limit"] reseller.save(update_fields=["account_limit"]) + if "manage_resources" in policy: + reseller.manage_resources = policy["manage_resources"] + reseller.save(update_fields=["manage_resources"]) if "hosting_plans" in policy: reseller.hosting_plans.set(policy["hosting_plans"]) changes = policy_changes(before, policy_snapshot(reseller)) diff --git a/src/coulobre/hosting/reseller_onboarding.py b/src/coulobre/hosting/reseller_onboarding.py new file mode 100644 index 0000000..0c7e4d7 --- /dev/null +++ b/src/coulobre/hosting/reseller_onboarding.py @@ -0,0 +1,109 @@ +from django.core.exceptions import PermissionDenied, ValidationError +from django.db import transaction + +from .access import reseller_for_user +from .models import Customer, HostingAccount, Reseller, ResellerAuditEvent +from .reseller_accounts import lock_resellers, record_event +from .resource_requests import lock_hosting_account, require_open_account + +Action = ResellerAuditEvent.Action + + +def scoped_customers(reseller): + return reseller.managed_customers.filter( + user__is_staff=False, + user__is_superuser=False, + user__hosting_reseller__isnull=True, + ) + + +def lock_reseller_account(access, account_id, *, resources=False): + account = lock_hosting_account(account_id, customer_id=None) + if account.reseller_id != access.pk: + raise HostingAccount.DoesNotExist + reseller = lock_resellers( + Reseller.objects.filter(pk=access.pk, user_id=access.user_id) + ).first() + if ( + reseller is None + or not reseller.user.is_active + or reseller_for_user(reseller.user) is None + ): + raise PermissionDenied + if resources and not reseller.manage_resources: + raise PermissionDenied + require_open_account(account) + return account, reseller + + +def require_unassigned_customer(account): + if account.customer_id is not None: + raise ValidationError("This hosting account already has a customer.") + + +@transaction.atomic +def create_reseller_customer(access, account_id, form): + account, reseller = lock_reseller_account(access, account_id) + require_unassigned_customer(account) + customer = Customer.objects.create(user=form.save(), reseller=reseller) + save_customer_link(account, reseller, customer, Action.CUSTOMER_CREATE) + return account + + +@transaction.atomic +def link_reseller_customer(access, account_id, customer_id): + account, reseller = lock_reseller_account(access, account_id) + require_unassigned_customer(account) + customer = ( + scoped_customers(reseller) + .select_for_update() + .filter(pk=customer_id, user__is_active=True) + .first() + ) + if customer is None: + raise ValidationError("This customer is no longer available.") + save_customer_link(account, reseller, customer, Action.CUSTOMER_LINK) + return account + + +def save_customer_link(account, reseller, customer, action): + account.customer = customer + account.save(update_fields=["customer"]) + record_event( + reseller, + reseller.user.get_username(), + action, + {"customer": str(customer)}, + account_domain=account.primary_domain, + ) + + +@transaction.atomic +def request_reseller_resource(access, account_id, create, values): + account, reseller = lock_reseller_account( + access, account_id, resources=True + ) + resource = create(account.pk, **values) + record_resource_event(reseller, account, Action.RESOURCE_REQUEST, resource) + return resource + + +@transaction.atomic +def provision_reseller_resource(access, account_id, provision, resource): + account, reseller = lock_reseller_account( + access, account_id, resources=True + ) + if provision(resource): + record_resource_event( + reseller, account, Action.RESOURCE_PROVISION, resource + ) + + +def record_resource_event(reseller, account, action, resource): + record_event( + reseller, + reseller.user.get_username(), + action, + {"resource": str(resource), "type": resource._meta.verbose_name}, + account_domain=account.primary_domain, + ) diff --git a/src/coulobre/hosting/reseller_onboarding_views.py b/src/coulobre/hosting/reseller_onboarding_views.py new file mode 100644 index 0000000..fab3681 --- /dev/null +++ b/src/coulobre/hosting/reseller_onboarding_views.py @@ -0,0 +1,119 @@ +from django import forms +from django.contrib.auth import get_user_model +from django.contrib.auth.forms import UserCreationForm +from django.contrib.auth.mixins import PermissionRequiredMixin +from django.core.exceptions import ValidationError +from django.db import IntegrityError +from django.http import Http404 +from django.shortcuts import get_object_or_404, redirect +from django.utils.decorators import method_decorator +from django.utils.functional import cached_property +from django.views.decorators.debug import sensitive_post_parameters +from django.views.generic import FormView + +from .access import reseller_for_user +from .models import HostingAccount +from .reseller_onboarding import ( + create_reseller_customer, + link_reseller_customer, + scoped_customers, +) + + +class ResellerCustomerLoginForm(UserCreationForm): + email = forms.EmailField( + required=False, + help_text="Used for customer password recovery when enabled.", + ) + + class Meta(UserCreationForm.Meta): + fields = ("username", "email") + + +class ResellerCustomerLinkForm(forms.Form): + customer = forms.ModelChoiceField(queryset=None) + + def __init__(self, *args, customers, **kwargs): + super().__init__(*args, **kwargs) + self.fields["customer"].queryset = customers + + +class ResellerCustomerEditor(PermissionRequiredMixin, FormView): + template_name = "hosting/customer_form.html" + + @cached_property + def reseller(self): + return reseller_for_user(self.request.user) + + @cached_property + def account(self): + return get_object_or_404( + HostingAccount, + pk=self.kwargs["pk"], + reseller=self.reseller, + retired_at__isnull=True, + customer__isnull=True, + ) + + def has_permission(self): + return self.reseller is not None + + def get_context_data(self, **kwargs): + return super().get_context_data(account=self.account, **kwargs) + + +@method_decorator( + sensitive_post_parameters("password1", "password2"), name="dispatch" +) +class ResellerCustomerCreate(ResellerCustomerEditor): + form_class = ResellerCustomerLoginForm + extra_context = {"title": "Add customer login"} + + def form_valid(self, form): + account = self.account + try: + account = create_reseller_customer(self.reseller, account.pk, form) + except HostingAccount.DoesNotExist as error: + raise Http404 from error + except ValidationError as error: + form.add_error(None, error) + return self.form_invalid(form) + except IntegrityError: + user = form.instance + if ( + not get_user_model() + .objects.filter(username__iexact=user.username) + .exists() + ): + raise + form.add_error( + "username", user.unique_error_message(type(user), ["username"]) + ) + return self.form_invalid(form) + return redirect(account) + + +class ResellerCustomerLink(ResellerCustomerEditor): + form_class = ResellerCustomerLinkForm + extra_context = {"title": "Link existing customer"} + + def get_form_kwargs(self): + return super().get_form_kwargs() | { + "customers": scoped_customers(self.reseller) + .filter(user__is_active=True) + .select_related("user") + .order_by("user__username") + } + + def form_valid(self, form): + account = self.account + try: + account = link_reseller_customer( + self.reseller, account.pk, form.cleaned_data["customer"].pk + ) + except HostingAccount.DoesNotExist as error: + raise Http404 from error + except ValidationError as error: + form.add_error(None, error) + return self.form_invalid(form) + return redirect(account) diff --git a/src/coulobre/hosting/reseller_views.py b/src/coulobre/hosting/reseller_views.py index 826a10b..5487305 100644 --- a/src/coulobre/hosting/reseller_views.py +++ b/src/coulobre/hosting/reseller_views.py @@ -33,8 +33,16 @@ class ResellerPolicyForm(forms.ModelForm): class Meta: model = Reseller - fields = ("is_active", "account_limit", "hosting_plans") - labels = {"hosting_plans": "Allowed hosting plans"} + fields = ( + "is_active", + "account_limit", + "hosting_plans", + "manage_resources", + ) + labels = { + "hosting_plans": "Allowed hosting plans", + "manage_resources": "Manage databases and mailboxes", + } help_texts = { "account_limit": "Enter 0 to stop self-service account creation.", "hosting_plans": ( diff --git a/src/coulobre/hosting/resource_requests.py b/src/coulobre/hosting/resource_requests.py index c584c5c..192946b 100644 --- a/src/coulobre/hosting/resource_requests.py +++ b/src/coulobre/hosting/resource_requests.py @@ -95,7 +95,7 @@ def queue_mailbox_provisioning(mailbox): mailbox.mail_domain.account_id, customer_id=None ) require_active_services(account) - MailboxProvisioning.objects.queue(mailbox=mailbox) + return MailboxProvisioning.objects.queue(mailbox=mailbox) @transaction.atomic @@ -200,7 +200,7 @@ def require_active_services(account): def queue_database_provisioning(database): account = lock_hosting_account(database.account_id, customer_id=None) require_active_services(account) - DatabaseProvisioning.objects.queue(database=database) + return DatabaseProvisioning.objects.queue(database=database) @transaction.atomic diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index f149fa5..a93e5fb 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -39,6 +39,21 @@ {% endif %} {% if is_operator and perms.hosting.view_customer %}
| Database | {% if is_operator %}Deployment | {% endif %}||
|---|---|---|---|
| Database | {% if is_operator or manage_database_provisioning %}Deployment | {% endif %}||
|
- Download manifest
+ {% if is_operator %}
+ Download manifest
+ {% endif %}
{% if manage_database_provisioning %}
{% url 'panel:database_provision' database.pk as provision_url %}
{% include "hosting/resource_provisioning.html" with provisioning=database.provisioning enabled=local_database_enabled action=provision_url resource=database provision_label="Provision database" %}
{% endif %}
- {% if manage_database_provisioning and database.provisioning.problem %}
+ {% if is_operator and manage_database_provisioning and database.provisioning.problem %}
{% endif %}
|
@@ -231,7 +248,7 @@
{% endif %}
{% endif %}
- {% if is_customer or is_operator and perms.hosting.add_hostingmailbox %}
+ {% if is_customer or reseller_resource_management or is_operator and perms.hosting.add_hostingmailbox %}
Request mailbox
{% endif %}
@@ -242,7 +259,7 @@
|||
| Email address | Storage limit | - {% if is_operator %}Deployment | {% endif %} + {% if is_operator or manage_mailbox_provisioning %}Deployment | {% endif %}{% if mailbox.quota_mib is not None %}{{ mailbox.quota_mib }} MiB{% else %}Unlimited{% endif %} | - {% if is_operator %} + {% if is_operator or manage_mailbox_provisioning %}
- Download manifest
+ {% if is_operator %}
+ Download manifest
+ {% endif %}
{% if change_mailbox_quota %}
Change storage limit
{% endif %}
@@ -276,7 +295,7 @@
{% include "hosting/resource_provisioning.html" with provisioning=mailbox.provisioning enabled=local_mailbox_enabled action=provision_url resource=mailbox provision_label="Provision mailbox" %}
{% endif %}
- {% if manage_mailbox_provisioning and mailbox.provisioning.problem %}
+ {% if is_operator and manage_mailbox_provisioning and mailbox.provisioning.problem %}
{% endif %}
|
diff --git a/src/coulobre/hosting/templates/hosting/base.html b/src/coulobre/hosting/templates/hosting/base.html
index c82d43f..c966d73 100644
--- a/src/coulobre/hosting/templates/hosting/base.html
+++ b/src/coulobre/hosting/templates/hosting/base.html
@@ -27,7 +27,7 @@
Hosting accounts
{% endif %}
- {% if is_operator and perms.hosting.view_customer %}
+ {% if is_reseller or is_operator and perms.hosting.view_customer %}
Customers
diff --git a/src/coulobre/hosting/templates/hosting/customer_form.html b/src/coulobre/hosting/templates/hosting/customer_form.html
index 23c90e4..273cd8d 100644
--- a/src/coulobre/hosting/templates/hosting/customer_form.html
+++ b/src/coulobre/hosting/templates/hosting/customer_form.html
@@ -1,15 +1,23 @@
{% extends "hosting/base.html" %}
-{% block title %}Add customer · Coulobre Panel{% endblock %}
+{% block title %}{{ title|default:"Add customer" }} · Coulobre Panel{% endblock %}
{% block content %}
- ← Customers
-
| Username | Sign-in status | - {% if perms.hosting.change_customer or can_impersonate %}Actions | {% endif %} + {% if is_operator and perms.hosting.change_customer or can_impersonate %}Actions | {% endif %}
{% if perms.hosting.change_customer and not customer.user.is_staff and not customer.user.is_superuser and not customer.user.hosting_reseller %}
@@ -67,6 +67,8 @@
{% elif search %}
No customers match this search. + {% elif is_reseller %} +Open an unassigned hosting account to add a customer login. {% else %}No customers yet. {% endif %} diff --git a/src/coulobre/hosting/templates/hosting/reseller_detail.html b/src/coulobre/hosting/templates/hosting/reseller_detail.html index e906357..909307c 100644 --- a/src/coulobre/hosting/templates/hosting/reseller_detail.html +++ b/src/coulobre/hosting/templates/hosting/reseller_detail.html @@ -10,6 +10,7 @@
@@ -67,6 +68,11 @@
{% if event.changes.account_limit %}
Account limit {{ event.changes.account_limit.before|default_if_none:"—" }} → {{ event.changes.account_limit.after }}
{% endif %}
+ {% if event.changes.customer %}{{ event.changes.customer }} {% endif %}
+ {% if event.changes.resource %}{{ event.changes.type|capfirst }} {{ event.changes.resource }} {% endif %}
+ {% if event.changes.manage_resources %}
+ Database and mailbox management {{ event.changes.manage_resources.before|yesno:"allowed,operator only,—" }} → {{ event.changes.manage_resources.after|yesno:"allowed,operator only" }}
+ {% endif %}
{% if event.changes.is_active %}
Panel sign-in {{ event.changes.is_active.before|yesno:"active,suspended,—" }} → {{ event.changes.is_active.after|yesno:"active,suspended" }}
{% endif %}
diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py
index 9baa78a..913d32e 100644
--- a/src/coulobre/hosting/urls.py
+++ b/src/coulobre/hosting/urls.py
@@ -14,6 +14,10 @@ from .password_reset import (
CustomerResetDoneView,
)
from .phpmyadmin import PhpMyAdminLaunch, redeem_phpmyadmin
+from .reseller_onboarding_views import (
+ ResellerCustomerCreate,
+ ResellerCustomerLink,
+)
from .reseller_views import (
ResellerCreate,
ResellerDetail,
@@ -73,6 +77,16 @@ urlpatterns = [
name="account_retirement",
),
path("accounts/ |