Merge pull request 'Add a customer portal with hosting plan quotas' (#11) from feature/customer-portal into main

Reviewed-on: #11
This commit was merged in pull request #11.
This commit is contained in:
parkel committed 2026-11-21 00:43:36 +01:00
commit 7295f00008
22 files changed
+1100 -112

No files matched your search

+2
View File
@@ -11,6 +11,8 @@ See [Local development](docs/development.md) to run it.
- Self-hosted installation on a single Ubuntu server, with Debian support planned. - Self-hosted installation on a single Ubuntu server, with Debian support planned.
- Hosting plans and self-service access for administrators, resellers, and customers. - Hosting plans and self-service access for administrators, resellers, and customers.
- Customer impersonation for administrator support, with a dedicated permission,
a visible session indicator, and an audit trail.
- Domains, TLS certificates, SFTP, and databases using Apache, PHP-FPM, and MariaDB. - Domains, TLS certificates, SFTP, and databases using Apache, PHP-FPM, and MariaDB.
- Mail and DNS on the hosting server or on separate servers. - Mail and DNS on the hosting server or on separate servers.
- Account backups, restore, and migration from DirectAdmin. - Account backups, restore, and migration from DirectAdmin.
+34
View File
@@ -23,6 +23,17 @@ Use **Hosting plans** to add named plans with an optional description. Choose a
plan when creating or editing an account. Existing accounts start unassigned. plan when creating or editing an account. Existing accounts start unassigned.
Operators need permission to view hosting plans before they can assign one. Operators need permission to view hosting plans before they can assign one.
Set a database limit and a mailbox limit on a hosting plan to cap how many
requests each assigned account can make through the panel. A blank limit allows
unlimited requests. Zero blocks new requests of that type. Accounts without a
plan have unlimited requests. The account page shows usage for configured
limits. Mailboxes count toward the same limit across all of an account's mail
domains, including domains retained after a primary domain change.
Changing or reassigning a plan preserves existing databases and mailboxes. If
the new limit is at or below current usage, the panel blocks additional
requests of that type.
## Give a reseller access to assigned accounts ## Give a reseller access to assigned accounts
In `/admin/`, create a normal user and add a **Reseller** record for that user. In `/admin/`, create a normal user and add a **Reseller** record for that user.
@@ -45,6 +56,29 @@ and node deployment files.
The local database defaults to `db.sqlite3`. Set `COULOBRE_SQLITE_PATH` to use a The local database defaults to `db.sqlite3`. Set `COULOBRE_SQLITE_PATH` to use a
different file. Keep `COULOBRE_DEBUG` for local development. different file. Keep `COULOBRE_DEBUG` for local development.
## Give a customer access to hosting accounts
In Coulobre Panel, open **Customers** and select **Add customer**. Enter a
username and initial password. Select the customer when adding or editing a
hosting account. Repeat the assignment for each hosting account the customer
should be able to access. To give an existing user customer access, add a
**Customer** record for that user in `/admin/`.
The customer can sign in to Coulobre Panel with that username and password.
Their account list shows only the hosting accounts assigned to them. Each
account page shows its hosting plan, database requests, DNS zones, and mailbox
requests. Customers can request databases and mailboxes for their own accounts
within their plan limits. Operators deploy those requests on the hosting nodes.
Use **Suspend sign-in** in the customer list to block panel access for that
customer across all their hosting accounts. Use **Restore sign-in** to give
them access again. Account assignments are preserved through suspension.
Operators need the **Can view customer** permission to use the customer list
and select a customer on hosting accounts they can create or edit. **Can add
customer** enables customer creation. **Can change customer** enables
sign-in suspension and restoration.
## Request a MariaDB database ## Request a MariaDB database
Open a hosting account and select **Request database**. Choose a short suffix Open a hosting account and select **Request database**. Choose a short suffix
+2 -4
View File
@@ -1,14 +1,12 @@
from django.contrib.admin import AdminSite from django.contrib.admin import AdminSite
from django.contrib.admin.apps import AdminConfig from django.contrib.admin.apps import AdminConfig
from .hosting.access import reseller_for_user from .hosting.access import is_tenant
class CoulobreAdminSite(AdminSite): class CoulobreAdminSite(AdminSite):
def has_permission(self, request): def has_permission(self, request):
return ( return super().has_permission(request) and not is_tenant(request.user)
super().has_permission(request) and reseller_for_user(request.user) is None
)
class CoulobreAdminConfig(AdminConfig): class CoulobreAdminConfig(AdminConfig):
+33 -4
View File
@@ -1,30 +1,59 @@
def reseller_for_user(user): def customer_for_user(user):
if not user.is_authenticated or user.is_superuser: if not user.is_authenticated or user.is_superuser:
return None return None
return getattr(user, "hosting_customer", None)
def reseller_for_user(user):
if (
not user.is_authenticated
or user.is_superuser
or customer_for_user(user) is not None
):
return None
return getattr(user, "hosting_reseller", None) return getattr(user, "hosting_reseller", None)
def is_tenant(user):
return customer_for_user(user) is not None or reseller_for_user(user) is not None
def panel_access(request): def panel_access(request):
return {"is_reseller": reseller_for_user(request.user) is not None} customer = customer_for_user(request.user) is not None
reseller = not customer and reseller_for_user(request.user) is not None
return {
"is_customer": customer,
"is_reseller": reseller,
"is_tenant": customer or reseller,
"is_operator": request.user.is_authenticated and not (customer or reseller),
}
class OperatorOnlyMixin: class OperatorOnlyMixin:
def dispatch(self, request, *args, **kwargs): def dispatch(self, request, *args, **kwargs):
if reseller_for_user(request.user) is not None: if is_tenant(request.user):
return self.handle_no_permission() return self.handle_no_permission()
return super().dispatch(request, *args, **kwargs) return super().dispatch(request, *args, **kwargs)
class ResellerScopeMixin: class TenantScopeMixin:
reseller_relation = "reseller" reseller_relation = "reseller"
customer_relation = None
def has_permission(self): def has_permission(self):
if customer_for_user(self.request.user) is not None:
return self.customer_relation is not None
return ( return (
reseller_for_user(self.request.user) is not None or super().has_permission() reseller_for_user(self.request.user) is not None or super().has_permission()
) )
def get_queryset(self): def get_queryset(self):
queryset = super().get_queryset() queryset = super().get_queryset()
customer = customer_for_user(self.request.user)
if customer is not None:
if self.customer_relation is None:
return queryset.none()
return queryset.filter(**{f"{self.customer_relation}_id": customer.pk})
reseller = reseller_for_user(self.request.user) reseller = reseller_for_user(self.request.user)
if reseller is not None: if reseller is not None:
return queryset.filter(**{f"{self.reseller_relation}_id": reseller.pk}) return queryset.filter(**{f"{self.reseller_relation}_id": reseller.pk})
+17 -2
View File
@@ -1,7 +1,7 @@
from django.contrib import admin from django.contrib import admin
from django.utils.html import format_html from django.utils.html import format_html
from .models import HostingAccount, HostingPlan, Reseller, WebProvisioningPlan from .models import Customer, HostingAccount, HostingPlan, Reseller, WebProvisioningPlan
@admin.register(HostingAccount) @admin.register(HostingAccount)
@@ -17,6 +17,8 @@ class HostingAccountAdmin(admin.ModelAdmin):
excluded.append("hosting_plan") excluded.append("hosting_plan")
if not request.user.has_perm("hosting.view_reseller"): if not request.user.has_perm("hosting.view_reseller"):
excluded.append("reseller") excluded.append("reseller")
if not request.user.has_perm("hosting.view_customer"):
excluded.append("customer")
return excluded return excluded
def save_model(self, request, obj, form, change): def save_model(self, request, obj, form, change):
@@ -36,9 +38,15 @@ class HostingAccountAdmin(admin.ModelAdmin):
@admin.register(HostingPlan) @admin.register(HostingPlan)
class HostingPlanAdmin(admin.ModelAdmin): class HostingPlanAdmin(admin.ModelAdmin):
list_display = ("name", "description") list_display = ("name", "description", "database_limit", "mailbox_limit")
search_fields = ("name",) search_fields = ("name",)
def save_model(self, request, obj, form, change):
if change:
obj.save(update_fields=form.changed_data)
else:
super().save_model(request, obj, form, change)
@admin.register(Reseller) @admin.register(Reseller)
class ResellerAdmin(admin.ModelAdmin): class ResellerAdmin(admin.ModelAdmin):
@@ -54,6 +62,13 @@ class ResellerAdmin(admin.ModelAdmin):
return excluded return excluded
@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
list_display = ("user",)
list_select_related = ("user",)
search_fields = ("user__username",)
@admin.register(WebProvisioningPlan) @admin.register(WebProvisioningPlan)
class WebProvisioningPlanAdmin(admin.ModelAdmin): class WebProvisioningPlanAdmin(admin.ModelAdmin):
list_display = ("primary_domain", "account", "requested_at", "completed_at") list_display = ("primary_domain", "account", "requested_at", "completed_at")
@@ -0,0 +1,65 @@
# Generated by Django 5.2.19 on 2026-11-20 23:20
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0010_directadminimport"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AlterField(
model_name="reseller",
name="user",
field=models.OneToOneField(
limit_choices_to={
"hosting_customer__isnull": True,
"is_superuser": False,
},
on_delete=django.db.models.deletion.PROTECT,
related_name="hosting_reseller",
to=settings.AUTH_USER_MODEL,
),
),
migrations.CreateModel(
name="Customer",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"user",
models.OneToOneField(
limit_choices_to={
"hosting_reseller__isnull": True,
"is_staff": False,
"is_superuser": False,
},
on_delete=django.db.models.deletion.PROTECT,
related_name="hosting_customer",
to=settings.AUTH_USER_MODEL,
),
),
],
),
migrations.AddField(
model_name="hostingaccount",
name="customer",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.PROTECT,
to="hosting.customer",
),
),
]
@@ -0,0 +1,30 @@
# Generated by Django 5.2.19 on 2026-11-20 23:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0011_customer_access"),
]
operations = [
migrations.AddField(
model_name="hostingplan",
name="database_limit",
field=models.PositiveIntegerField(
blank=True,
help_text="Leave blank for unlimited. Enter 0 to block new database requests.",
null=True,
),
),
migrations.AddField(
model_name="hostingplan",
name="mailbox_limit",
field=models.PositiveIntegerField(
blank=True,
help_text="Leave blank for unlimited. Enter 0 to block new mailbox requests.",
null=True,
),
),
]
+30 -1
View File
@@ -21,7 +21,7 @@ class Reseller(models.Model):
settings.AUTH_USER_MODEL, settings.AUTH_USER_MODEL,
on_delete=models.PROTECT, on_delete=models.PROTECT,
related_name="hosting_reseller", related_name="hosting_reseller",
limit_choices_to={"is_superuser": False}, limit_choices_to={"is_superuser": False, "hosting_customer__isnull": True},
) )
account_limit = models.PositiveIntegerField(default=0) account_limit = models.PositiveIntegerField(default=0)
hosting_plans = models.ManyToManyField("HostingPlan", blank=True) hosting_plans = models.ManyToManyField("HostingPlan", blank=True)
@@ -33,9 +33,35 @@ class Reseller(models.Model):
return self.user.get_username() return self.user.get_username()
class Customer(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.PROTECT,
related_name="hosting_customer",
limit_choices_to={
"is_staff": False,
"is_superuser": False,
"hosting_reseller__isnull": True,
},
)
def __str__(self):
return self.user.get_username()
class HostingPlan(models.Model): class HostingPlan(models.Model):
name = models.CharField(max_length=120, unique=True) name = models.CharField(max_length=120, unique=True)
description = models.CharField(max_length=240, blank=True) description = models.CharField(max_length=240, blank=True)
database_limit = models.PositiveIntegerField(
blank=True,
null=True,
help_text="Leave blank for unlimited. Enter 0 to block new database requests.",
)
mailbox_limit = models.PositiveIntegerField(
blank=True,
null=True,
help_text="Leave blank for unlimited. Enter 0 to block new mailbox requests.",
)
class Meta: class Meta:
ordering = ("name", "pk") ordering = ("name", "pk")
@@ -53,6 +79,9 @@ class HostingAccount(models.Model):
reseller = models.ForeignKey( reseller = models.ForeignKey(
Reseller, on_delete=models.PROTECT, null=True, blank=True Reseller, on_delete=models.PROTECT, null=True, blank=True
) )
customer = models.ForeignKey(
Customer, on_delete=models.PROTECT, null=True, blank=True
)
created_at = models.DateTimeField(auto_now_add=True) created_at = models.DateTimeField(auto_now_add=True)
def get_absolute_url(self): def get_absolute_url(self):
+62
View File
@@ -0,0 +1,62 @@
from django.core.exceptions import ValidationError
from django.db import connection, transaction
from django.db.models import F
from coulobre.mail_node import MailboxSpec
from .models import HostingAccount, HostingMailbox, HostingMailDomain
def lock_hosting_account(account_id, customer_id):
accounts = HostingAccount.objects.filter(pk=account_id)
if customer_id is not None:
accounts = accounts.filter(customer_id=customer_id)
if connection.vendor == "sqlite":
# Acquire the write lock before reading the account and resource counts.
accounts.update(hosting_plan=F("hosting_plan"))
return accounts.select_for_update().get()
@transaction.atomic
def create_database_request(account_id, suffix, *, customer_id=None):
account = lock_hosting_account(account_id, customer_id)
databases = account.databases
if databases.filter(suffix=suffix).exists():
raise ValidationError(
{"suffix": "This account already has a database with that suffix."}
)
plan = account.hosting_plan
if (
plan
and plan.database_limit is not None
and databases.count() >= plan.database_limit
):
raise ValidationError("This hosting account has reached its database limit.")
return databases.create(suffix=suffix)
@transaction.atomic
def create_mailbox_request(account_id, local_part, *, customer_id=None):
account = lock_hosting_account(account_id, customer_id)
try:
spec = MailboxSpec(account.primary_domain, local_part)
except ValueError as error:
raise ValidationError({"local_part": str(error)}) from error
mail_domain, _ = HostingMailDomain.objects.get_or_create(
domain=spec.domain, defaults={"account": account}
)
if mail_domain.account_id != account.pk:
raise ValidationError("This mail domain belongs to another hosting account.")
if mail_domain.mailboxes.filter(local_part=spec.local_part).exists():
raise ValidationError(
{"local_part": "This mailbox has already been requested."}
)
plan = account.hosting_plan
if plan and plan.mailbox_limit is not None:
mailboxes = HostingMailbox.objects.filter(mail_domain__account=account)
if mailboxes.count() >= plan.mailbox_limit:
raise ValidationError("This hosting account has reached its mailbox limit.")
return mail_domain.mailboxes.create(local_part=spec.local_part)
+21 -2
View File
@@ -159,6 +159,25 @@ button, input, select, textarea {
background: linear-gradient(currentColor, currentColor) center 35% / 40% 1px no-repeat; background: linear-gradient(currentColor, currentColor) center 35% / 40% 1px no-repeat;
} }
.nav-icon-customers {
position: relative;
height: 0.46rem;
margin-top: 0.47rem;
border-radius: 0.4rem 0.4rem 2px 2px;
}
.nav-icon-customers::before {
position: absolute;
left: 50%;
bottom: calc(100% + 2px);
width: 0.39rem;
height: 0.39rem;
transform: translateX(-50%);
border: 1px solid currentColor;
border-radius: 50%;
content: "";
}
.sidebar-account { .sidebar-account {
display: grid; display: grid;
gap: 0.3rem; gap: 0.3rem;
@@ -439,12 +458,12 @@ dd {
font-weight: 680; font-weight: 680;
} }
.status.ready { .status.ready, .status.active {
background: #dcebdc; background: #dcebdc;
color: #205038; color: #205038;
} }
.status.pending { .status.pending, .status.suspended {
background: #f5ead6; background: #f5ead6;
color: #6b431b; color: #6b431b;
} }
@@ -7,25 +7,28 @@
<h1>{{ account.name }}</h1> <h1>{{ account.name }}</h1>
<p class="heading-meta domain">{{ account.primary_domain }}</p> <p class="heading-meta domain">{{ account.primary_domain }}</p>
</div> </div>
{% if not is_reseller and perms.hosting.change_hostingaccount %} {% if is_operator and perms.hosting.change_hostingaccount %}
<a class="button secondary" href="{% url 'panel:account_edit' account.pk %}">Edit account</a> <a class="button secondary" href="{% url 'panel:account_edit' account.pk %}">Edit account</a>
{% endif %} {% endif %}
</header> </header>
<dl class="details surface"> <dl class="details surface">
<div><dt>Primary domain</dt><dd class="domain">{{ account.primary_domain }}</dd></div> <div><dt>Primary domain</dt><dd class="domain">{{ account.primary_domain }}</dd></div>
{% if is_reseller or perms.hosting.view_hostingplan %} {% if is_tenant or perms.hosting.view_hostingplan %}
<div><dt>Hosting plan</dt><dd>{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}Unassigned{% endif %}</dd></div> <div><dt>Hosting plan</dt><dd>{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}Unassigned{% endif %}</dd></div>
{% endif %} {% endif %}
{% if not is_reseller and perms.hosting.view_reseller %} {% if is_operator and perms.hosting.view_reseller %}
<div><dt>Reseller</dt><dd>{{ account.reseller|default_if_none:"Unassigned" }}</dd></div> <div><dt>Reseller</dt><dd>{{ account.reseller|default_if_none:"Unassigned" }}</dd></div>
{% endif %} {% endif %}
{% if is_operator and perms.hosting.view_customer %}
<div><dt>Customer</dt><dd>{{ account.customer|default_if_none:"Unassigned" }}</dd></div>
{% endif %}
<div><dt>Added</dt><dd>{{ account.created_at|date:"j M Y, H:i" }} UTC</dd></div> <div><dt>Added</dt><dd>{{ account.created_at|date:"j M Y, H:i" }} UTC</dd></div>
</dl> </dl>
{% if is_reseller or perms.hosting.view_webprovisioningplan %} {% if is_reseller or is_operator and perms.hosting.view_webprovisioningplan %}
<section class="surface" aria-labelledby="previews-heading"> <section class="surface" aria-labelledby="previews-heading">
<header class="section-heading"> <header class="section-heading">
<h2 id="previews-heading">Recent Apache previews</h2> <h2 id="previews-heading">Recent Apache previews</h2>
{% if not is_reseller and perms.hosting.change_hostingaccount %} {% if is_operator and perms.hosting.change_hostingaccount %}
<form method="post" action="{% url 'panel:request_plan' account.pk %}"> <form method="post" action="{% url 'panel:request_plan' account.pk %}">
{% csrf_token %} {% csrf_token %}
<button class="button primary" type="submit">Request Apache preview</button> <button class="button primary" type="submit">Request Apache preview</button>
@@ -35,23 +38,30 @@
{% include "hosting/plan_table.html" %} {% include "hosting/plan_table.html" %}
</section> </section>
{% endif %} {% endif %}
{% if is_reseller or perms.hosting.view_hostingdatabase %} {% if is_tenant or perms.hosting.view_hostingdatabase %}
<section class="surface" aria-labelledby="databases-heading"> <section class="surface" aria-labelledby="databases-heading">
<header class="section-heading"> <header class="section-heading">
<div>
<h2 id="databases-heading">MariaDB database requests</h2> <h2 id="databases-heading">MariaDB database requests</h2>
{% if not is_reseller and perms.hosting.add_hostingdatabase %} {% if is_tenant or perms.hosting.view_hostingplan %}
{% if account.hosting_plan and account.hosting_plan.database_limit is not None %}
<p class="heading-meta">{{ databases|length }} of {{ account.hosting_plan.database_limit }} databases requested</p>
{% endif %}
{% endif %}
</div>
{% if is_customer or is_operator and perms.hosting.add_hostingdatabase %}
<a class="button primary" href="{% url 'panel:database_create' account.pk %}">Request database</a> <a class="button primary" href="{% url 'panel:database_create' account.pk %}">Request database</a>
{% endif %} {% endif %}
</header> </header>
{% if databases %} {% if databases %}
<div class="table-scroll"> <div class="table-scroll">
<table> <table>
<thead><tr><th scope="col">Database</th>{% if not is_reseller %}<th scope="col">Deployment</th>{% endif %}</tr></thead> <thead><tr><th scope="col">Database</th>{% if is_operator %}<th scope="col">Deployment</th>{% endif %}</tr></thead>
<tbody> <tbody>
{% for database in databases %} {% for database in databases %}
<tr> <tr>
<td class="domain">{{ database }}</td> <td class="domain">{{ database }}</td>
{% if not is_reseller %} {% if is_operator %}
<td><a class="record-link" href="{% url 'panel:database_manifest' database.pk %}" aria-label="Download manifest for {{ database }}">Download manifest</a></td> <td><a class="record-link" href="{% url 'panel:database_manifest' database.pk %}" aria-label="Download manifest for {{ database }}">Download manifest</a></td>
{% endif %} {% endif %}
</tr> </tr>
@@ -64,11 +74,11 @@
{% endif %} {% endif %}
</section> </section>
{% endif %} {% endif %}
{% if is_reseller or perms.hosting.view_hostingdnszone %} {% if is_tenant or perms.hosting.view_hostingdnszone %}
<section class="surface" aria-labelledby="dns-zones-heading"> <section class="surface" aria-labelledby="dns-zones-heading">
<header class="section-heading"> <header class="section-heading">
<h2 id="dns-zones-heading">DNS zones</h2> <h2 id="dns-zones-heading">DNS zones</h2>
{% if not is_reseller and perms.hosting.add_hostingdnszone and not has_primary_zone %} {% if is_operator and perms.hosting.add_hostingdnszone and not has_primary_zone %}
<a class="button primary" href="{% url 'panel:dns_zone_create' account.pk %}">Add DNS zone</a> <a class="button primary" href="{% url 'panel:dns_zone_create' account.pk %}">Add DNS zone</a>
{% endif %} {% endif %}
</header> </header>
@@ -79,21 +89,21 @@
<tr> <tr>
<th scope="col">Domain</th> <th scope="col">Domain</th>
<th scope="col">SOA serial</th> <th scope="col">SOA serial</th>
{% if not is_reseller %}<th scope="col">Deployment</th>{% endif %} {% if is_operator %}<th scope="col">Deployment</th>{% endif %}
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{% for zone in dns_zones %} {% for zone in dns_zones %}
<tr> <tr>
<td class="domain"> <td class="domain">
{% if not is_reseller and perms.hosting.change_hostingdnszone %} {% if is_operator and perms.hosting.change_hostingdnszone %}
<a class="record-link" href="{% url 'panel:dns_zone_edit' zone.pk %}" aria-label="Edit DNS zone for {{ zone.domain }}">{{ zone.domain }}</a> <a class="record-link" href="{% url 'panel:dns_zone_edit' zone.pk %}" aria-label="Edit DNS zone for {{ zone.domain }}">{{ zone.domain }}</a>
{% else %} {% else %}
{{ zone.domain }} {{ zone.domain }}
{% endif %} {% endif %}
</td> </td>
<td>{{ zone.serial }}</td> <td>{{ zone.serial }}</td>
{% if not is_reseller %} {% if is_operator %}
<td><a class="record-link" href="{% url 'panel:dns_zone_manifest' zone.pk %}" aria-label="Download DNS manifest for {{ zone.domain }}">Download manifest</a></td> <td><a class="record-link" href="{% url 'panel:dns_zone_manifest' zone.pk %}" aria-label="Download DNS manifest for {{ zone.domain }}">Download manifest</a></td>
{% endif %} {% endif %}
</tr> </tr>
@@ -106,11 +116,18 @@
{% endif %} {% endif %}
</section> </section>
{% endif %} {% endif %}
{% if is_reseller or perms.hosting.view_hostingmailbox %} {% if is_tenant or perms.hosting.view_hostingmailbox %}
<section class="surface" aria-labelledby="mailboxes-heading"> <section class="surface" aria-labelledby="mailboxes-heading">
<header class="section-heading"> <header class="section-heading">
<div>
<h2 id="mailboxes-heading">Mailbox requests</h2> <h2 id="mailboxes-heading">Mailbox requests</h2>
{% if not is_reseller and perms.hosting.add_hostingmailbox %} {% if is_tenant or perms.hosting.view_hostingplan %}
{% if account.hosting_plan and account.hosting_plan.mailbox_limit is not None %}
<p class="heading-meta">{{ mailboxes|length }} of {{ account.hosting_plan.mailbox_limit }} mailboxes requested</p>
{% endif %}
{% endif %}
</div>
{% if is_customer or is_operator and perms.hosting.add_hostingmailbox %}
<a class="button primary" href="{% url 'panel:mailbox_create' account.pk %}">Request mailbox</a> <a class="button primary" href="{% url 'panel:mailbox_create' account.pk %}">Request mailbox</a>
{% endif %} {% endif %}
</header> </header>
@@ -120,14 +137,14 @@
<thead> <thead>
<tr> <tr>
<th scope="col">Email address</th> <th scope="col">Email address</th>
{% if not is_reseller %}<th scope="col">Deployment</th>{% endif %} {% if is_operator %}<th scope="col">Deployment</th>{% endif %}
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{% for mailbox in mailboxes %} {% for mailbox in mailboxes %}
<tr> <tr>
<td class="domain">{{ mailbox }}</td> <td class="domain">{{ mailbox }}</td>
{% if not is_reseller %} {% if is_operator %}
<td><a class="record-link" href="{% url 'panel:mailbox_manifest' mailbox.pk %}" aria-label="Download mailbox manifest for {{ mailbox }}">Download manifest</a></td> <td><a class="record-link" href="{% url 'panel:mailbox_manifest' mailbox.pk %}" aria-label="Download mailbox manifest for {{ mailbox }}">Download manifest</a></td>
{% endif %} {% endif %}
</tr> </tr>
@@ -7,7 +7,7 @@
<p class="heading-meta">{{ paginator.count }} account{{ paginator.count|pluralize }}{% if search %} matching your search{% endif %}</p> <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 %} {% if account_allowance %}<p class="heading-meta">{{ account_allowance.used }} of {{ account_allowance.limit }} accounts allocated</p>{% endif %}
</div> </div>
{% if account_allowance and account_allowance.used < account_allowance.limit or not is_reseller and perms.hosting.add_hostingaccount %} {% if account_allowance 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> <a class="button primary" href="{% url 'panel:account_create' %}">Add hosting account</a>
{% endif %} {% endif %}
</header> </header>
@@ -25,7 +25,7 @@
<tr> <tr>
<th scope="col">Account</th> <th scope="col">Account</th>
<th scope="col">Primary domain</th> <th scope="col">Primary domain</th>
{% if is_reseller or perms.hosting.view_hostingplan %}<th scope="col">Hosting plan</th>{% endif %} {% if is_tenant or perms.hosting.view_hostingplan %}<th scope="col">Hosting plan</th>{% endif %}
<th scope="col" class="cell-date">Added</th> <th scope="col" class="cell-date">Added</th>
</tr> </tr>
</thead> </thead>
@@ -34,7 +34,7 @@
<tr> <tr>
<td><a class="record-link" href="{{ account.get_absolute_url }}">{{ account.name }}</a></td> <td><a class="record-link" href="{{ account.get_absolute_url }}">{{ account.name }}</a></td>
<td class="domain">{{ account.primary_domain }}</td> <td class="domain">{{ account.primary_domain }}</td>
{% if is_reseller or perms.hosting.view_hostingplan %} {% if is_tenant or perms.hosting.view_hostingplan %}
<td>{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}<span class="muted">Unassigned</span>{% endif %}</td> <td>{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}<span class="muted">Unassigned</span>{% endif %}</td>
{% endif %} {% endif %}
<td class="cell-date muted">{{ account.created_at|date:"j M Y" }}</td> <td class="cell-date muted">{{ account.created_at|date:"j M Y" }}</td>
@@ -17,19 +17,25 @@
</a> </a>
<nav class="navigation" aria-label="Main navigation"> <nav class="navigation" aria-label="Main navigation">
{% with current=request.resolver_match.url_name %} {% with current=request.resolver_match.url_name %}
{% if is_reseller or perms.hosting.view_hostingaccount %} {% if is_tenant or perms.hosting.view_hostingaccount %}
<a href="{% url 'panel:accounts' %}"{% if current == 'accounts' or current == 'account' or current == 'account_create' or current == 'account_edit' or current == 'database_create' %} aria-current="page"{% endif %}> <a href="{% url 'panel:accounts' %}"{% if current == 'accounts' or current == 'account' or current == 'account_create' or current == 'account_edit' or current == 'database_create' %} aria-current="page"{% endif %}>
<span class="nav-icon nav-icon-accounts" aria-hidden="true"></span> <span class="nav-icon nav-icon-accounts" aria-hidden="true"></span>
Hosting accounts Hosting accounts
</a> </a>
{% endif %} {% endif %}
{% if not is_reseller and perms.hosting.view_hostingplan %} {% if is_operator and perms.hosting.view_customer %}
<a href="{% url 'panel:customers' %}"{% if current == 'customers' or current == 'customer_create' %} aria-current="page"{% endif %}>
<span class="nav-icon nav-icon-customers" aria-hidden="true"></span>
Customers
</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 %}> <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> <span class="nav-icon nav-icon-packages" aria-hidden="true"></span>
Hosting plans Hosting plans
</a> </a>
{% endif %} {% endif %}
{% if is_reseller or perms.hosting.view_webprovisioningplan %} {% if is_reseller or is_operator and perms.hosting.view_webprovisioningplan %}
<a href="{% url 'panel:plans' %}"{% if current == 'plans' or current == 'plan' %} aria-current="page"{% endif %}> <a href="{% url 'panel:plans' %}"{% if current == 'plans' or current == 'plan' %} aria-current="page"{% endif %}>
<span class="nav-icon nav-icon-plans" aria-hidden="true"></span> <span class="nav-icon nav-icon-plans" aria-hidden="true"></span>
Web provisioning Web provisioning
@@ -0,0 +1,16 @@
{% extends "hosting/base.html" %}
{% block title %}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>
<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>
</div>
</form>
</section>
{% endblock %}
@@ -0,0 +1,61 @@
{% extends "hosting/base.html" %}
{% block title %}Customers · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading">
<h1>Customers</h1>
{% if perms.hosting.add_customer %}
<a class="button primary" href="{% url 'panel:customer_create' %}">Add customer</a>
{% endif %}
</header>
<section class="surface" aria-label="Customer list">
<form class="toolbar" method="get" action="{% url 'panel:customers' %}" role="search">
<label class="visually-hidden" for="customer-search">Search customers by username</label>
<input type="search" id="customer-search" name="q" placeholder="Username" value="{{ search }}">
<button class="button secondary" type="submit">Search</button>
{% if search %}<a class="quiet-link" href="{% url 'panel:customers' %}">Clear</a>{% endif %}
</form>
{% if customers %}
<div class="table-scroll">
<table>
<thead>
<tr>
<th scope="col">Username</th>
<th scope="col">Sign-in status</th>
{% if perms.hosting.change_customer %}<th scope="col">Actions</th>{% endif %}
</tr>
</thead>
<tbody>
{% for customer in customers %}
<tr>
<td><strong>{{ customer }}</strong></td>
<td>
{% 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 %}
<td>
{% if not customer.user.is_staff and not customer.user.is_superuser and not customer.user.hosting_reseller %}
<form method="post" action="{% url 'panel:customer_access' customer.pk %}{% querystring %}">
{% csrf_token %}
{% if customer.user.is_active %}
<button class="button secondary" type="submit" name="access" value="suspend" aria-label="Suspend sign-in for {{ customer }}">Suspend sign-in</button>
{% else %}
<button class="button secondary" type="submit" name="access" value="restore" aria-label="Restore sign-in for {{ customer }}">Restore sign-in</button>
{% endif %}
</form>
{% endif %}
</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% elif search %}
<p class="empty">No customers match this search.</p>
{% else %}
<p class="empty">No customers yet.</p>
{% endif %}
{% include "hosting/pagination.html" %}
</section>
{% endblock %}
@@ -11,7 +11,14 @@
{% if hosting_plans %} {% if hosting_plans %}
<div class="table-scroll"> <div class="table-scroll">
<table> <table>
<thead><tr><th scope="col">Plan</th><th scope="col">Description</th></tr></thead> <thead>
<tr>
<th scope="col">Plan</th>
<th scope="col">Description</th>
<th scope="col">Database limit</th>
<th scope="col">Mailbox limit</th>
</tr>
</thead>
<tbody> <tbody>
{% for hosting_plan in hosting_plans %} {% for hosting_plan in hosting_plans %}
<tr> <tr>
@@ -23,6 +30,8 @@
{% endif %} {% endif %}
</td> </td>
<td>{{ hosting_plan.description|default:"—" }}</td> <td>{{ hosting_plan.description|default:"—" }}</td>
<td>{{ hosting_plan.database_limit|default_if_none:"Unlimited" }}</td>
<td>{{ hosting_plan.mailbox_limit|default_if_none:"Unlimited" }}</td>
</tr> </tr>
{% endfor %} {% endfor %}
</tbody> </tbody>
+418
View File
@@ -0,0 +1,418 @@
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import TestCase
from django.urls import reverse
from .models import (
Customer,
HostingAccount,
HostingDatabase,
HostingDnsZone,
HostingMailbox,
HostingMailDomain,
HostingPlan,
Reseller,
WebProvisioningPlan,
)
from .resource_requests import create_database_request
from .views import DatabaseCreate
class CustomerAccessTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_superuser("operator")
cls.alice = users.create_user("alice", password="test-customer-password")
cls.bob = users.create_user("bob")
cls.customer = Customer.objects.create(user=cls.alice)
cls.other_customer = Customer.objects.create(user=cls.bob)
cls.package = HostingPlan.objects.create(name="Starter")
cls.account = HostingAccount.objects.create(
name="Alice website",
primary_domain="alice.example",
customer=cls.customer,
hosting_plan=cls.package,
)
cls.other_account = HostingAccount.objects.create(
name="Bob website",
primary_domain="bob.example",
customer=cls.other_customer,
)
cls.unassigned_account = HostingAccount.objects.create(
name="Unassigned website",
primary_domain="unassigned.example",
)
cls.database = HostingDatabase.objects.create(account=cls.account, suffix="cms")
cls.zone = HostingDnsZone.objects.create(
account=cls.account,
domain="alice.example",
serial=123456789,
nameservers=["ns1.provider.example", "ns2.provider.example"],
responsible_name="hostmaster.alice.example",
)
mail_domain = HostingMailDomain.objects.create(
account=cls.account, domain="alice.example"
)
cls.mailbox = HostingMailbox.objects.create(
mail_domain=mail_domain, local_part="support"
)
cls.preview = WebProvisioningPlan.for_account(cls.account)
cls.preview.save()
def test_customer_can_sign_in_and_see_only_assigned_accounts(self):
additional = HostingAccount.objects.create(
name="Alice blog", primary_domain="blog.example", customer=self.customer
)
self.assertRedirects(
self.client.post(
reverse("panel:login"),
{"username": "alice", "password": "test-customer-password"},
),
reverse("panel:accounts"),
)
accounts = self.client.get(reverse("panel:accounts"))
self.assertContains(accounts, self.account.name)
self.assertContains(accounts, additional.name)
self.assertContains(accounts, self.package.name)
self.assertNotContains(accounts, self.other_account.name)
self.assertNotContains(accounts, self.unassigned_account.name)
self.assertContains(
self.client.get(reverse("panel:accounts"), {"q": "bob.example"}),
"No hosting accounts match this search.",
)
detail = self.client.get(self.account.get_absolute_url())
self.assertContains(detail, str(self.database))
self.assertContains(detail, str(self.zone.serial))
self.assertContains(detail, "support@alice.example")
for account in (self.other_account, self.unassigned_account):
with self.subTest(account=account):
self.assertEqual(
self.client.get(account.get_absolute_url()).status_code, 404
)
def test_operator_permissions_do_not_widen_customer_access(self):
self.alice.is_staff = True
self.alice.save(update_fields=["is_staff"])
self.alice.user_permissions.add(
*Permission.objects.filter(content_type__app_label="hosting")
)
reseller = Reseller.objects.create(user=self.alice, account_limit=2)
self.unassigned_account.reseller = reseller
self.unassigned_account.save(update_fields=["reseller"])
self.client.force_login(self.alice)
accounts = self.client.get(reverse("panel:accounts"))
self.assertContains(accounts, self.account.name)
for label in (
self.unassigned_account.name,
"Add hosting account",
"Web provisioning",
):
self.assertNotContains(accounts, label)
detail = self.client.get(self.account.get_absolute_url())
for label in (
"Edit account",
"Recent Apache previews",
"Download manifest",
):
self.assertNotContains(detail, label)
for route, args in (
("panel:plans", ()),
("panel:plan", (self.preview.pk,)),
("panel:download_deployment_manifest", (self.preview.pk,)),
("panel:download_smoke_bundle", (self.preview.pk,)),
("panel:database_manifest", (self.database.pk,)),
("panel:dns_zone_manifest", (self.zone.pk,)),
("panel:mailbox_manifest", (self.mailbox.pk,)),
("panel:hosting_plans", ()),
):
with self.subTest(route=route):
self.assertEqual(
self.client.get(reverse(route, args=args)).status_code, 403
)
for route, args in (
("panel:account_create", ()),
("panel:account_edit", (self.account.pk,)),
("panel:request_plan", (self.account.pk,)),
("panel:dns_zone_create", (self.account.pk,)),
("panel:dns_zone_edit", (self.zone.pk,)),
):
with self.subTest(route=route):
self.assertEqual(
self.client.post(reverse(route, args=args)).status_code, 403
)
admin_url = reverse("admin:hosting_hostingaccount_changelist")
self.assertRedirects(
self.client.get(admin_url), f"{reverse('admin:login')}?next={admin_url}"
)
def test_customer_can_request_databases_and_mailboxes_up_to_the_plan_limits(self):
HostingPlan.objects.filter(pk=self.package.pk).update(
database_limit=2, mailbox_limit=2
)
self.client.force_login(self.alice)
account_url = self.account.get_absolute_url()
detail = self.client.get(account_url)
self.assertContains(detail, "Request database")
self.assertContains(detail, "Request mailbox")
database_url = reverse("panel:database_create", args=[self.account.pk])
self.assertContains(self.client.get(database_url), "Request MariaDB database")
self.assertRedirects(
self.client.post(database_url, {"suffix": "shop"}), account_url
)
self.assertContains(
self.client.post(database_url, {"suffix": "another"}),
"This hosting account has reached its database limit.",
)
self.assertEqual(self.account.databases.count(), 2)
mailbox_url = reverse("panel:mailbox_create", args=[self.account.pk])
self.assertContains(self.client.get(mailbox_url), "Request mailbox")
self.assertRedirects(
self.client.post(mailbox_url, {"local_part": "Sales"}), account_url
)
self.assertContains(
self.client.post(mailbox_url, {"local_part": "billing"}),
"This hosting account has reached its mailbox limit.",
)
self.assertEqual(
HostingMailbox.objects.filter(mail_domain__account=self.account).count(), 2
)
self.assertContains(self.client.get(account_url), "sales@alice.example")
def test_customer_cannot_open_or_submit_resource_forms_for_other_accounts(self):
self.alice.user_permissions.add(
*Permission.objects.filter(content_type__app_label="hosting")
)
self.client.force_login(self.alice)
for account in (self.other_account, self.unassigned_account):
for route, data in (
("panel:database_create", {"suffix": "shop"}),
("panel:mailbox_create", {"local_part": "sales"}),
):
with self.subTest(account=account, route=route):
url = reverse(route, args=[account.pk])
self.assertEqual(self.client.get(url).status_code, 404)
self.assertEqual(self.client.post(url, data).status_code, 404)
self.assertEqual(HostingDatabase.objects.count(), 1)
self.assertEqual(HostingMailbox.objects.count(), 1)
def test_database_request_rechecks_customer_assignment_before_writing(self):
self.client.force_login(self.alice)
def reassign_before_create(account_id, **kwargs):
HostingAccount.objects.filter(pk=account_id).update(
customer=self.other_customer
)
return create_database_request(account_id, **kwargs)
with patch.object(
DatabaseCreate, "create_request", side_effect=reassign_before_create
):
response = self.client.post(
reverse("panel:database_create", args=[self.account.pk]),
{"suffix": "shop"},
)
self.assertEqual(response.status_code, 404)
self.assertFalse(self.account.databases.filter(suffix="shop").exists())
def test_operator_can_create_customer_and_reassign_existing_account(self):
user = get_user_model().objects.create_user("charlie")
self.client.force_login(self.operator)
self.assertRedirects(
self.client.post(reverse("admin:hosting_customer_add"), {"user": user.pk}),
reverse("admin:hosting_customer_changelist"),
)
customer = Customer.objects.get(user=user)
self.assertRedirects(
self.client.post(
reverse("panel:account_edit", args=[self.account.pk]),
{
"name": self.account.name,
"primary_domain": self.account.primary_domain,
"hosting_plan": self.package.pk,
"customer": customer.pk,
},
),
self.account.get_absolute_url(),
)
view_accounts = Permission.objects.get(codename="view_hostingaccount")
self.alice.user_permissions.add(view_accounts)
self.client.force_login(self.alice)
self.assertEqual(
self.client.get(self.account.get_absolute_url()).status_code, 404
)
self.assertContains(
self.client.get(reverse("panel:accounts")), "No hosting accounts yet."
)
self.client.force_login(user)
self.assertContains(
self.client.get(self.account.get_absolute_url()), self.account.name
)
class CustomerManagementTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_user("operator", is_staff=True)
cls.operator.user_permissions.add(
*Permission.objects.filter(
content_type__app_label="hosting",
codename__in=(
"view_customer",
"add_customer",
"change_customer",
"view_hostingaccount",
"add_hostingaccount",
),
)
)
cls.customer = Customer.objects.create(user=users.create_user("alice"))
cls.account = HostingAccount.objects.create(
name="Alice hosting", primary_domain="alice.example", customer=cls.customer
)
def test_operator_can_create_customer_and_assign_hosting_in_the_panel(self):
self.client.force_login(self.operator)
customers = reverse("panel:customers")
self.assertContains(self.client.get(customers), "Add customer")
password = "initial-correct-horse-battery-staple"
self.assertRedirects(
self.client.post(
reverse("panel:customer_create"),
{
"username": "charlie",
"password1": password,
"password2": password,
"is_staff": "on",
"is_superuser": "on",
},
),
customers,
)
charlie = Customer.objects.select_related("user").get(user__username="charlie")
self.assertFalse(charlie.user.is_staff)
self.assertFalse(charlie.user.is_superuser)
results = self.client.get(customers, {"q": "CHARLIE"})
self.assertContains(results, "charlie")
self.assertNotContains(results, "alice")
response = self.client.post(
reverse("panel:account_create"),
{
"name": "Charlie hosting",
"primary_domain": "charlie.example",
"customer": charlie.pk,
},
)
account = HostingAccount.objects.get(customer=charlie)
self.assertRedirects(response, account.get_absolute_url())
self.client.logout()
self.assertRedirects(
self.client.post(
reverse("panel:login"), {"username": "charlie", "password": password}
),
reverse("panel:accounts"),
)
self.assertContains(self.client.get(reverse("panel:accounts")), account.name)
def test_customer_creation_preserves_existing_users_and_validates_passwords(self):
self.client.force_login(self.operator)
existing = get_user_model().objects.create_user("existing")
url = reverse("panel:customer_create")
password = "initial-correct-horse-battery-staple"
duplicate = self.client.post(
url, {"username": "Existing", "password1": password, "password2": password}
)
self.assertIn("username", duplicate.context["form"].errors)
self.assertFalse(Customer.objects.filter(user=existing).exists())
invalid = self.client.post(
url, {"username": "new", "password1": "123", "password2": "123"}
)
self.assertIn("password2", invalid.context["form"].errors)
self.assertFalse(get_user_model().objects.filter(username="new").exists())
def test_suspend_blocks_an_existing_session_and_preserves_assignments(self):
self.client.force_login(self.customer.user)
self.assertContains(
self.client.get(self.account.get_absolute_url()), self.account.name
)
operator_client = self.client_class()
operator_client.force_login(self.operator)
url = reverse("panel:customer_access", args=[self.customer.pk])
customers = reverse("panel:customers")
self.assertEqual(operator_client.get(url).status_code, 405)
self.assertEqual(operator_client.post(url, {}).status_code, 400)
for _ in range(2):
self.assertRedirects(
operator_client.post(url, {"access": "suspend"}), customers
)
self.assertContains(operator_client.get(customers), "Suspended")
account_url = self.account.get_absolute_url()
self.assertRedirects(
self.client.get(account_url), f"{reverse('panel:login')}?next={account_url}"
)
self.account.refresh_from_db()
self.assertEqual(self.account.customer_id, self.customer.pk)
filtered = f"{customers}?q=alice"
self.assertContains(operator_client.get(filtered), f'action="{url}?q=alice"')
self.assertRedirects(
operator_client.post(f"{url}?q=alice", {"access": "restore"}), filtered
)
self.customer.user.refresh_from_db()
self.assertTrue(self.customer.user.is_active)
self.client.force_login(self.customer.user)
self.assertContains(self.client.get(account_url), self.account.name)
def test_customer_permissions_cannot_manage_other_customers(self):
self.customer.user.user_permissions.add(*self.operator.user_permissions.all())
self.client.force_login(self.customer.user)
self.assertNotContains(
self.client.get(reverse("panel:accounts")), reverse("panel:customers")
)
self.assertEqual(self.client.get(reverse("panel:customers")).status_code, 403)
self.assertEqual(
self.client.post(reverse("panel:customer_create")).status_code, 403
)
self.assertEqual(
self.client.post(
reverse("panel:customer_access", args=[self.customer.pk]),
{"access": "suspend"},
).status_code,
403,
)
def test_view_only_operator_and_privileged_logins_cannot_be_modified(self):
users = get_user_model().objects
reader = users.create_user("reader")
reader.user_permissions.add(Permission.objects.get(codename="view_customer"))
url = reverse("panel:customer_access", args=[self.customer.pk])
self.client.force_login(reader)
response = self.client.get(reverse("panel:customers"))
self.assertContains(response, "alice")
self.assertNotContains(response, "Add customer")
self.assertNotContains(response, "Suspend sign-in")
self.assertEqual(self.client.post(url, {"access": "suspend"}).status_code, 403)
self.assertEqual(
self.client.get(reverse("panel:customer_create")).status_code, 403
)
self.client.force_login(self.operator)
self.customer.user.is_staff = True
self.customer.user.save(update_fields=["is_staff"])
self.assertEqual(self.client.post(url, {"access": "suspend"}).status_code, 404)
self.customer.user.refresh_from_db()
self.assertTrue(self.customer.user.is_active)
+32 -1
View File
@@ -5,7 +5,7 @@ from django.urls import reverse
from coulobre.database_node import DatabaseSpec from coulobre.database_node import DatabaseSpec
from .models import HostingAccount, HostingDatabase, Reseller from .models import HostingAccount, HostingDatabase, HostingPlan, Reseller
class DatabaseRequestTests(TestCase): class DatabaseRequestTests(TestCase):
@@ -74,6 +74,37 @@ class DatabaseRequestTests(TestCase):
self.assertIn("suffix", response.context["form"].errors) self.assertIn("suffix", response.context["form"].errors)
self.assertFalse(HostingDatabase.objects.exists()) self.assertFalse(HostingDatabase.objects.exists())
def test_database_limit_is_per_account_and_uses_the_current_plan(self):
plan = HostingPlan.objects.create(name="Starter", database_limit=1)
HostingAccount.objects.update(hosting_plan=plan)
self.assertRedirects(
self.client.post(self.request_url, {"suffix": "cms"}),
self.account.get_absolute_url(),
)
capped = self.client.post(self.request_url, {"suffix": "shop"})
self.assertContains(
capped, "This hosting account has reached its database limit."
)
other_url = reverse("panel:database_create", args=[self.other_account.pk])
self.assertRedirects(
self.client.post(other_url, {"suffix": "cms"}),
self.other_account.get_absolute_url(),
)
zero = HostingPlan.objects.create(name="No databases", database_limit=0)
HostingAccount.objects.filter(pk=self.account.pk).update(hosting_plan=zero)
self.assertContains(
self.client.get(self.account.get_absolute_url()),
"1 of 0 databases requested",
)
capped = self.client.post(self.request_url, {"suffix": "shop"})
self.assertContains(
capped, "This hosting account has reached its database limit."
)
self.assertEqual(
list(self.account.databases.values_list("suffix", flat=True)), ["cms"]
)
def test_reseller_view_is_scoped_and_node_actions_require_an_operator(self): def test_reseller_view_is_scoped_and_node_actions_require_an_operator(self):
owned = HostingDatabase.objects.create(account=self.account, suffix="wordpress") owned = HostingDatabase.objects.create(account=self.account, suffix="wordpress")
HostingDatabase.objects.create(account=self.other_account, suffix="othersite") HostingDatabase.objects.create(account=self.other_account, suffix="othersite")
+28 -2
View File
@@ -30,10 +30,17 @@ class HostingPlanTests(TestCase):
list_url = reverse("panel:hosting_plans") list_url = reverse("panel:hosting_plans")
response = self.client.post( response = self.client.post(
reverse("panel:hosting_plan_create"), reverse("panel:hosting_plan_create"),
{"name": "Starter", "description": "Shared hosting for small sites"}, {
"name": "Starter",
"description": "Shared hosting for small sites",
"database_limit": 0,
"mailbox_limit": 5,
},
) )
self.assertRedirects(response, list_url) self.assertRedirects(response, list_url)
plan = HostingPlan.objects.get() plan = HostingPlan.objects.get()
self.assertEqual(plan.database_limit, 0)
self.assertEqual(plan.mailbox_limit, 5)
self.assertContains( self.assertContains(
self.client.get(self.account.get_absolute_url()), "Unassigned" self.client.get(self.account.get_absolute_url()), "Unassigned"
@@ -52,9 +59,18 @@ class HostingPlanTests(TestCase):
response = self.client.post( response = self.client.post(
reverse("panel:hosting_plan_edit", args=[plan.pk]), reverse("panel:hosting_plan_edit", args=[plan.pk]),
{"name": "Standard", "description": "Updated description"}, {
"name": "Standard",
"description": "Updated description",
"database_limit": "",
"mailbox_limit": 2,
},
) )
self.assertRedirects(response, list_url) self.assertRedirects(response, list_url)
plan.refresh_from_db()
self.assertIsNone(plan.database_limit)
self.assertEqual(plan.mailbox_limit, 2)
self.assertContains(self.client.get(list_url), "Unlimited")
self.assertContains(self.client.get(reverse("panel:accounts")), "Standard") self.assertContains(self.client.get(reverse("panel:accounts")), "Standard")
response = self.client.post( response = self.client.post(
@@ -69,6 +85,16 @@ class HostingPlanTests(TestCase):
self.assertRedirects(response, new_account.get_absolute_url()) self.assertRedirects(response, new_account.get_absolute_url())
self.assertEqual(new_account.hosting_plan_id, plan.pk) self.assertEqual(new_account.hosting_plan_id, plan.pk)
def test_plan_rejects_negative_limits(self):
self.client.force_login(self.operator)
response = self.client.post(
reverse("panel:hosting_plan_create"),
{"name": "Invalid plan", "database_limit": -1, "mailbox_limit": -2},
)
self.assertIn("database_limit", response.context["form"].errors)
self.assertIn("mailbox_limit", response.context["form"].errors)
self.assertFalse(HostingPlan.objects.exists())
def test_editor_without_plan_permission_cannot_assign_in_either_interface(self): def test_editor_without_plan_permission_cannot_assign_in_either_interface(self):
current = HostingPlan.objects.create(name="Private plan") current = HostingPlan.objects.create(name="Private plan")
other = HostingPlan.objects.create(name="Other plan") other = HostingPlan.objects.create(name="Other plan")
+42 -1
View File
@@ -10,7 +10,13 @@ from django.urls import reverse
from coulobre.mail_node import MailboxSpec, main from coulobre.mail_node import MailboxSpec, main
from .models import HostingAccount, HostingMailbox, HostingMailDomain, Reseller from .models import (
HostingAccount,
HostingMailbox,
HostingMailDomain,
HostingPlan,
Reseller,
)
class MailboxRequestTests(TestCase): class MailboxRequestTests(TestCase):
@@ -79,6 +85,41 @@ class MailboxRequestTests(TestCase):
self.assertIn("local_part", response.context["form"].errors) self.assertIn("local_part", response.context["form"].errors)
self.assertFalse(HostingMailDomain.objects.exists()) self.assertFalse(HostingMailDomain.objects.exists())
def test_mailbox_quota_counts_old_domains_and_preserves_existing_requests(self):
plan = HostingPlan.objects.create(name="Solo mail", mailbox_limit=1)
HostingAccount.objects.filter(pk=self.account.pk).update(hosting_plan=plan)
original = self.request_mailbox("support")
response = self.client.post(
reverse("panel:account_edit", args=[self.account.pk]),
{
"name": self.account.name,
"primary_domain": "new.example",
"hosting_plan": plan.pk,
},
)
self.assertRedirects(response, self.account.get_absolute_url())
self.assertContains(
self.client.get(self.account.get_absolute_url()),
"1 of 1 mailboxes requested",
)
capped = self.client.post(self.request_url, {"local_part": "billing"})
self.assertContains(
capped, "This hosting account has reached its mailbox limit."
)
self.assertEqual(HostingMailbox.objects.get(), original)
self.assertFalse(
HostingMailDomain.objects.filter(domain="new.example").exists()
)
HostingPlan.objects.filter(pk=plan.pk).update(mailbox_limit=2)
self.assertRedirects(
self.client.post(self.request_url, {"local_part": "billing"}),
self.account.get_absolute_url(),
)
self.assertEqual(
HostingMailbox.objects.get(local_part="billing").spec.domain, "new.example"
)
def test_renamed_account_keeps_existing_mail_and_prevents_domain_reassignment(self): def test_renamed_account_keeps_existing_mail_and_prevents_domain_reassignment(self):
original = self.request_mailbox("support") original = self.request_mailbox("support")
mail_domain = original.mail_domain.domain mail_domain = original.mail_domain.domain
+7
View File
@@ -19,6 +19,13 @@ urlpatterns = [
path("accounts/new/", views.AccountCreate.as_view(), name="account_create"), path("accounts/new/", views.AccountCreate.as_view(), name="account_create"),
path("accounts/<int:pk>/", views.AccountDetail.as_view(), name="account"), path("accounts/<int:pk>/", views.AccountDetail.as_view(), name="account"),
path("accounts/<int:pk>/edit/", views.AccountEdit.as_view(), name="account_edit"), path("accounts/<int:pk>/edit/", views.AccountEdit.as_view(), name="account_edit"),
path("customers/", views.CustomerList.as_view(), name="customers"),
path("customers/new/", views.CustomerCreate.as_view(), name="customer_create"),
path(
"customers/<int:pk>/access/",
views.CustomerAccess.as_view(),
name="customer_access",
),
path( path(
"accounts/<int:pk>/databases/new/", "accounts/<int:pk>/databases/new/",
views.DatabaseCreate.as_view(), views.DatabaseCreate.as_view(),
+143 -70
View File
@@ -1,30 +1,41 @@
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.mixins import PermissionRequiredMixin from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction from django.db import IntegrityError, transaction
from django.db.models import Q from django.db.models import Q
from django.http import HttpResponse, JsonResponse from django.http import Http404, HttpResponse, HttpResponseBadRequest, JsonResponse
from django.shortcuts import get_object_or_404, redirect from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse_lazy from django.urls import reverse, reverse_lazy
from django.utils.decorators import method_decorator
from django.utils.functional import cached_property from django.utils.functional import cached_property
from django.views import View from django.views import View
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic import CreateView, DetailView, FormView, ListView, UpdateView from django.views.generic import CreateView, DetailView, FormView, ListView, UpdateView
from django.views.generic.detail import SingleObjectMixin from django.views.generic.detail import SingleObjectMixin
from coulobre.dns_node import MAX_SOA_SERIAL from coulobre.dns_node import MAX_SOA_SERIAL
from coulobre.mail_node import INVALID_LOCAL_PART, MailboxSpec from coulobre.mail_node import INVALID_LOCAL_PART
from .access import OperatorOnlyMixin, ResellerScopeMixin, reseller_for_user from .access import (
OperatorOnlyMixin,
TenantScopeMixin,
customer_for_user,
reseller_for_user,
)
from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record
from .models import ( from .models import (
Customer,
HostingAccount, HostingAccount,
HostingDatabase, HostingDatabase,
HostingDnsZone, HostingDnsZone,
HostingMailbox, HostingMailbox,
HostingMailDomain,
HostingPlan, HostingPlan,
Reseller,
WebProvisioningPlan, WebProvisioningPlan,
) )
from .reseller_accounts import create_reseller_account from .reseller_accounts import create_reseller_account
from .resource_requests import create_database_request, create_mailbox_request
from .web_node import build_web_smoke_bundle, serialize_deployment_manifest from .web_node import build_web_smoke_bundle, serialize_deployment_manifest
VIEW_ACCOUNTS = "hosting.view_hostingaccount" VIEW_ACCOUNTS = "hosting.view_hostingaccount"
@@ -32,12 +43,13 @@ CHANGE_ACCOUNTS = "hosting.change_hostingaccount"
VIEW_PLANS = "hosting.view_webprovisioningplan" VIEW_PLANS = "hosting.view_webprovisioningplan"
VIEW_HOSTING_PLANS = "hosting.view_hostingplan" VIEW_HOSTING_PLANS = "hosting.view_hostingplan"
VIEW_RESELLERS = "hosting.view_reseller" VIEW_RESELLERS = "hosting.view_reseller"
VIEW_CUSTOMERS = "hosting.view_customer"
VIEW_DATABASES = "hosting.view_hostingdatabase" VIEW_DATABASES = "hosting.view_hostingdatabase"
VIEW_DNS_ZONES = "hosting.view_hostingdnszone" VIEW_DNS_ZONES = "hosting.view_hostingdnszone"
VIEW_MAILBOXES = "hosting.view_hostingmailbox" VIEW_MAILBOXES = "hosting.view_hostingmailbox"
class AccountList(ResellerScopeMixin, PermissionRequiredMixin, ListView): class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView):
queryset = HostingAccount.objects.select_related("hosting_plan").order_by( queryset = HostingAccount.objects.select_related("hosting_plan").order_by(
"primary_domain" "primary_domain"
) )
@@ -45,6 +57,7 @@ class AccountList(ResellerScopeMixin, PermissionRequiredMixin, ListView):
template_name = "hosting/account_list.html" template_name = "hosting/account_list.html"
context_object_name = "accounts" context_object_name = "accounts"
paginate_by = 20 paginate_by = 20
customer_relation = "customer"
def get_queryset(self): def get_queryset(self):
self.search = self.request.GET.get("q", "").strip()[:253] self.search = self.request.GET.get("q", "").strip()[:253]
@@ -78,6 +91,8 @@ class AccountEditor:
self.fields += ("hosting_plan",) self.fields += ("hosting_plan",)
if reseller is None and self.request.user.has_perm(VIEW_RESELLERS): if reseller is None and self.request.user.has_perm(VIEW_RESELLERS):
self.fields += ("reseller",) self.fields += ("reseller",)
if reseller is None and self.request.user.has_perm(VIEW_CUSTOMERS):
self.fields += ("customer",)
return super().get_form_class() return super().get_form_class()
def get_form(self, form_class=None): def get_form(self, form_class=None):
@@ -91,12 +106,12 @@ class AccountEditor:
field.queryset = reseller.hosting_plans.all() field.queryset = reseller.hosting_plans.all()
field.required = True field.required = True
field.empty_label = "Select a hosting plan" field.empty_label = "Select a hosting plan"
if "reseller" in form.fields: for name in ("reseller", "customer"):
form.fields["reseller"].empty_label = "Unassigned" if name in form.fields:
form.fields["reseller"].queryset = ( field = form.fields[name]
form.fields["reseller"] field.empty_label = "Unassigned"
.queryset.select_related("user") field.queryset = field.queryset.select_related("user").order_by(
.order_by("user__username") "user__username"
) )
return form return form
@@ -106,6 +121,8 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView):
extra_context = {"page_title": "Add hosting account", "submit_label": "Add account"} extra_context = {"page_title": "Add hosting account", "submit_label": "Add account"}
def has_permission(self): def has_permission(self):
if customer_for_user(self.request.user) is not None:
return False
reseller = reseller_for_user(self.request.user) reseller = reseller_for_user(self.request.user)
if reseller is not None: if reseller is not None:
return reseller.may_create_accounts() return reseller.may_create_accounts()
@@ -148,64 +165,147 @@ class AccountEdit(
return redirect(self.object) return redirect(self.object)
class AccountDetail(ResellerScopeMixin, PermissionRequiredMixin, DetailView): class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
queryset = HostingAccount.objects.select_related("hosting_plan", "reseller__user") queryset = HostingAccount.objects.select_related(
"hosting_plan", "reseller__user", "customer__user"
)
permission_required = VIEW_ACCOUNTS permission_required = VIEW_ACCOUNTS
template_name = "hosting/account_detail.html" template_name = "hosting/account_detail.html"
context_object_name = "account" context_object_name = "account"
customer_relation = "customer"
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs) context = super().get_context_data(**kwargs)
user = self.request.user user = self.request.user
reseller = reseller_for_user(user) reseller = reseller_for_user(user)
if reseller is not None or user.has_perm(VIEW_PLANS): customer = customer_for_user(user)
tenant = reseller is not None or customer is not None
if reseller is not None or (customer is None and user.has_perm(VIEW_PLANS)):
context["plans"] = self.object.webprovisioningplan_set.order_by( context["plans"] = self.object.webprovisioningplan_set.order_by(
"-requested_at", "-pk" "-requested_at", "-pk"
)[:10] )[:10]
if reseller is not None or user.has_perm(VIEW_DATABASES): if tenant or user.has_perm(VIEW_DATABASES):
context["databases"] = self.object.databases.all() context["databases"] = self.object.databases.all()
if reseller is not None or user.has_perm(VIEW_DNS_ZONES): if tenant or user.has_perm(VIEW_DNS_ZONES):
zones = list(self.object.dns_zones.all()) zones = list(self.object.dns_zones.all())
context["dns_zones"] = zones context["dns_zones"] = zones
context["has_primary_zone"] = any( context["has_primary_zone"] = any(
zone.domain == self.object.primary_domain for zone in zones zone.domain == self.object.primary_domain for zone in zones
) )
if reseller is not None or user.has_perm(VIEW_MAILBOXES): if tenant or user.has_perm(VIEW_MAILBOXES):
context["mailboxes"] = HostingMailbox.objects.filter( context["mailboxes"] = HostingMailbox.objects.filter(
mail_domain__account=self.object mail_domain__account=self.object
).select_related("mail_domain") ).select_related("mail_domain")
return context return context
class DatabaseCreate(OperatorOnlyMixin, PermissionRequiredMixin, CreateView): class CustomerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
model = HostingDatabase queryset = Customer.objects.select_related("user__hosting_reseller").order_by(
fields = ("suffix",) "user__username"
template_name = "hosting/database_form.html" )
permission_required = (VIEW_ACCOUNTS, VIEW_DATABASES, "hosting.add_hostingdatabase") permission_required = VIEW_CUSTOMERS
template_name = "hosting/customer_list.html"
context_object_name = "customers"
paginate_by = 20
def get_queryset(self):
self.search = self.request.GET.get("q", "").strip()[:150]
queryset = super().get_queryset()
if self.search:
queryset = queryset.filter(user__username__icontains=self.search)
return queryset
def get_context_data(self, **kwargs):
return super().get_context_data(search=self.search, **kwargs)
@method_decorator(sensitive_post_parameters("password1", "password2"), name="dispatch")
class CustomerCreate(OperatorOnlyMixin, PermissionRequiredMixin, FormView):
permission_required = (VIEW_CUSTOMERS, "hosting.add_customer")
form_class = UserCreationForm
template_name = "hosting/customer_form.html"
success_url = reverse_lazy("panel:customers")
def form_valid(self, form):
try:
with transaction.atomic():
Customer.objects.create(user=form.save())
except IntegrityError:
user = form.instance
users = get_user_model().objects
if not users.filter(username__iexact=user.username).exists():
raise
form.add_error(
"username", user.unique_error_message(type(user), ["username"])
)
return self.form_invalid(form)
return super().form_valid(form)
class CustomerAccess(OperatorOnlyMixin, PermissionRequiredMixin, View):
permission_required = (VIEW_CUSTOMERS, "hosting.change_customer")
def post(self, request, pk):
access = request.POST.get("access")
if access not in ("restore", "suspend"):
return HttpResponseBadRequest(
"Choose whether to restore or suspend sign-in."
)
customer = Customer.objects.filter(pk=pk).values("user_id")
resellers = Reseller.objects.values("user_id")
users = (
get_user_model()
.objects.filter(pk__in=customer, is_staff=False, is_superuser=False)
.exclude(pk__in=resellers)
)
if not users.update(is_active=access == "restore"):
raise Http404
return redirect(reverse("panel:customers", query=request.GET))
class ResourceRequestCreate(PermissionRequiredMixin, CreateView):
@cached_property
def customer(self):
return customer_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()
)
@cached_property @cached_property
def account(self): def account(self):
return get_object_or_404(HostingAccount, pk=self.kwargs["pk"]) accounts = HostingAccount.objects.all()
if self.customer is not None:
accounts = accounts.filter(customer=self.customer)
return get_object_or_404(accounts, pk=self.kwargs["pk"])
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
return super().get_context_data(account=self.account, **kwargs) return super().get_context_data(account=self.account, **kwargs)
def form_valid(self, form): def form_valid(self, form):
self.object = form.save(commit=False)
self.object.account = self.account
try: try:
with transaction.atomic(): self.object = self.create_request(
self.object.save() self.account.pk,
except IntegrityError: **form.cleaned_data,
if not self.account.databases.filter(suffix=self.object.suffix).exists(): customer_id=self.customer.pk if self.customer is not None else None,
raise
form.add_error(
"suffix", "This account already has a database with that suffix."
) )
except HostingAccount.DoesNotExist as error:
raise Http404 from error
except ValidationError as error:
form.add_error(None, error)
return self.form_invalid(form) return self.form_invalid(form)
return redirect(self.account) return redirect(self.account)
class DatabaseCreate(ResourceRequestCreate):
model = HostingDatabase
fields = ("suffix",)
template_name = "hosting/database_form.html"
permission_required = (VIEW_ACCOUNTS, VIEW_DATABASES, "hosting.add_hostingdatabase")
create_request = staticmethod(create_database_request)
class DownloadDatabaseManifest(OperatorOnlyMixin, PermissionRequiredMixin, View): class DownloadDatabaseManifest(OperatorOnlyMixin, PermissionRequiredMixin, View):
permission_required = (VIEW_ACCOUNTS, VIEW_DATABASES) permission_required = (VIEW_ACCOUNTS, VIEW_DATABASES)
@@ -339,50 +439,18 @@ class DownloadDnsZoneManifest(OperatorOnlyMixin, PermissionRequiredMixin, View):
) )
class MailboxCreate(OperatorOnlyMixin, PermissionRequiredMixin, CreateView): class MailboxCreate(ResourceRequestCreate):
model = HostingMailbox model = HostingMailbox
fields = ("local_part",) fields = ("local_part",)
template_name = "hosting/mailbox_form.html" template_name = "hosting/mailbox_form.html"
permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES, "hosting.add_hostingmailbox") permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES, "hosting.add_hostingmailbox")
create_request = staticmethod(create_mailbox_request)
@cached_property
def account(self):
return get_object_or_404(HostingAccount, pk=self.kwargs["pk"])
def get_form(self, form_class=None): def get_form(self, form_class=None):
form = super().get_form(form_class) form = super().get_form(form_class)
form.fields["local_part"].help_text = INVALID_LOCAL_PART form.fields["local_part"].help_text = INVALID_LOCAL_PART
return form return form
def get_context_data(self, **kwargs):
return super().get_context_data(account=self.account, **kwargs)
def form_valid(self, form):
try:
spec = MailboxSpec(
self.account.primary_domain, form.cleaned_data["local_part"]
)
except ValueError as error:
form.add_error("local_part", str(error))
return self.form_invalid(form)
with transaction.atomic():
mail_domain, _ = HostingMailDomain.objects.get_or_create(
domain=spec.domain, defaults={"account": self.account}
)
if mail_domain.account_id != self.account.pk:
form.add_error(
None, "This mail domain belongs to another hosting account."
)
return self.form_invalid(form)
self.object, created = HostingMailbox.objects.get_or_create(
mail_domain=mail_domain, local_part=spec.local_part
)
if not created:
form.add_error("local_part", "This mailbox has already been requested.")
return self.form_invalid(form)
return redirect(self.account)
class DownloadMailboxManifest(OperatorOnlyMixin, PermissionRequiredMixin, View): class DownloadMailboxManifest(OperatorOnlyMixin, PermissionRequiredMixin, View):
permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES) permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES)
@@ -410,7 +478,7 @@ class HostingPlanList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
class HostingPlanEditor: class HostingPlanEditor:
model = HostingPlan model = HostingPlan
fields = ("name", "description") fields = ("name", "description", "database_limit", "mailbox_limit")
template_name = "hosting/hosting_plan_form.html" template_name = "hosting/hosting_plan_form.html"
success_url = reverse_lazy("panel:hosting_plans") success_url = reverse_lazy("panel:hosting_plans")
@@ -428,6 +496,11 @@ class HostingPlanEdit(
permission_required = (VIEW_HOSTING_PLANS, "hosting.change_hostingplan") permission_required = (VIEW_HOSTING_PLANS, "hosting.change_hostingplan")
extra_context = {"page_title": "Edit hosting plan", "submit_label": "Save changes"} extra_context = {"page_title": "Edit hosting plan", "submit_label": "Save changes"}
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.save(update_fields=form.changed_data)
return redirect(self.get_success_url())
class RequestWebPlan( class RequestWebPlan(
OperatorOnlyMixin, PermissionRequiredMixin, SingleObjectMixin, View OperatorOnlyMixin, PermissionRequiredMixin, SingleObjectMixin, View
@@ -441,7 +514,7 @@ class RequestWebPlan(
return redirect("panel:plan", pk=plan.pk) return redirect("panel:plan", pk=plan.pk)
class PlanList(ResellerScopeMixin, PermissionRequiredMixin, ListView): class PlanList(TenantScopeMixin, PermissionRequiredMixin, ListView):
queryset = WebProvisioningPlan.objects.select_related("account").order_by( queryset = WebProvisioningPlan.objects.select_related("account").order_by(
"-requested_at", "-pk" "-requested_at", "-pk"
) )
@@ -452,7 +525,7 @@ class PlanList(ResellerScopeMixin, PermissionRequiredMixin, ListView):
paginate_by = 20 paginate_by = 20
class PlanDetail(ResellerScopeMixin, PermissionRequiredMixin, DetailView): class PlanDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
queryset = WebProvisioningPlan.objects.select_related("account") queryset = WebProvisioningPlan.objects.select_related("account")
permission_required = VIEW_PLANS permission_required = VIEW_PLANS
reseller_relation = "account__reseller" reseller_relation = "account__reseller"