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 %}
Customer
{{ account.customer|default_if_none:"Unassigned" }}
+ {% elif is_reseller %} +
Customer
+
+ {% if account.customer_id %} + {% if account.customer.reseller_id == account.reseller_id %} + {{ account.customer }} + {% else %}Assigned{% endif %} + {% else %} + Add customer login + {% if reseller_customer_link %} + Link existing customer + {% endif %} + {% endif %} +
+
{% endif %}
Added
{{ account.created_at|date:"j M Y, H:i" }} UTC
@@ -92,14 +107,14 @@ {% endif %} {% endif %} - {% if is_customer or is_operator and perms.hosting.add_hostingdatabase %} + {% if is_customer or reseller_resource_management or is_operator and perms.hosting.add_hostingdatabase %} Request database {% endif %} {% if databases %}
- {% if is_operator %}{% endif %} + {% if is_operator or manage_database_provisioning %}{% endif %} {% for database in databases %} @@ -115,16 +130,18 @@ {% endif %} - {% if is_operator %} + {% if is_operator or manage_database_provisioning %} @@ -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 @@ - {% if is_operator %}{% endif %} + {% if is_operator or manage_mailbox_provisioning %}{% endif %} @@ -264,10 +281,12 @@ {% endif %} - {% if is_operator %} + {% if is_operator or manage_mailbox_provisioning %} 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 -

Add customer

+ {% if account %} + ← {{ account.name }} + {% else %} + ← Customers + {% endif %} +

{{ title|default:"Add customer" }}

{% csrf_token %} {{ form.as_div }}
- - Cancel + + {% if account %} + Cancel + {% else %} + Cancel + {% endif %}
diff --git a/src/coulobre/hosting/templates/hosting/customer_list.html b/src/coulobre/hosting/templates/hosting/customer_list.html index 1e67d59..080c433 100644 --- a/src/coulobre/hosting/templates/hosting/customer_list.html +++ b/src/coulobre/hosting/templates/hosting/customer_list.html @@ -3,7 +3,7 @@ {% block content %}

Customers

- {% if perms.hosting.add_customer %} + {% if is_operator and perms.hosting.add_customer %} Add customer {% endif %}
@@ -21,7 +21,7 @@ - {% if perms.hosting.change_customer or can_impersonate %}{% endif %} + {% if is_operator and perms.hosting.change_customer or can_impersonate %}{% endif %} @@ -32,7 +32,7 @@ {% if customer.user.is_active %}Active {% else %}Suspended{% endif %} - {% if perms.hosting.change_customer or can_impersonate %} + {% if is_operator and perms.hosting.change_customer or can_impersonate %}
DatabaseDeployment
DatabaseDeployment
- 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 %}

{{ database.provisioning.problem }}

{% endif %}
Email address Storage limitDeploymentDeployment
{% if mailbox.quota_mib is not None %}{{ mailbox.quota_mib }} MiB{% else %}Unlimited{% endif %}
- 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 %}

{{ mailbox.provisioning.problem }}

