diff --git a/README.md b/README.md index 835a4a8..9ef27ed 100644 --- a/README.md +++ b/README.md @@ -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. - 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. - Mail and DNS on the hosting server or on separate servers. - Account backups, restore, and migration from DirectAdmin. diff --git a/docs/development.md b/docs/development.md index 1da7d02..5cbddee 100644 --- a/docs/development.md +++ b/docs/development.md @@ -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. 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 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 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 Open a hosting account and select **Request database**. Choose a short suffix diff --git a/src/coulobre/admin.py b/src/coulobre/admin.py index 59e9741..3f2679b 100644 --- a/src/coulobre/admin.py +++ b/src/coulobre/admin.py @@ -1,14 +1,12 @@ from django.contrib.admin import AdminSite from django.contrib.admin.apps import AdminConfig -from .hosting.access import reseller_for_user +from .hosting.access import is_tenant class CoulobreAdminSite(AdminSite): def has_permission(self, request): - return ( - super().has_permission(request) and reseller_for_user(request.user) is None - ) + return super().has_permission(request) and not is_tenant(request.user) class CoulobreAdminConfig(AdminConfig): diff --git a/src/coulobre/hosting/access.py b/src/coulobre/hosting/access.py index 05b7d51..3145f11 100644 --- a/src/coulobre/hosting/access.py +++ b/src/coulobre/hosting/access.py @@ -1,30 +1,59 @@ -def reseller_for_user(user): +def customer_for_user(user): if not user.is_authenticated or user.is_superuser: 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) +def is_tenant(user): + return customer_for_user(user) is not None or reseller_for_user(user) is not None + + 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: 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 super().dispatch(request, *args, **kwargs) -class ResellerScopeMixin: +class TenantScopeMixin: reseller_relation = "reseller" + customer_relation = None def has_permission(self): + if customer_for_user(self.request.user) is not None: + return self.customer_relation is not None return ( reseller_for_user(self.request.user) is not None or super().has_permission() ) def get_queryset(self): 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) if reseller is not None: return queryset.filter(**{f"{self.reseller_relation}_id": reseller.pk}) diff --git a/src/coulobre/hosting/admin.py b/src/coulobre/hosting/admin.py index 43439ae..e85e797 100644 --- a/src/coulobre/hosting/admin.py +++ b/src/coulobre/hosting/admin.py @@ -1,7 +1,7 @@ from django.contrib import admin 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) @@ -17,6 +17,8 @@ class HostingAccountAdmin(admin.ModelAdmin): excluded.append("hosting_plan") if not request.user.has_perm("hosting.view_reseller"): excluded.append("reseller") + if not request.user.has_perm("hosting.view_customer"): + excluded.append("customer") return excluded def save_model(self, request, obj, form, change): @@ -36,9 +38,15 @@ class HostingAccountAdmin(admin.ModelAdmin): @admin.register(HostingPlan) class HostingPlanAdmin(admin.ModelAdmin): - list_display = ("name", "description") + list_display = ("name", "description", "database_limit", "mailbox_limit") 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) class ResellerAdmin(admin.ModelAdmin): @@ -54,6 +62,13 @@ class ResellerAdmin(admin.ModelAdmin): return excluded +@admin.register(Customer) +class CustomerAdmin(admin.ModelAdmin): + list_display = ("user",) + list_select_related = ("user",) + search_fields = ("user__username",) + + @admin.register(WebProvisioningPlan) class WebProvisioningPlanAdmin(admin.ModelAdmin): list_display = ("primary_domain", "account", "requested_at", "completed_at") diff --git a/src/coulobre/hosting/migrations/0011_customer_access.py b/src/coulobre/hosting/migrations/0011_customer_access.py new file mode 100644 index 0000000..fd52772 --- /dev/null +++ b/src/coulobre/hosting/migrations/0011_customer_access.py @@ -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", + ), + ), + ] diff --git a/src/coulobre/hosting/migrations/0012_hosting_plan_quotas.py b/src/coulobre/hosting/migrations/0012_hosting_plan_quotas.py new file mode 100644 index 0000000..f23b1c7 --- /dev/null +++ b/src/coulobre/hosting/migrations/0012_hosting_plan_quotas.py @@ -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, + ), + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 75add91..cd8270c 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -21,7 +21,7 @@ class Reseller(models.Model): settings.AUTH_USER_MODEL, on_delete=models.PROTECT, 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) hosting_plans = models.ManyToManyField("HostingPlan", blank=True) @@ -33,9 +33,35 @@ class Reseller(models.Model): 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): name = models.CharField(max_length=120, unique=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: ordering = ("name", "pk") @@ -53,6 +79,9 @@ class HostingAccount(models.Model): reseller = models.ForeignKey( 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) def get_absolute_url(self): diff --git a/src/coulobre/hosting/resource_requests.py b/src/coulobre/hosting/resource_requests.py new file mode 100644 index 0000000..b29f83e --- /dev/null +++ b/src/coulobre/hosting/resource_requests.py @@ -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) diff --git a/src/coulobre/hosting/static/hosting/panel.css b/src/coulobre/hosting/static/hosting/panel.css index 3328f18..bcc92ed 100644 --- a/src/coulobre/hosting/static/hosting/panel.css +++ b/src/coulobre/hosting/static/hosting/panel.css @@ -159,6 +159,25 @@ button, input, select, textarea { 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 { display: grid; gap: 0.3rem; @@ -439,12 +458,12 @@ dd { font-weight: 680; } -.status.ready { +.status.ready, .status.active { background: #dcebdc; color: #205038; } -.status.pending { +.status.pending, .status.suspended { background: #f5ead6; color: #6b431b; } diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index 3ee9cf2..d858710 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -7,25 +7,28 @@

