Let resellers onboard customers and provision hosting resources #101

Merged
parkel merged 2 commits from feature/reseller-customer-onboarding into main 2026-11-22 11:53:10 +01:00
15 changed files with 498 additions and 70 deletions
Showing only changes of commit 2846e83644 - Show all commits

No files matched your search

+14 -3
View File
@@ -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):
@@ -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,
),
),
]
+19 -2
View File
@@ -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,
+7 -1
View File
@@ -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))
+109
View File
@@ -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,
)
@@ -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)
+10 -2
View File
@@ -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": (
+2 -2
View File
@@ -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
@@ -39,6 +39,21 @@
{% endif %}
{% if is_operator and perms.hosting.view_customer %}
<div><dt>Customer</dt><dd>{{ account.customer|default_if_none:"Unassigned" }}</dd></div>
{% elif is_reseller %}
<div><dt>Customer</dt>
<dd>
{% if account.customer_id %}
{% if account.customer.reseller_id == account.reseller_id %}
{{ account.customer }}
{% else %}Assigned{% endif %}
{% else %}
<a class="record-link" href="{% url 'panel:reseller_customer_create' account.pk %}">Add customer login</a>
{% if reseller_customer_link %}
<a class="record-link" href="{% url 'panel:reseller_customer_link' account.pk %}">Link existing customer</a>
{% endif %}
{% endif %}
</dd>
</div>
{% endif %}
<div><dt>Added</dt><dd>{{ account.created_at|date:"j M Y, H:i" }} UTC</dd></div>
</dl>
@@ -92,14 +107,14 @@
{% endif %}
{% endif %}
</div>
{% 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 %}
<a class="button primary" href="{% url 'panel:database_create' account.pk %}">Request database</a>
{% endif %}
</header>
{% if databases %}
<div class="table-scroll">
<table>
<thead><tr><th scope="col">Database</th>{% if is_operator %}<th scope="col">Deployment</th>{% endif %}</tr></thead>
<thead><tr><th scope="col">Database</th>{% if is_operator or manage_database_provisioning %}<th scope="col">Deployment</th>{% endif %}</tr></thead>
<tbody>
{% for database in databases %}
<tr>
@@ -115,16 +130,18 @@
</form>
{% endif %}
</td>
{% if is_operator %}
{% if is_operator or manage_database_provisioning %}
<td>
<div class="form-actions">
<a class="record-link" href="{% url 'panel:database_manifest' database.pk %}" aria-label="Download manifest for {{ database }}">Download manifest</a>
{% if is_operator %}
<a class="record-link" href="{% url 'panel:database_manifest' database.pk %}" aria-label="Download manifest for {{ database }}">Download manifest</a>
{% 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 %}
</div>
{% if manage_database_provisioning and database.provisioning.problem %}
{% if is_operator and manage_database_provisioning and database.provisioning.problem %}
<p class="heading-meta">{{ database.provisioning.problem }}</p>
{% endif %}
</td>
@@ -231,7 +248,7 @@
{% endif %}
{% endif %}
</div>
{% 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 %}
<a class="button primary" href="{% url 'panel:mailbox_create' account.pk %}">Request mailbox</a>
{% endif %}
</header>
@@ -242,7 +259,7 @@
<tr>
<th scope="col">Email address</th>
<th scope="col">Storage limit</th>
{% if is_operator %}<th scope="col">Deployment</th>{% endif %}
{% if is_operator or manage_mailbox_provisioning %}<th scope="col">Deployment</th>{% endif %}
</tr>
</thead>
<tbody>
@@ -264,10 +281,12 @@
{% endif %}
</td>
<td>{% if mailbox.quota_mib is not None %}{{ mailbox.quota_mib }} MiB{% else %}Unlimited{% endif %}</td>
{% if is_operator %}
{% if is_operator or manage_mailbox_provisioning %}
<td>
<div class="form-actions">
<a class="record-link" href="{% url 'panel:mailbox_manifest' mailbox.pk %}" aria-label="Download mailbox manifest for {{ mailbox }}">Download manifest</a>
{% if is_operator %}
<a class="record-link" href="{% url 'panel:mailbox_manifest' mailbox.pk %}" aria-label="Download mailbox manifest for {{ mailbox }}">Download manifest</a>
{% endif %}
{% if change_mailbox_quota %}
<a class="record-link" href="{% url 'panel:mailbox_quota' mailbox.pk %}" aria-label="Change storage limit for {{ mailbox }}">Change storage limit</a>
{% 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 %}
</div>
{% if manage_mailbox_provisioning and mailbox.provisioning.problem %}
{% if is_operator and manage_mailbox_provisioning and mailbox.provisioning.problem %}
<p class="heading-meta">{{ mailbox.provisioning.problem }}</p>
{% endif %}
</td>
@@ -27,7 +27,7 @@
Hosting accounts
</a>
{% endif %}
{% if is_operator and perms.hosting.view_customer %}
{% if is_reseller or is_operator and perms.hosting.view_customer %}
<a href="{% url 'panel:customers' %}"{% if panel_section == 'customers' %} aria-current="{% if current == 'customers' %}page{% else %}location{% endif %}"{% endif %}>
<span class="nav-icon nav-icon-customers" aria-hidden="true"></span>
Customers
@@ -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 %}
<a class="back-link" href="{% url 'panel:customers' %}">← Customers</a>
<header class="page-heading"><h1>Add customer</h1></header>
{% if account %}
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
{% else %}
<a class="back-link" href="{% url 'panel:customers' %}">← Customers</a>
{% endif %}
<header class="page-heading"><h1>{{ title|default:"Add customer" }}</h1></header>
<section class="surface editor-surface">
<form method="post" class="editor">
{% csrf_token %}
{{ form.as_div }}
<div class="form-actions">
<button class="button primary" type="submit">Add customer</button>
<a class="button secondary" href="{% url 'panel:customers' %}">Cancel</a>
<button class="button primary" type="submit">{{ title|default:"Add customer" }}</button>
{% if account %}
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
{% else %}
<a class="button secondary" href="{% url 'panel:customers' %}">Cancel</a>
{% endif %}
</div>
</form>
</section>
@@ -3,7 +3,7 @@
{% block content %}
<header class="page-heading">
<h1>Customers</h1>
{% if perms.hosting.add_customer %}
{% if is_operator and perms.hosting.add_customer %}
<a class="button primary" href="{% url 'panel:customer_create' %}">Add customer</a>
{% endif %}
</header>
@@ -21,7 +21,7 @@
<tr>
<th scope="col">Username</th>
<th scope="col">Sign-in status</th>
{% if perms.hosting.change_customer or can_impersonate %}<th scope="col">Actions</th>{% endif %}
{% if is_operator and perms.hosting.change_customer or can_impersonate %}<th scope="col">Actions</th>{% endif %}
</tr>
</thead>
<tbody>
@@ -32,7 +32,7 @@
{% if customer.user.is_active %}<span class="status active">Active</span>
{% else %}<span class="status suspended">Suspended</span>{% endif %}
</td>
{% if perms.hosting.change_customer or can_impersonate %}
{% if is_operator and perms.hosting.change_customer or can_impersonate %}
<td>
<div class="table-actions">
{% 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 @@
</div>
{% elif search %}
<p class="empty">No customers match this search.</p>
{% elif is_reseller %}
<p class="empty">Open an unassigned hosting account to add a customer login.</p>
{% else %}
<p class="empty">No customers yet.</p>
{% endif %}
@@ -10,6 +10,7 @@
</header>
<dl class="details surface">
<div><dt>Panel sign-in</dt><dd>{{ reseller.user.is_active|yesno:"Active,Suspended" }}</dd></div>
<div><dt>Database and mailbox management</dt><dd>{{ reseller.manage_resources|yesno:"Allowed,Operator only" }}</dd></div>
<div><dt>Accounts allocated</dt><dd>{{ account_count }} of {{ reseller.account_limit }}</dd></div>
{% if perms.hosting.view_hostingplan %}
<div>
@@ -67,6 +68,11 @@
{% if event.changes.account_limit %}
<div>Account limit {{ event.changes.account_limit.before|default_if_none:"—" }} → {{ event.changes.account_limit.after }}</div>
{% endif %}
{% if event.changes.customer %}<div>{{ event.changes.customer }}</div>{% endif %}
{% if event.changes.resource %}<div>{{ event.changes.type|capfirst }} {{ event.changes.resource }}</div>{% endif %}
{% if event.changes.manage_resources %}
<div>Database and mailbox management {{ event.changes.manage_resources.before|yesno:"allowed,operator only,—" }} → {{ event.changes.manage_resources.after|yesno:"allowed,operator only" }}</div>
{% endif %}
{% if event.changes.is_active %}
<div>Panel sign-in {{ event.changes.is_active.before|yesno:"active,suspended,—" }} → {{ event.changes.is_active.after|yesno:"active,suspended" }}</div>
{% endif %}
+14
View File
@@ -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/<int:pk>/", views.AccountDetail.as_view(), name="account"),
path(
"accounts/<int:pk>/customers/new/",
ResellerCustomerCreate.as_view(),
name="reseller_customer_create",
),
path(
"accounts/<int:pk>/customers/link/",
ResellerCustomerLink.as_view(),
name="reseller_customer_link",
),
path(
"accounts/<int:pk>/service-access/",
views.ChangeHostingServices.as_view(),
+98 -41
View File
@@ -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):