{% endif %}
Username Sign-in statusActionsActions
{% 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 @@
Panel sign-in
{{ reseller.user.is_active|yesno:"Active,Suspended" }}
+
Database and mailbox management
{{ reseller.manage_resources|yesno:"Allowed,Operator only" }}
Accounts allocated
{{ account_count }} of {{ reseller.account_limit }}
{% if perms.hosting.view_hostingplan %}
@@ -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//", views.AccountDetail.as_view(), name="account"), + path( + "accounts//customers/new/", + ResellerCustomerCreate.as_view(), + name="reseller_customer_create", + ), + path( + "accounts//customers/link/", + ResellerCustomerLink.as_view(), + name="reseller_customer_link", + ), path( "accounts//service-access/", views.ChangeHostingServices.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 77b004b..219ec92 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -114,6 +114,11 @@ from .php_versions import ( ) from .phpmyadmin import phpmyadmin_available from .reseller_accounts import create_reseller_account, save_operator_account +from .reseller_onboarding import ( + provision_reseller_resource, + request_reseller_resource, + scoped_customers, +) from .resource_requests import ( change_mailbox_quota, create_database_request, @@ -365,6 +370,14 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): reseller = reseller_for_user(user) customer = customer_for_user(user) tenant = reseller is not None or customer is not None + manage_resources = reseller is not None and reseller.manage_resources + context["reseller_resource_management"] = manage_resources + context["reseller_customer_link"] = reseller is not None and ( + self.object.customer_id is None + and scoped_customers(reseller) + .filter(user__is_active=True) + .exists() + ) context["can_retire_account"] = not tenant and user.has_perms( RETIRE_ACCOUNTS ) @@ -532,7 +545,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): ] and roundcube_available(self.request) if tenant or user.has_perm(VIEW_DATABASES): databases = self.object.databases.all() - if not tenant and user.has_perms(PROVISION_DATABASE): + if manage_resources or ( + not tenant and user.has_perms(PROVISION_DATABASE) + ): databases = databases.select_related("provisioning") context["manage_database_provisioning"] = True context["local_database_enabled"] = ( @@ -573,14 +588,16 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): mailboxes = HostingMailbox.objects.filter( mail_domain__account=self.object ).select_related("mail_domain") - if not tenant and user.has_perms(PROVISION_MAILBOX): + if manage_resources or ( + not tenant and user.has_perms(PROVISION_MAILBOX) + ): mailboxes = mailboxes.select_related("provisioning") context["manage_mailbox_provisioning"] = True context["local_mailbox_enabled"] = ( settings.LOCAL_MAILBOX_PROVISIONING ) - context["change_mailbox_quota"] = user.has_perms( - CHANGE_MAILBOX_QUOTA + context["change_mailbox_quota"] = ( + not tenant and user.has_perms(CHANGE_MAILBOX_QUOTA) ) if context.get("show_webmail"): mailboxes = list( @@ -1393,7 +1410,7 @@ class SiteSFTPKeys(PermissionRequiredMixin, FormView): return super().form_valid(form) -class CustomerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView): +class CustomerList(TenantScopeMixin, PermissionRequiredMixin, ListView): queryset = Customer.objects.select_related( "user__hosting_reseller" ).order_by("user__username") @@ -1404,7 +1421,10 @@ class CustomerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView): def get_queryset(self): self.search = self.request.GET.get("q", "").strip()[:150] + reseller = reseller_for_user(self.request.user) queryset = super().get_queryset() + if reseller is not None: + queryset = queryset.filter(pk__in=scoped_customers(reseller)) if self.search: queryset = queryset.filter(user__username__icontains=self.search) return queryset @@ -1529,17 +1549,22 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView): def customer(self): return customer_for_user(self.request.user) + @cached_property + def reseller(self): + return reseller_for_user(self.request.user) + def has_permission(self): - return self.customer is not None or ( - reseller_for_user(self.request.user) is None - and super().has_permission() - ) + if self.reseller is not None: + return self.reseller.manage_resources + return self.customer is not None or super().has_permission() @cached_property def account(self): accounts = HostingAccount.objects.filter(retired_at__isnull=True) if self.customer is not None: accounts = accounts.filter(customer=self.customer) + if self.reseller is not None: + accounts = accounts.filter(reseller=self.reseller) return get_object_or_404(accounts, pk=self.kwargs["pk"]) def get_context_data(self, **kwargs): @@ -1559,13 +1584,21 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView): def form_valid(self, form): try: with support_write_session(self.request) as session: - self.object = self.create_request( - self.account.pk, - **form.cleaned_data, - customer_id=self.customer.pk - if self.customer is not None - else None, - ) + if self.reseller is not None: + self.object = request_reseller_resource( + self.reseller, + self.account.pk, + self.create_request, + form.cleaned_data, + ) + else: + self.object = self.create_request( + self.account.pk, + **form.cleaned_data, + customer_id=self.customer.pk + if self.customer is not None + else None, + ) if session is not None: CustomerImpersonationAction.objects.create( session=session, @@ -1609,22 +1642,53 @@ class DownloadDatabaseManifest( ) -class RequestDatabaseProvisioning( - OperatorOnlyMixin, PermissionRequiredMixin, View -): - permission_required = PROVISION_DATABASE +class ResourceProvisioningRequest(PermissionRequiredMixin, View): + @cached_property + def reseller(self): + return reseller_for_user(self.request.user) + + def has_permission(self): + if self.reseller is not None: + return self.reseller.manage_resources + return ( + customer_for_user(self.request.user) is None + and super().has_permission() + ) def post(self, request, pk): - if not settings.LOCAL_DATABASE_PROVISIONING: + if not getattr(settings, self.enabled_setting): raise Http404 - database = get_object_or_404( - HostingDatabase.objects.select_related("account"), pk=pk - ) + queryset = self.queryset.all() + if self.reseller is not None: + queryset = queryset.filter( + **{f"{self.account_relation}__reseller": self.reseller} + ) + resource = get_object_or_404(queryset, pk=pk) + account = self.get_account(resource) try: - queue_database_provisioning(database) + if self.reseller is None: + self.provision(resource) + else: + provision_reseller_resource( + self.reseller, account.pk, self.provision, resource + ) + except HostingAccount.DoesNotExist as error: + raise Http404 from error except ValidationError as error: return provisioning_conflict(error) - return redirect(database.account) + return redirect(account) + + +class RequestDatabaseProvisioning(ResourceProvisioningRequest): + permission_required = PROVISION_DATABASE + enabled_setting = "LOCAL_DATABASE_PROVISIONING" + queryset = HostingDatabase.objects.select_related("account") + account_relation = "account" + provision = staticmethod(queue_database_provisioning) + + @staticmethod + def get_account(database): + return database.account class DnsZoneEditor(PermissionRequiredMixin, FormView): @@ -1905,23 +1969,16 @@ class MailboxQuotaEdit(OperatorOnlyMixin, PermissionRequiredMixin, UpdateView): return redirect(self.object.mail_domain.account) -class RequestMailboxProvisioning( - OperatorOnlyMixin, PermissionRequiredMixin, View -): +class RequestMailboxProvisioning(ResourceProvisioningRequest): permission_required = PROVISION_MAILBOX + enabled_setting = "LOCAL_MAILBOX_PROVISIONING" + queryset = HostingMailbox.objects.select_related("mail_domain__account") + account_relation = "mail_domain__account" + provision = staticmethod(queue_mailbox_provisioning) - def post(self, request, pk): - if not settings.LOCAL_MAILBOX_PROVISIONING: - raise Http404 - mailbox = get_object_or_404( - HostingMailbox.objects.select_related("mail_domain__account"), - pk=pk, - ) - try: - queue_mailbox_provisioning(mailbox) - except ValidationError as error: - return provisioning_conflict(error) - return redirect(mailbox.mail_domain.account) + @staticmethod + def get_account(mailbox): + return mailbox.mail_domain.account class HostingPlanList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):