{{ account.name }}

{{ account.primary_domain }}

- {% if not is_reseller and perms.hosting.change_hostingaccount %} + {% if is_operator and perms.hosting.change_hostingaccount %} Edit account {% endif %}
Primary domain
{{ account.primary_domain }}
- {% if is_reseller or perms.hosting.view_hostingplan %} + {% if is_tenant or perms.hosting.view_hostingplan %}
Hosting plan
{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}Unassigned{% endif %}
{% endif %} - {% if not is_reseller and perms.hosting.view_reseller %} + {% if is_operator and perms.hosting.view_reseller %}
Reseller
{{ account.reseller|default_if_none:"Unassigned" }}
{% endif %} + {% if is_operator and perms.hosting.view_customer %} +
Customer
{{ account.customer|default_if_none:"Unassigned" }}
+ {% endif %}
Added
{{ account.created_at|date:"j M Y, H:i" }} UTC
- {% if is_reseller or perms.hosting.view_webprovisioningplan %} + {% if is_reseller or is_operator and perms.hosting.view_webprovisioningplan %}

Recent Apache previews

- {% if not is_reseller and perms.hosting.change_hostingaccount %} + {% if is_operator and perms.hosting.change_hostingaccount %}
{% csrf_token %} @@ -35,23 +38,30 @@ {% include "hosting/plan_table.html" %}
{% endif %} - {% if is_reseller or perms.hosting.view_hostingdatabase %} + {% if is_tenant or perms.hosting.view_hostingdatabase %}
-

MariaDB database requests

- {% if not is_reseller and perms.hosting.add_hostingdatabase %} +
+

MariaDB database requests

+ {% if is_tenant or perms.hosting.view_hostingplan %} + {% if account.hosting_plan and account.hosting_plan.database_limit is not None %} +

{{ databases|length }} of {{ account.hosting_plan.database_limit }} databases requested

+ {% endif %} + {% endif %} +
+ {% if is_customer or is_operator and perms.hosting.add_hostingdatabase %} Request database {% endif %}
{% if databases %}
- {% if not is_reseller %}{% endif %} + {% if is_operator %}{% endif %} {% for database in databases %} - {% if not is_reseller %} + {% if is_operator %} {% endif %} @@ -64,11 +74,11 @@ {% endif %} {% endif %} - {% if is_reseller or perms.hosting.view_hostingdnszone %} + {% if is_tenant or perms.hosting.view_hostingdnszone %}

DNS zones

- {% 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 %} Add DNS zone {% endif %}
@@ -79,21 +89,21 @@
- {% if not is_reseller %}{% endif %} + {% if is_operator %}{% endif %} {% for zone in dns_zones %} - {% if not is_reseller %} + {% if is_operator %} {% endif %} @@ -106,11 +116,18 @@ {% endif %} {% endif %} - {% if is_reseller or perms.hosting.view_hostingmailbox %} + {% if is_tenant or perms.hosting.view_hostingmailbox %}
-

Mailbox requests

- {% if not is_reseller and perms.hosting.add_hostingmailbox %} +
+

Mailbox requests

+ {% if is_tenant or perms.hosting.view_hostingplan %} + {% if account.hosting_plan and account.hosting_plan.mailbox_limit is not None %} +

