Compare commits

...
2 Commits
Author SHA1 Message Date
parkel df924c0025 Verify and document reseller policy and audit history
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 19:08:45 +01:00
parkel 7ec11a69b3 Manage reseller access, plans, and accounts in the panel 2026-11-21 19:08:45 +01:00
14 changed files with 941 additions and 21 deletions

No files matched your search

+14
View File
@@ -1016,6 +1016,20 @@ let outstanding jobs finish before switching destinations.
For mail on a separate server, retrieve logins on the mail node, and use the
[separate-node backup workflow](development.md#bundle-backups-from-separate-nodes).
## Manage resellers
Open **Resellers** to add a reseller login or change an existing reseller's
panel access, account limit, and allowed hosting plans. The detail page shows
allocated accounts and audit history. Viewing account names and plan details
requires the corresponding hosting account and hosting plan permissions.
The account limit and allowed plans apply when a reseller creates a hosting
account. Reducing the limit or removing a plan takes effect on the next
self-service creation request. Existing accounts still count toward the
limit and retain their assigned plans. Operators can assign and move
accounts from the hosting account form. Use the audit history to review
changes to reseller policy and account assignments made through the panel.
## Suspend and resume hosting services
Open the hosting account and use **Hosting service access**. This requires
@@ -0,0 +1,64 @@
# Generated by Django 5.2.19 on 2026-11-21 18:05
import django.db.models.deletion
from django.db import migrations, models
import coulobre.hosting.fields
class Migration(migrations.Migration):
dependencies = [
("hosting", "0034_account_service_changes"),
]
operations = [
migrations.CreateModel(
name="ResellerAuditEvent",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("reseller_username", models.CharField(max_length=150)),
("actor_username", models.CharField(max_length=150)),
(
"action",
models.CharField(
choices=[
("create", "Created reseller"),
("update", "Updated reseller"),
("assign", "Assigned hosting account"),
("unassign", "Unassigned hosting account"),
("plan", "Changed hosting account plan"),
],
max_length=8,
),
),
(
"account_domain",
coulobre.hosting.fields.DomainNameField(
blank=True, max_length=253
),
),
("changes", models.JSONField()),
("created_at", models.DateTimeField(auto_now_add=True)),
(
"reseller",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="audit_events",
to="hosting.reseller",
),
),
],
options={
"ordering": ("-pk",),
},
),
]
+28
View File
@@ -57,10 +57,38 @@ class Reseller(models.Model):
def __str__(self):
return self.user.get_username()
def get_absolute_url(self):
return reverse("panel:reseller", kwargs={"pk": self.pk})
def may_create_accounts(self):
return self.account_limit > 0 and self.hosting_plans.exists()
class ResellerAuditEvent(models.Model):
class Action(models.TextChoices):
CREATE = "create", "Created reseller"
UPDATE = "update", "Updated reseller"
ASSIGN = "assign", "Assigned hosting account"
UNASSIGN = "unassign", "Unassigned hosting account"
PLAN = "plan", "Changed hosting account plan"
reseller = models.ForeignKey(
Reseller,
on_delete=models.SET_NULL,
null=True,
related_name="audit_events",
)
reseller_username = models.CharField(max_length=150)
actor_username = models.CharField(max_length=150)
action = models.CharField(max_length=8, choices=Action)
account_domain = DomainNameField(max_length=253, blank=True)
changes = models.JSONField()
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ("-pk",)
class Customer(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
+179 -6
View File
@@ -1,18 +1,115 @@
from django.contrib.auth import get_user_model
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
from .models import Customer, Reseller, ResellerAuditEvent
from .resource_requests import lock_hosting_account, require_active_services
Action = ResellerAuditEvent.Action
def lock_resellers(candidates):
if connection.vendor == "sqlite":
# Acquire the write lock before reading the reseller's policy.
candidates.update(account_limit=F("account_limit"))
return candidates.order_by("pk").select_for_update()
def plan_reference(plan):
if plan is None:
return None
return {"id": plan.pk, "name": plan.name}
def policy_snapshot(reseller):
return {
"account_limit": reseller.account_limit,
"hosting_plans": [
plan_reference(plan)
for plan in reseller.hosting_plans.order_by("pk")
],
"is_active": reseller.user.is_active,
}
def record_event(reseller, actor, action, changes, *, account_domain=""):
ResellerAuditEvent.objects.create(
reseller=reseller,
reseller_username=reseller.user.get_username(),
actor_username=actor,
action=action,
account_domain=account_domain,
changes=changes,
)
def policy_changes(before, after):
return {
key: {"before": before.get(key), "after": value}
for key, value in after.items()
if before.get(key) != value
}
def may_manage_sign_in(user):
return (
not user.is_staff
and not user.is_superuser
and not Customer.objects.filter(user=user).exists()
)
@transaction.atomic
def create_reseller(login_form, policy, actor):
user = login_form.save(commit=False)
user.is_active = policy["is_active"]
user.save()
reseller = Reseller.objects.create(
user=user, account_limit=policy["account_limit"]
)
if "hosting_plans" in policy:
reseller.hosting_plans.set(policy["hosting_plans"])
record_event(
reseller,
actor,
Action.CREATE,
policy_changes({}, policy_snapshot(reseller)),
)
return reseller
@transaction.atomic
def update_reseller(reseller_id, policy, actor):
reseller = lock_resellers(Reseller.objects.filter(pk=reseller_id)).get()
user = (
get_user_model().objects.select_for_update().get(pk=reseller.user_id)
)
reseller.user = user
before = policy_snapshot(reseller)
if "is_active" in policy and user.is_active != policy["is_active"]:
if not may_manage_sign_in(user):
raise ValidationError(
"This login can no longer be managed as a reseller."
)
user.is_active = policy["is_active"]
user.save(update_fields=["is_active"])
if reseller.account_limit != policy["account_limit"]:
reseller.account_limit = policy["account_limit"]
reseller.save(update_fields=["account_limit"])
if "hosting_plans" in policy:
reseller.hosting_plans.set(policy["hosting_plans"])
changes = policy_changes(before, policy_snapshot(reseller))
if changes:
record_event(reseller, actor, Action.UPDATE, changes)
@transaction.atomic
def create_reseller_account(access, account):
candidates = Reseller.objects.filter(pk=access.pk, user_id=access.user_id)
if connection.vendor == "sqlite":
# Write first so SQLite locks writers before the quota check.
candidates.update(account_limit=F("account_limit"))
reseller = candidates.select_for_update().first()
if reseller is None:
reseller = lock_resellers(candidates).first()
if reseller is None or not reseller.user.is_active:
raise ValidationError(
{NON_FIELD_ERRORS: "Your reseller access has changed."}
)
@@ -31,3 +128,79 @@ def create_reseller_account(access, account):
account.reseller = reseller
account.save(force_insert=True)
record_account_event(
reseller, reseller.user.get_username(), Action.ASSIGN, account
)
def record_account_event(reseller, actor, action, account):
plan = plan_reference(account.hosting_plan)
record_event(
reseller,
actor,
action,
{"plan": plan},
account_domain=account.primary_domain,
)
@transaction.atomic
def save_operator_account(account, actor, *, changed_fields=None):
if changed_fields is None:
previous = None
previous_reseller_id = None
reseller_id = account.reseller_id
else:
previous = lock_hosting_account(account.pk, customer_id=None)
if "primary_domain" in changed_fields:
require_active_services(previous)
previous_reseller_id = previous.reseller_id
reseller_id = (
account.reseller_id
if "reseller" in changed_fields
else previous_reseller_id
)
locked = {
reseller.pk: reseller
for reseller in lock_resellers(
Reseller.objects.filter(pk__in=[previous_reseller_id, reseller_id])
)
}
if reseller_id is not None and reseller_id not in locked:
raise ValidationError(
{"reseller": "This reseller is no longer available."}
)
account.save(update_fields=changed_fields)
if previous_reseller_id != reseller_id:
if previous_reseller_id is not None:
record_account_event(
locked[previous_reseller_id], actor, Action.UNASSIGN, previous
)
if reseller_id is not None:
account.refresh_from_db(fields=["primary_domain", "hosting_plan"])
record_account_event(
locked[reseller_id], actor, Action.ASSIGN, account
)
elif (
reseller_id is not None
and changed_fields is not None
and "hosting_plan" in changed_fields
and previous.hosting_plan_id != account.hosting_plan_id
):
record_event(
locked[reseller_id],
actor,
Action.PLAN,
{
"account_plan": {
"before": plan_reference(previous.hosting_plan),
"after": plan_reference(account.hosting_plan),
}
},
account_domain=(
account.primary_domain
if "primary_domain" in changed_fields
else previous.primary_domain
),
)
+192
View File
@@ -0,0 +1,192 @@
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.core.paginator import Paginator
from django.db import IntegrityError
from django.db.models import Count
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 DetailView, FormView, ListView
from .access import OperatorOnlyMixin
from .models import Reseller
from .reseller_accounts import (
create_reseller,
may_manage_sign_in,
update_reseller,
)
VIEW_RESELLERS = "hosting.view_reseller"
VIEW_PLANS = "hosting.view_hostingplan"
VIEW_ACCOUNTS = "hosting.view_hostingaccount"
class ResellerPolicyForm(forms.ModelForm):
is_active = forms.BooleanField(
label="Allow panel sign-in", required=False, initial=True
)
class Meta:
model = Reseller
fields = ("is_active", "account_limit", "hosting_plans")
labels = {"hosting_plans": "Allowed hosting plans"}
help_texts = {
"account_limit": "Enter 0 to stop self-service account creation.",
"hosting_plans": (
"Plans available when a reseller creates an account."
),
}
def __init__(self, *args, show_plans, **kwargs):
super().__init__(*args, **kwargs)
if not show_plans:
self.fields.pop("hosting_plans")
if self.instance.pk:
user = self.instance.user
if may_manage_sign_in(user):
self.initial["is_active"] = user.is_active
else:
self.fields.pop("is_active")
class ResellerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
permission_required = VIEW_RESELLERS
template_name = "hosting/reseller_list.html"
context_object_name = "resellers"
paginate_by = 20
def get_queryset(self):
self.search = self.request.GET.get("q", "").strip()[:150]
resellers = (
Reseller.objects.select_related("user")
.annotate(account_count=Count("hostingaccount"))
.order_by("user__username", "pk")
)
if self.search:
resellers = resellers.filter(user__username__icontains=self.search)
return resellers
def get_context_data(self, **kwargs):
return super().get_context_data(search=self.search, **kwargs)
class ResellerDetail(OperatorOnlyMixin, PermissionRequiredMixin, DetailView):
permission_required = VIEW_RESELLERS
template_name = "hosting/reseller_detail.html"
queryset = Reseller.objects.select_related("user")
context_object_name = "reseller"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
user = self.request.user
accounts = self.object.hostingaccount_set.select_related(
"hosting_plan"
).order_by("primary_domain", "pk")
events = self.object.audit_events.all()
context["account_count"] = accounts.count()
if user.has_perm(VIEW_ACCOUNTS):
context["account_page"] = Paginator(accounts, 20).get_page(
self.request.GET.get("account_page")
)
else:
events = events.filter(account_domain="")
context["history_page"] = Paginator(events, 20).get_page(
self.request.GET.get("history_page")
)
if user.has_perm(VIEW_PLANS):
context["allowed_plans"] = list(self.object.hosting_plans.all())
return context
@method_decorator(
sensitive_post_parameters("password1", "password2"), name="dispatch"
)
class ResellerCreate(OperatorOnlyMixin, PermissionRequiredMixin, FormView):
permission_required = (VIEW_RESELLERS, "hosting.add_reseller")
form_class = UserCreationForm
template_name = "hosting/reseller_form.html"
extra_context = {
"page_title": "Add reseller",
"submit_label": "Add reseller",
}
@cached_property
def policy_form(self):
return ResellerPolicyForm(
self.request.POST if self.request.method == "POST" else None,
prefix="policy",
show_plans=self.request.user.has_perm(VIEW_PLANS),
)
def get_context_data(self, **kwargs):
return super().get_context_data(
policy_form=self.policy_form, login_form=True, **kwargs
)
def form_valid(self, form):
if not self.policy_form.is_valid():
return self.form_invalid(form)
try:
reseller = create_reseller(
form,
self.policy_form.cleaned_data,
self.request.user.get_username(),
)
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(reseller)
class ResellerEdit(OperatorOnlyMixin, PermissionRequiredMixin, FormView):
permission_required = (VIEW_RESELLERS, "hosting.change_reseller")
form_class = ResellerPolicyForm
template_name = "hosting/reseller_form.html"
extra_context = {
"page_title": "Edit reseller",
"submit_label": "Save changes",
}
@cached_property
def reseller(self):
return get_object_or_404(
Reseller.objects.select_related("user"), pk=self.kwargs["pk"]
)
def get_form_kwargs(self):
return {
**super().get_form_kwargs(),
"instance": self.reseller,
"show_plans": self.request.user.has_perm(VIEW_PLANS),
}
def get_context_data(self, **kwargs):
return super().get_context_data(reseller=self.reseller, **kwargs)
def form_valid(self, form):
try:
update_reseller(
self.reseller.pk,
form.cleaned_data,
self.request.user.get_username(),
)
except Reseller.DoesNotExist as error:
raise Http404 from error
except ValidationError as error:
form.add_error(None, error)
return self.form_invalid(form)
return redirect(self.reseller)
@@ -159,6 +159,12 @@ button, input, select, textarea {
background: linear-gradient(currentColor, currentColor) center 35% / 40% 1px no-repeat;
}
.nav-icon-resellers {
background:
linear-gradient(currentColor, currentColor) center 35% / 55% 1px no-repeat,
linear-gradient(currentColor, currentColor) center 65% / 75% 1px no-repeat;
}
.nav-icon-health {
background:
linear-gradient(currentColor, currentColor) 25% bottom / 1px 40% no-repeat,
@@ -527,6 +533,22 @@ dd {
width: 100%;
}
.reseller-editor fieldset {
min-width: 0;
padding: 0;
border: 0;
margin: 0;
}
.reseller-editor legend {
margin-bottom: 0.65rem;
font-weight: 680;
}
.reseller-editor input[type="checkbox"] {
width: auto;
}
.editor .errorlist {
margin: 0;
padding: 0 0 0 1.1rem;
@@ -7,7 +7,7 @@
<p class="heading-meta">{{ paginator.count }} account{{ paginator.count|pluralize }}{% if search %} matching your search{% endif %}</p>
{% if account_allowance %}<p class="heading-meta">{{ account_allowance.used }} of {{ account_allowance.limit }} accounts allocated</p>{% endif %}
</div>
{% if account_allowance and account_allowance.used < account_allowance.limit or is_operator and perms.hosting.add_hostingaccount %}
{% if account_allowance.may_create and account_allowance.used < account_allowance.limit or is_operator and perms.hosting.add_hostingaccount %}
<a class="button primary" href="{% url 'panel:account_create' %}">Add hosting account</a>
{% endif %}
</header>
@@ -29,6 +29,12 @@
Customers
</a>
{% endif %}
{% if is_operator and perms.hosting.view_reseller %}
<a href="{% url 'panel:resellers' %}"{% if current == 'resellers' or current == 'reseller_create' or current == 'reseller' or current == 'reseller_edit' %} aria-current="page"{% endif %}>
<span class="nav-icon nav-icon-resellers" aria-hidden="true"></span>
Resellers
</a>
{% endif %}
{% if is_operator and perms.hosting.view_hostingplan %}
<a href="{% url 'panel:hosting_plans' %}"{% if current == 'hosting_plans' or current == 'hosting_plan_create' or current == 'hosting_plan_edit' %} aria-current="page"{% endif %}>
<span class="nav-icon nav-icon-packages" aria-hidden="true"></span>
@@ -0,0 +1,101 @@
{% extends "hosting/base.html" %}
{% block title %}{{ reseller }} · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{% url 'panel:resellers' %}">← Resellers</a>
<header class="page-heading">
<h1>{{ reseller }}</h1>
{% if perms.hosting.change_reseller %}
<a class="button secondary" href="{% url 'panel:reseller_edit' reseller.pk %}">Edit reseller</a>
{% endif %}
</header>
<dl class="details surface">
<div><dt>Panel sign-in</dt><dd>{{ reseller.user.is_active|yesno:"Active,Suspended" }}</dd></div>
<div><dt>Accounts allocated</dt><dd>{{ account_count }} of {{ reseller.account_limit }}</dd></div>
{% if perms.hosting.view_hostingplan %}
<div>
<dt>Allowed hosting plans</dt>
<dd>{% for plan in allowed_plans %}{{ plan.name }}{% if not forloop.last %}, {% endif %}{% empty %}None{% endfor %}</dd>
</div>
{% endif %}
</dl>
{% if perms.hosting.view_hostingaccount %}
<section class="surface" aria-labelledby="reseller-accounts-heading">
<header class="section-heading"><h2 id="reseller-accounts-heading">Assigned hosting accounts</h2></header>
{% if account_page.object_list %}
<div class="table-scroll">
<table>
<thead>
<tr><th scope="col">Account</th><th scope="col">Primary domain</th>{% if perms.hosting.view_hostingplan %}<th scope="col">Hosting plan</th>{% endif %}</tr>
</thead>
<tbody>
{% for account in account_page %}
<tr>
<th scope="row"><a class="record-link" href="{{ account.get_absolute_url }}">{{ account.name }}</a></th>
<td class="domain">{{ account.primary_domain }}</td>
{% if perms.hosting.view_hostingplan %}<td>{{ account.hosting_plan.name|default:"Unassigned" }}</td>{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% if account_page.has_other_pages %}
<nav class="pagination" aria-label="Assigned account pages">
{% if account_page.has_previous %}<a class="button secondary" href="{% querystring account_page=account_page.previous_page_number %}">Previous</a>{% endif %}
<span>Page {{ account_page.number }} of {{ account_page.paginator.num_pages }}</span>
{% if account_page.has_next %}<a class="button secondary" href="{% querystring account_page=account_page.next_page_number %}">Next</a>{% endif %}
</nav>
{% endif %}
{% else %}
<p class="empty">No hosting accounts are assigned.</p>
{% endif %}
</section>
{% endif %}
<section class="surface" aria-labelledby="reseller-history-heading">
<header class="section-heading"><h2 id="reseller-history-heading">Audit history</h2></header>
{% if history_page.object_list %}
<div class="table-scroll">
<table>
<thead>
<tr><th scope="col">Change</th><th scope="col">Changed by</th><th scope="col">Time (UTC)</th></tr>
</thead>
<tbody>
{% for event in history_page %}
<tr>
<td>
<strong>{{ event.get_action_display }}</strong>
{% if event.account_domain %}<div class="domain">{{ event.account_domain }}</div>{% endif %}
{% 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.is_active %}
<div>Panel sign-in {{ event.changes.is_active.before|yesno:"active,suspended,—" }} → {{ event.changes.is_active.after|yesno:"active,suspended" }}</div>
{% endif %}
{% if perms.hosting.view_hostingplan %}
{% if event.changes.hosting_plans %}
<div>Allowed plans {% for plan in event.changes.hosting_plans.before %}{{ plan.name }}{% if not forloop.last %}, {% endif %}{% empty %}None{% endfor %} → {% for plan in event.changes.hosting_plans.after %}{{ plan.name }}{% if not forloop.last %}, {% endif %}{% empty %}None{% endfor %}</div>
{% endif %}
{% if event.changes.plan %}<div>Hosting plan {{ event.changes.plan.name }}</div>{% endif %}
{% if event.changes.account_plan %}
<div>Hosting plan {{ event.changes.account_plan.before.name|default:"Unassigned" }} → {{ event.changes.account_plan.after.name|default:"Unassigned" }}</div>
{% endif %}
{% endif %}
</td>
<td>{{ event.actor_username }}</td>
<td class="cell-date">{{ event.created_at|date:"j M Y, H:i" }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% if history_page.has_other_pages %}
<nav class="pagination" aria-label="Audit history pages">
{% if history_page.has_previous %}<a class="button secondary" href="{% querystring history_page=history_page.previous_page_number %}">Previous</a>{% endif %}
<span>Page {{ history_page.number }} of {{ history_page.paginator.num_pages }}</span>
{% if history_page.has_next %}<a class="button secondary" href="{% querystring history_page=history_page.next_page_number %}">Next</a>{% endif %}
</nav>
{% endif %}
{% else %}
<p class="empty">No changes recorded by the panel.</p>
{% endif %}
</section>
{% endblock %}
@@ -0,0 +1,27 @@
{% extends "hosting/base.html" %}
{% block title %}{{ page_title }} · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{% if reseller %}{{ reseller.get_absolute_url }}{% else %}{% url 'panel:resellers' %}{% endif %}">← {% if reseller %}{{ reseller }}{% else %}Resellers{% endif %}</a>
<header class="page-heading"><h1>{{ page_title }}</h1></header>
<section class="surface editor-surface">
<form method="post" class="editor reseller-editor">
{% csrf_token %}
{% if login_form %}
<fieldset class="editor">
<legend>Login</legend>
{{ form.as_div }}
</fieldset>
<fieldset class="editor">
<legend>Access and plans</legend>
{{ policy_form.as_div }}
</fieldset>
{% else %}
{{ form.as_div }}
{% endif %}
<div class="form-actions">
<button class="button primary" type="submit">{{ submit_label }}</button>
<a class="button secondary" href="{% if reseller %}{{ reseller.get_absolute_url }}{% else %}{% url 'panel:resellers' %}{% endif %}">Cancel</a>
</div>
</form>
</section>
{% endblock %}
@@ -0,0 +1,41 @@
{% extends "hosting/base.html" %}
{% block title %}Resellers · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading">
<h1>Resellers</h1>
{% if perms.hosting.add_reseller %}
<a class="button primary" href="{% url 'panel:reseller_create' %}">Add reseller</a>
{% endif %}
</header>
<section class="surface" aria-label="Reseller list">
<form class="toolbar" method="get" action="{% url 'panel:resellers' %}" role="search">
<label class="visually-hidden" for="reseller-search">Search by username</label>
<input type="search" id="reseller-search" name="q" placeholder="Username" value="{{ search }}">
<button class="button secondary" type="submit">Search</button>
{% if search %}<a class="quiet-link" href="{% url 'panel:resellers' %}">Clear</a>{% endif %}
</form>
{% if resellers %}
<div class="table-scroll">
<table>
<thead>
<tr><th scope="col">Username</th><th scope="col">Panel sign-in</th><th scope="col">Accounts allocated</th></tr>
</thead>
<tbody>
{% for reseller in resellers %}
<tr>
<th scope="row"><a class="record-link" href="{{ reseller.get_absolute_url }}">{{ reseller }}</a></th>
<td>{{ reseller.user.is_active|yesno:"Active,Suspended" }}</td>
<td>{{ reseller.account_count }} of {{ reseller.account_limit }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% elif search %}
<p class="empty">No resellers match this search.</p>
{% else %}
<p class="empty">No resellers yet.</p>
{% endif %}
{% include "hosting/pagination.html" %}
</section>
{% endblock %}
+241 -2
View File
@@ -2,10 +2,17 @@ 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.test import Client, TestCase
from django.urls import reverse
from .models import HostingAccount, HostingPlan, Reseller, WebProvisioningPlan
from .models import (
Customer,
HostingAccount,
HostingPlan,
Reseller,
ResellerAuditEvent,
WebProvisioningPlan,
)
from .reseller_accounts import create_reseller_account
from .tasks import render_web_plan
@@ -288,3 +295,235 @@ class ResellerAccountCreationTests(TestCase):
self.assertEqual(
list(self.reseller.hosting_plans.all()), [self.unavailable]
)
class ResellerManagementTests(TestCase):
password = "test-reseller-login-password"
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_superuser("operator")
cls.login = users.create_user("seller", password=cls.password)
cls.reseller = Reseller.objects.create(user=cls.login, account_limit=3)
cls.other = Reseller.objects.create(user=users.create_user("other"))
cls.basic = HostingPlan.objects.create(name="Basic plan")
cls.upgrade = HostingPlan.objects.create(name="Upgraded plan")
cls.reseller.hosting_plans.add(cls.basic, cls.upgrade)
cls.account = HostingAccount.objects.create(
name="Seller website",
primary_domain="seller.example",
reseller=cls.reseller,
hosting_plan=cls.basic,
)
def setUp(self):
self.client.force_login(self.operator)
self.detail = self.reseller.get_absolute_url()
self.edit = reverse("panel:reseller_edit", args=[self.reseller.pk])
self.index = reverse("panel:resellers")
self.create = reverse("panel:reseller_create")
def test_create_an_unprivileged_login_and_view_its_policy(self):
form = self.client.get(self.create)
self.assertContains(form, 'name="policy-hosting_plans"')
self.assertContains(form, 'name="password1"')
response = self.client.post(
self.create,
{
"username": "new-seller",
"password1": self.password,
"password2": self.password,
"policy-account_limit": 4,
"policy-is_active": "on",
"policy-hosting_plans": [self.upgrade.pk],
"is_staff": "on",
},
)
reseller = Reseller.objects.get(user__username="new-seller")
self.assertRedirects(response, reseller.get_absolute_url())
self.assertTrue(reseller.user.check_password(self.password))
self.assertTrue(reseller.user.is_active)
self.assertFalse(reseller.user.is_staff)
self.assertFalse(reseller.user.is_superuser)
self.assertEqual(list(reseller.hosting_plans.all()), [self.upgrade])
self.assertContains(
self.client.get(self.index, {"q": "new-"}), "0 of 4"
)
self.assertContains(
self.client.get(reseller.get_absolute_url()), "Created reseller"
)
audit = reseller.audit_events.get()
self.assertEqual(audit.actor_username, "operator")
self.assertEqual(audit.reseller_username, "new-seller")
self.assertNotIn(self.password, str(audit.changes))
def test_limit_and_plan_updates_apply_to_new_account_requests(self):
tenant = Client()
tenant.force_login(self.login)
create_account = reverse("panel:account_create")
self.assertContains(tenant.get(create_account), self.basic.name)
payload = {
"name": "Another website",
"primary_domain": "another.example",
}
self.assertRedirects(
self.client.post(
self.edit,
{
"is_active": "on",
"account_limit": 1,
"hosting_plans": [self.upgrade.pk],
},
),
self.detail,
)
self.assertContains(self.client.get(self.detail), "1 of 1")
self.assertContains(self.client.get(self.detail), self.account.name)
self.assertContains(
tenant.post(
create_account, payload | {"hosting_plan": self.upgrade.pk}
),
"Your hosting account limit has been reached.",
)
response = tenant.post(
create_account, payload | {"hosting_plan": self.basic.pk}
)
self.assertIn("hosting_plan", response.context["form"].errors)
self.account.refresh_from_db()
self.assertEqual(self.account.hosting_plan, self.basic)
self.assertEqual(self.reseller.hostingaccount_set.count(), 1)
audit = self.reseller.audit_events.get()
self.assertEqual(
audit.changes["account_limit"], {"before": 3, "after": 1}
)
self.assertEqual(
audit.changes["hosting_plans"]["after"],
[{"id": self.upgrade.pk, "name": self.upgrade.name}],
)
def test_edit_sign_in_revokes_a_resellers_session_and_can_restore_it(self):
tenant = Client()
self.assertTrue(
tenant.login(username="seller", password=self.password)
)
policy = {
"account_limit": 3,
"hosting_plans": [self.basic.pk, self.upgrade.pk],
}
self.assertRedirects(self.client.post(self.edit, policy), self.detail)
self.assertFalse(
tenant.login(username="seller", password=self.password)
)
self.assertEqual(
tenant.get(reverse("panel:accounts")).status_code, 302
)
self.assertEqual(
self.reseller.audit_events.first().changes["is_active"],
{"before": True, "after": False},
)
self.assertRedirects(
self.client.post(self.edit, policy | {"is_active": "on"}),
self.detail,
)
self.assertTrue(
tenant.login(username="seller", password=self.password)
)
def test_account_plan_edits_and_transfers_are_audited_for_each_reseller(
self,
):
edit_account = reverse("panel:account_edit", args=[self.account.pk])
payload = {
"name": self.account.name,
"primary_domain": self.account.primary_domain,
"hosting_plan": self.upgrade.pk,
}
for reseller in (self.reseller, self.other):
self.assertRedirects(
self.client.post(
edit_account, payload | {"reseller": reseller.pk}
),
self.account.get_absolute_url(),
)
moved = self.other.audit_events.get()
self.assertEqual(moved.action, ResellerAuditEvent.Action.ASSIGN)
self.assertEqual(moved.account_domain, self.account.primary_domain)
self.assertEqual(moved.changes["plan"]["id"], self.upgrade.pk)
self.assertEqual(moved.actor_username, "operator")
self.assertEqual(
list(self.reseller.audit_events.values_list("action", flat=True)),
[
ResellerAuditEvent.Action.UNASSIGN,
ResellerAuditEvent.Action.PLAN,
],
)
self.assertContains(
self.client.get(self.detail), "Unassigned hosting account"
)
self.assertContains(
self.client.get(self.other.get_absolute_url()), self.account.name
)
def test_tenants_cannot_view_or_manage_resellers_with_operator_permissions(
self,
):
customer = Customer.objects.create(
user=get_user_model().objects.create_user("customer")
)
permissions = Permission.objects.filter(
content_type__app_label="hosting",
codename__in=("view_reseller", "add_reseller", "change_reseller"),
)
for user in (self.login, customer.user):
user.user_permissions.add(*permissions)
self.client.force_login(user)
for page in (self.index, self.detail, self.edit, self.create):
with self.subTest(user=user, page=page):
self.assertEqual(self.client.get(page).status_code, 403)
self.assertEqual(self.client.post(self.edit).status_code, 403)
self.assertFalse(ResellerAuditEvent.objects.exists())
def test_limited_operator_cannot_read_or_replace_allowed_plans(self):
users = get_user_model().objects
operator = users.create_user("reseller-manager")
operator.user_permissions.add(
*Permission.objects.filter(
content_type__app_label="hosting",
codename__in=("view_reseller", "change_reseller"),
)
)
self.client.force_login(operator)
self.assertNotContains(self.client.get(self.detail), self.account.name)
self.assertNotContains(self.client.get(self.detail), self.basic.name)
self.assertNotContains(
self.client.get(self.edit), 'name="hosting_plans"'
)
self.assertRedirects(
self.client.post(
self.edit,
{
"account_limit": 2,
"is_active": "on",
"hosting_plans": [self.upgrade.pk],
},
),
self.detail,
)
self.assertEqual(
list(self.reseller.hosting_plans.all()), [self.basic, self.upgrade]
)
self.assertNotIn(
"hosting_plans", self.reseller.audit_events.get().changes
)
def test_existing_staff_reseller_can_keep_their_sign_in(self):
self.login.is_staff = True
self.login.save(update_fields=["is_staff"])
self.assertNotContains(self.client.get(self.edit), 'name="is_active"')
self.assertRedirects(
self.client.post(self.edit, {"account_limit": 1}), self.detail
)
self.login.refresh_from_db()
self.assertTrue(self.login.is_active)
+14
View File
@@ -6,6 +6,12 @@ from .backup_restores import RestoreKind
from .credential_views import DatabaseCredentialView, MailboxCredentialView
from .health_views import ServiceHealthView
from .phpmyadmin import PhpMyAdminLaunch, redeem_phpmyadmin
from .reseller_views import (
ResellerCreate,
ResellerDetail,
ResellerEdit,
ResellerList,
)
app_name = "panel"
@@ -112,6 +118,14 @@ urlpatterns = [
views.AccountEdit.as_view(),
name="account_edit",
),
path("resellers/", ResellerList.as_view(), name="resellers"),
path("resellers/new/", ResellerCreate.as_view(), name="reseller_create"),
path("resellers/<int:pk>/", ResellerDetail.as_view(), name="reseller"),
path(
"resellers/<int:pk>/edit/",
ResellerEdit.as_view(),
name="reseller_edit",
),
path("customers/", views.CustomerList.as_view(), name="customers"),
path(
"customers/new/",
+11 -12
View File
@@ -96,18 +96,16 @@ from .php_settings import (
settings_from_form,
)
from .phpmyadmin import phpmyadmin_available
from .reseller_accounts import create_reseller_account
from .reseller_accounts import create_reseller_account, save_operator_account
from .resource_requests import (
change_mailbox_quota,
create_database_request,
create_mailbox_request,
lock_hosting_account,
queue_database_provisioning,
queue_mailbox_provisioning,
queue_site_storage_limit,
queue_site_storage_measurement,
queue_web_https,
require_active_services,
)
from .service_changes import request_service_change
from .service_credentials import (
@@ -212,10 +210,11 @@ class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView):
def get_context_data(self, **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():
if reseller is not None:
context["account_allowance"] = {
"used": reseller.hostingaccount_set.count(),
"limit": reseller.account_limit,
"may_create": reseller.may_create_accounts(),
}
return context
@@ -278,7 +277,9 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView):
self.object = form.save(commit=False)
try:
if reseller is None:
self.object.save()
save_operator_account(
self.object, self.request.user.get_username()
)
else:
create_reseller_account(reseller, self.object)
except ValidationError as error:
@@ -307,13 +308,11 @@ class AccountEdit(
def form_valid(self, form):
self.object = form.save(commit=False)
try:
with transaction.atomic():
if "primary_domain" in form.changed_data:
current = lock_hosting_account(
self.object.pk, customer_id=None
)
require_active_services(current)
self.object.save(update_fields=form.changed_data)
save_operator_account(
self.object,
self.request.user.get_username(),
changed_fields=form.changed_data,
)
except ValidationError as error:
form.add_error(None, error)
return self.form_invalid(form)