{{ mailboxes|length }} of {{ account.hosting_plan.mailbox_limit }} mailboxes requested

+ {% endif %} + {% endif %} +
+ {% if is_customer or is_operator and perms.hosting.add_hostingmailbox %} Request mailbox {% endif %}
@@ -120,14 +137,14 @@
- {% if not is_reseller %}{% endif %} + {% if is_operator %}{% endif %} {% for mailbox in mailboxes %} - {% if not is_reseller %} + {% if is_operator %} {% endif %} diff --git a/src/coulobre/hosting/templates/hosting/account_list.html b/src/coulobre/hosting/templates/hosting/account_list.html index ba3a507..669bcc0 100644 --- a/src/coulobre/hosting/templates/hosting/account_list.html +++ b/src/coulobre/hosting/templates/hosting/account_list.html @@ -7,7 +7,7 @@

{{ paginator.count }} account{{ paginator.count|pluralize }}{% if search %} matching your search{% endif %}

{% if account_allowance %}

{{ account_allowance.used }} of {{ account_allowance.limit }} accounts allocated

{% endif %} - {% 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 %} Add hosting account {% endif %} @@ -25,7 +25,7 @@ - {% if is_reseller or perms.hosting.view_hostingplan %}{% endif %} + {% if is_tenant or perms.hosting.view_hostingplan %}{% endif %} @@ -34,7 +34,7 @@ - {% if is_reseller or perms.hosting.view_hostingplan %} + {% if is_tenant or perms.hosting.view_hostingplan %} {% endif %} diff --git a/src/coulobre/hosting/templates/hosting/base.html b/src/coulobre/hosting/templates/hosting/base.html index efde25d..42569d3 100644 --- a/src/coulobre/hosting/templates/hosting/base.html +++ b/src/coulobre/hosting/templates/hosting/base.html @@ -17,19 +17,25 @@
DatabaseDeployment
DatabaseDeployment
{{ database }}Download manifest
Domain SOA serialDeploymentDeployment
- {% if not is_reseller and perms.hosting.change_hostingdnszone %} + {% if is_operator and perms.hosting.change_hostingdnszone %} {{ zone.domain }} {% else %} {{ zone.domain }} {% endif %} {{ zone.serial }}Download manifest
Email addressDeploymentDeployment
{{ mailbox }}Download manifest
Account Primary domainHosting planHosting planAdded
{{ account.name }} {{ account.primary_domain }}{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}Unassigned{% endif %}{{ account.created_at|date:"j M Y" }}
+ + + + + {% if perms.hosting.change_customer %}{% endif %} + + + + {% for customer in customers %} + + + + {% if perms.hosting.change_customer %} + + {% endif %} + + {% endfor %} + +
UsernameSign-in statusActions
{{ customer }} + {% if customer.user.is_active %}Active + {% else %}Suspended{% endif %} + + {% if not customer.user.is_staff and not customer.user.is_superuser and not customer.user.hosting_reseller %} +
+ {% csrf_token %} + {% if customer.user.is_active %} + + {% else %} + + {% endif %} +
+ {% endif %} +
+
+ {% elif search %} +

No customers match this search.

+ {% else %} +

No customers yet.

+ {% endif %} + {% include "hosting/pagination.html" %} +
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/hosting_plan_list.html b/src/coulobre/hosting/templates/hosting/hosting_plan_list.html index da1a082..9bf7016 100644 --- a/src/coulobre/hosting/templates/hosting/hosting_plan_list.html +++ b/src/coulobre/hosting/templates/hosting/hosting_plan_list.html @@ -11,7 +11,14 @@ {% if hosting_plans %}
- + + + + + + + + {% for hosting_plan in hosting_plans %} @@ -23,6 +30,8 @@ {% endif %} + + {% endfor %} diff --git a/src/coulobre/hosting/test_customers.py b/src/coulobre/hosting/test_customers.py new file mode 100644 index 0000000..7ff9e96 --- /dev/null +++ b/src/coulobre/hosting/test_customers.py @@ -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) diff --git a/src/coulobre/hosting/test_databases.py b/src/coulobre/hosting/test_databases.py index 011c7fe..07b9b11 100644 --- a/src/coulobre/hosting/test_databases.py +++ b/src/coulobre/hosting/test_databases.py @@ -5,7 +5,7 @@ from django.urls import reverse from coulobre.database_node import DatabaseSpec -from .models import HostingAccount, HostingDatabase, Reseller +from .models import HostingAccount, HostingDatabase, HostingPlan, Reseller class DatabaseRequestTests(TestCase): @@ -74,6 +74,37 @@ class DatabaseRequestTests(TestCase): self.assertIn("suffix", response.context["form"].errors) 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): owned = HostingDatabase.objects.create(account=self.account, suffix="wordpress") HostingDatabase.objects.create(account=self.other_account, suffix="othersite") diff --git a/src/coulobre/hosting/test_hosting_plans.py b/src/coulobre/hosting/test_hosting_plans.py index 7a3e745..80ea446 100644 --- a/src/coulobre/hosting/test_hosting_plans.py +++ b/src/coulobre/hosting/test_hosting_plans.py @@ -30,10 +30,17 @@ class HostingPlanTests(TestCase): list_url = reverse("panel:hosting_plans") response = self.client.post( 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) plan = HostingPlan.objects.get() + self.assertEqual(plan.database_limit, 0) + self.assertEqual(plan.mailbox_limit, 5) self.assertContains( self.client.get(self.account.get_absolute_url()), "Unassigned" @@ -52,9 +59,18 @@ class HostingPlanTests(TestCase): response = self.client.post( 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) + 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") response = self.client.post( @@ -69,6 +85,16 @@ class HostingPlanTests(TestCase): self.assertRedirects(response, new_account.get_absolute_url()) 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): current = HostingPlan.objects.create(name="Private plan") other = HostingPlan.objects.create(name="Other plan") diff --git a/src/coulobre/hosting/test_mailboxes.py b/src/coulobre/hosting/test_mailboxes.py index 7ac8fa1..2dd2915 100644 --- a/src/coulobre/hosting/test_mailboxes.py +++ b/src/coulobre/hosting/test_mailboxes.py @@ -10,7 +10,13 @@ from django.urls import reverse 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): @@ -79,6 +85,41 @@ class MailboxRequestTests(TestCase): self.assertIn("local_part", response.context["form"].errors) 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): original = self.request_mailbox("support") mail_domain = original.mail_domain.domain diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 0a39867..d4b6bc8 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -19,6 +19,13 @@ urlpatterns = [ path("accounts/new/", views.AccountCreate.as_view(), name="account_create"), path("accounts//", views.AccountDetail.as_view(), name="account"), path("accounts//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//access/", + views.CustomerAccess.as_view(), + name="customer_access", + ), path( "accounts//databases/new/", views.DatabaseCreate.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index d0a81e5..260d8ac 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -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.core.exceptions import ValidationError from django.db import IntegrityError, transaction 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.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.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.detail import SingleObjectMixin 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 .models import ( + Customer, HostingAccount, HostingDatabase, HostingDnsZone, HostingMailbox, - HostingMailDomain, HostingPlan, + Reseller, WebProvisioningPlan, ) 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 VIEW_ACCOUNTS = "hosting.view_hostingaccount" @@ -32,12 +43,13 @@ CHANGE_ACCOUNTS = "hosting.change_hostingaccount" VIEW_PLANS = "hosting.view_webprovisioningplan" VIEW_HOSTING_PLANS = "hosting.view_hostingplan" VIEW_RESELLERS = "hosting.view_reseller" +VIEW_CUSTOMERS = "hosting.view_customer" VIEW_DATABASES = "hosting.view_hostingdatabase" VIEW_DNS_ZONES = "hosting.view_hostingdnszone" VIEW_MAILBOXES = "hosting.view_hostingmailbox" -class AccountList(ResellerScopeMixin, PermissionRequiredMixin, ListView): +class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView): queryset = HostingAccount.objects.select_related("hosting_plan").order_by( "primary_domain" ) @@ -45,6 +57,7 @@ class AccountList(ResellerScopeMixin, PermissionRequiredMixin, ListView): template_name = "hosting/account_list.html" context_object_name = "accounts" paginate_by = 20 + customer_relation = "customer" def get_queryset(self): self.search = self.request.GET.get("q", "").strip()[:253] @@ -78,6 +91,8 @@ class AccountEditor: self.fields += ("hosting_plan",) if reseller is None and self.request.user.has_perm(VIEW_RESELLERS): self.fields += ("reseller",) + if reseller is None and self.request.user.has_perm(VIEW_CUSTOMERS): + self.fields += ("customer",) return super().get_form_class() def get_form(self, form_class=None): @@ -91,13 +106,13 @@ class AccountEditor: field.queryset = reseller.hosting_plans.all() field.required = True field.empty_label = "Select a hosting plan" - if "reseller" in form.fields: - form.fields["reseller"].empty_label = "Unassigned" - form.fields["reseller"].queryset = ( - form.fields["reseller"] - .queryset.select_related("user") - .order_by("user__username") - ) + for name in ("reseller", "customer"): + if name in form.fields: + field = form.fields[name] + field.empty_label = "Unassigned" + field.queryset = field.queryset.select_related("user").order_by( + "user__username" + ) return form @@ -106,6 +121,8 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView): extra_context = {"page_title": "Add hosting account", "submit_label": "Add account"} def has_permission(self): + if customer_for_user(self.request.user) is not None: + return False reseller = reseller_for_user(self.request.user) if reseller is not None: return reseller.may_create_accounts() @@ -148,64 +165,147 @@ class AccountEdit( return redirect(self.object) -class AccountDetail(ResellerScopeMixin, PermissionRequiredMixin, DetailView): - queryset = HostingAccount.objects.select_related("hosting_plan", "reseller__user") +class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): + queryset = HostingAccount.objects.select_related( + "hosting_plan", "reseller__user", "customer__user" + ) permission_required = VIEW_ACCOUNTS template_name = "hosting/account_detail.html" context_object_name = "account" + customer_relation = "customer" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = self.request.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( "-requested_at", "-pk" )[: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() - 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()) context["dns_zones"] = zones context["has_primary_zone"] = any( 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( mail_domain__account=self.object ).select_related("mail_domain") return context -class DatabaseCreate(OperatorOnlyMixin, PermissionRequiredMixin, CreateView): - model = HostingDatabase - fields = ("suffix",) - template_name = "hosting/database_form.html" - permission_required = (VIEW_ACCOUNTS, VIEW_DATABASES, "hosting.add_hostingdatabase") +class CustomerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView): + queryset = Customer.objects.select_related("user__hosting_reseller").order_by( + "user__username" + ) + 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 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): return super().get_context_data(account=self.account, **kwargs) def form_valid(self, form): - self.object = form.save(commit=False) - self.object.account = self.account try: - with transaction.atomic(): - self.object.save() - except IntegrityError: - if not self.account.databases.filter(suffix=self.object.suffix).exists(): - raise - form.add_error( - "suffix", "This account already has a database with that suffix." + self.object = self.create_request( + self.account.pk, + **form.cleaned_data, + customer_id=self.customer.pk if self.customer is not None else None, ) + except HostingAccount.DoesNotExist as error: + raise Http404 from error + except ValidationError as error: + form.add_error(None, error) return self.form_invalid(form) return redirect(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): 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 fields = ("local_part",) template_name = "hosting/mailbox_form.html" permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES, "hosting.add_hostingmailbox") - - @cached_property - def account(self): - return get_object_or_404(HostingAccount, pk=self.kwargs["pk"]) + create_request = staticmethod(create_mailbox_request) def get_form(self, form_class=None): form = super().get_form(form_class) form.fields["local_part"].help_text = INVALID_LOCAL_PART 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): permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES) @@ -410,7 +478,7 @@ class HostingPlanList(OperatorOnlyMixin, PermissionRequiredMixin, ListView): class HostingPlanEditor: model = HostingPlan - fields = ("name", "description") + fields = ("name", "description", "database_limit", "mailbox_limit") template_name = "hosting/hosting_plan_form.html" success_url = reverse_lazy("panel:hosting_plans") @@ -428,6 +496,11 @@ class HostingPlanEdit( permission_required = (VIEW_HOSTING_PLANS, "hosting.change_hostingplan") 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( OperatorOnlyMixin, PermissionRequiredMixin, SingleObjectMixin, View @@ -441,7 +514,7 @@ class RequestWebPlan( 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( "-requested_at", "-pk" ) @@ -452,7 +525,7 @@ class PlanList(ResellerScopeMixin, PermissionRequiredMixin, ListView): paginate_by = 20 -class PlanDetail(ResellerScopeMixin, PermissionRequiredMixin, DetailView): +class PlanDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): queryset = WebProvisioningPlan.objects.select_related("account") permission_required = VIEW_PLANS reseller_relation = "account__reseller"
PlanDescription
PlanDescriptionDatabase limitMailbox limit
{{ hosting_plan.description|default:"—" }}{{ hosting_plan.database_limit|default_if_none:"Unlimited" }}{{ hosting_plan.mailbox_limit|default_if_none:"Unlimited" }}