From fd2bdb8a185807d7f58d020b11fb07fddb4ad67e Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Mon, 23 Nov 2026 22:09:27 +0100 Subject: [PATCH] Establish role workspaces and customer onboarding --- docs/deployment.md | 12 +- docs/security.md | 2 +- src/coulobre/hosting/access.py | 59 ++- .../hosting/account_administration.py | 353 ++++++++++++++++++ src/coulobre/hosting/account_backups.py | 6 +- src/coulobre/hosting/customer_backup_views.py | 67 ++++ src/coulobre/hosting/installation_views.py | 17 +- src/coulobre/hosting/invitations.py | 8 +- .../migrations/0060_welcome_message.py | 17 + src/coulobre/hosting/models.py | 2 + src/coulobre/hosting/panel_roles.py | 21 +- src/coulobre/hosting/reseller_views.py | 6 +- src/coulobre/hosting/static/hosting/panel.css | 26 ++ .../templates/hosting/account_detail.html | 2 +- .../templates/hosting/account_retirement.html | 2 +- .../hosting/templates/hosting/all_users.html | 22 ++ .../hosting/templates/hosting/base.html | 85 +---- .../templates/hosting/customer_backups.html | 19 + .../templates/hosting/installation.html | 5 +- .../templates/hosting/manager_packages.html | 11 + .../templates/hosting/panel_invitation.txt | 4 +- .../templates/hosting/reseller_detail.html | 4 +- .../templates/hosting/reseller_form.html | 6 +- .../templates/hosting/reseller_list.html | 12 +- .../hosting/reseller_profile_form.html | 2 +- .../hosting/reseller_profile_list.html | 6 +- .../templates/hosting/system_workspace.html | 16 + .../templates/hosting/workspace_form.html | 21 ++ .../hosting/workspace_navigation.html | 8 + src/coulobre/hosting/test_service_health.py | 4 +- src/coulobre/hosting/test_workspaces.py | 122 ++++++ src/coulobre/hosting/urls.py | 33 ++ src/coulobre/hosting/views.py | 2 +- src/coulobre/hosting/workspaces.py | 227 +++++++++++ 34 files changed, 1061 insertions(+), 148 deletions(-) create mode 100644 src/coulobre/hosting/account_administration.py create mode 100644 src/coulobre/hosting/customer_backup_views.py create mode 100644 src/coulobre/hosting/migrations/0060_welcome_message.py create mode 100644 src/coulobre/hosting/templates/hosting/all_users.html create mode 100644 src/coulobre/hosting/templates/hosting/customer_backups.html create mode 100644 src/coulobre/hosting/templates/hosting/manager_packages.html create mode 100644 src/coulobre/hosting/templates/hosting/system_workspace.html create mode 100644 src/coulobre/hosting/templates/hosting/workspace_form.html create mode 100644 src/coulobre/hosting/templates/hosting/workspace_navigation.html create mode 100644 src/coulobre/hosting/test_workspaces.py create mode 100644 src/coulobre/hosting/workspaces.py diff --git a/docs/deployment.md b/docs/deployment.md index a5c7238..4057fa8 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -498,12 +498,12 @@ sudo journalctl -u coulobre-panel -u coulobre-worker -u coulobre-beat ## Manage panel roles -A verified superuser can assign a Customer or Customer manager role to an -active login from **Customers** or **Customer managers**. Choose **Assign +A verified superuser can assign a Customer or Manager role to an +active login from **Customers** or **Managers**. Choose **Assign to existing login** and enter the username. Customer roles use their own -assigned hosting accounts. Customer managers use their own hosting account +assigned hosting accounts. Managers use their own hosting account assignments and hosting plan policy. New manager assignments use the default -customer manager profile when one is configured. +manager profile when one is configured. Logins with multiple roles can choose **Panel role** in the account area. The role applies to the session, including direct page requests and actions. @@ -784,7 +784,7 @@ loaded as long as any existing managed login uses it. Use the in-place procedure above with the v0.10 source release. Keep a copy of the v0.9 release and a matching database and configuration backup for -rollback. The upgrade adds tables for invitations and customer manager +rollback. The upgrade adds tables for invitations and manager profiles, and initializes the new web setup flags without running provisioning for existing accounts. @@ -1273,7 +1273,7 @@ sudo systemctl enable --now coulobre-database-provisioner.service ``` Select **Add database** on a hosting account to queue its provisioning. -Customers can add databases on their own accounts. Customer managers need +Customers can add databases on their own accounts. Managers need permission to manage resources for their assigned accounts. For a pending request, an operator can select **Provision database**. Operators need permission to view hosting accounts and databases and the **Can add database diff --git a/docs/security.md b/docs/security.md index b1ae06d..b159fe0 100644 --- a/docs/security.md +++ b/docs/security.md @@ -18,7 +18,7 @@ after users have a way to update. - Serve the panel over HTTPS. If you use a reverse proxy, restrict the private origin to that proxy and let the managed Apache configuration set the forwarding headers. Keep debug mode off on shared or public hosts. -- Require two-factor authentication for staff and customer managers. Use an +- Require two-factor authentication for staff and managers. Use an authenticator app for administrative accounts and keep recovery codes in a protected location. The **My account** page lets users verify a new email address, replace their authenticator, renew recovery codes, and revoke diff --git a/src/coulobre/hosting/access.py b/src/coulobre/hosting/access.py index 14515f2..0525105 100644 --- a/src/coulobre/hosting/access.py +++ b/src/coulobre/hosting/access.py @@ -7,21 +7,6 @@ class PanelRole(StrEnum): CUSTOMER = "customer" -NAVIGATION_SECTIONS = { - "accounts": "accounts", - "retired-accounts": "accounts", - "databases": "accounts", - "dns-zones": "accounts", - "mailboxes": "accounts", - "mail-domains": "accounts", - "customers": "customers", - "resellers": "resellers", - "hosting-plans": "hosting_plans", - "plans": "plans", - "service-health": "service_health", -} - - def customer_for_user(user): role = getattr(user, "panel_role", None) if role is not None and role != PanelRole.CUSTOMER: @@ -62,33 +47,37 @@ def manages_account(user, account): def panel_access(request): customer = customer_for_user(request.user) is not None reseller = not customer and reseller_for_user(request.user) is not None - match = request.resolver_match - section = None - if match is not None and match.namespace == "panel": - section = NAVIGATION_SECTIONS.get( - match.route.split("/", 1)[0], match.url_name - ) + from .workspaces import CUSTOMER_ACCOUNT, groups_for, workspace_accounts + operator = request.user.is_authenticated and not (customer or reseller) - grouped = reseller or ( - operator - and sum( - request.user.has_perm(f"hosting.view_{resource}") - for resource in ( - "hostingaccount", - "customer", - "reseller", - "hostingplan", - ) - ) - > 1 + groups = groups_for(request, customer=customer, manager=reseller) + current = next( + ( + label + for label, links in groups + if any(url == request.path for url, _ in links) + ), + "", ) + selected = request.session.get(CUSTOMER_ACCOUNT) + available = [] + if customer and not getattr(request, "impersonation", None): + available = list( + workspace_accounts(request.user) + .only("id", "primary_domain") + .order_by("primary_domain") + ) + if available and selected not in {account.pk for account in available}: + selected = available[0].pk return { "is_customer": customer, "is_reseller": reseller, "is_tenant": customer or reseller, "is_operator": operator, - "group_customer_navigation": grouped, - "panel_section": section, + "navigation_groups": groups, + "open_workspace_group": current, + "workspace_accounts": available if len(available) > 1 else [], + "workspace_selected": selected, } diff --git a/src/coulobre/hosting/account_administration.py b/src/coulobre/hosting/account_administration.py new file mode 100644 index 0000000..91be61c --- /dev/null +++ b/src/coulobre/hosting/account_administration.py @@ -0,0 +1,353 @@ +from django import forms +from django.contrib import messages +from django.contrib.admin.models import ADDITION, LogEntry +from django.contrib.auth import get_user_model, password_validation +from django.contrib.auth.forms import UserCreationForm +from django.contrib.auth.mixins import ( + PermissionRequiredMixin, + UserPassesTestMixin, +) +from django.core.exceptions import ValidationError +from django.db import IntegrityError, transaction +from django.db.models import Count, Q +from django.shortcuts import redirect +from django.urls import reverse_lazy +from django.views.generic import FormView, ListView + +from coulobre.domain_names import canonical_domain + +from .access import OperatorOnlyMixin, reseller_for_user +from .account_setup import setup_new_account +from .dns_defaults import zone_defaults +from .installation_features import ( + default_dns_zones_allowed, + panel_feature_allowed, +) +from .invitations import InviteLoginForm, queue_invitation +from .models import Customer, HostingAccount, HostingPlan, Reseller +from .reseller_accounts import ( + create_reseller_account, + lock_resellers, + save_operator_account, +) +from .resource_requests import lock_hosting_account, require_open_account + + +class ManagerOnboardingForm(InviteLoginForm): + primary_domain = HostingAccount._meta.get_field( + "primary_domain" + ).formfield(required=True) + plan = forms.ModelChoiceField( + queryset=HostingPlan.objects.none(), label="Hosting plan" + ) + manage_dns = forms.BooleanField( + required=False, label="Manage DNS in Coulobre" + ) + manage_mail = forms.BooleanField( + required=False, label="Manage email in Coulobre" + ) + send_invitation = forms.BooleanField( + required=False, initial=True, label="Send a welcome email" + ) + welcome_message = forms.CharField( + required=False, + max_length=2000, + widget=forms.Textarea(attrs={"rows": 3}), + label="Message to include in the welcome email", + ) + initial_password = forms.CharField( + required=False, + strip=False, + max_length=256, + widget=forms.PasswordInput, + label="Initial password", + help_text="Leave blank to use a password setup link.", + ) + + def __init__(self, *args, manager, defaults, **kwargs): + super().__init__(*args, **kwargs) + self.fields["plan"].queryset = manager.hosting_plans.order_by("name") + self.fields["manage_dns"].disabled = not default_dns_zones_allowed( + defaults + ) + self.fields["manage_mail"].disabled = not panel_feature_allowed( + "LOCAL_MAILBOX_PROVISIONING" + ) + + def clean_primary_domain(self): + try: + domain = canonical_domain(self.cleaned_data["primary_domain"]) + except ValueError as error: + raise ValidationError(str(error)) from error + if HostingAccount.objects.filter(primary_domain=domain).exists(): + raise ValidationError( + "This domain already belongs to a hosting account." + ) + return domain + + def clean(self): + cleaned = super().clean() + password = cleaned.get("initial_password") + if password: + if cleaned.get("send_invitation"): + self.add_error( + "initial_password", + "The welcome email uses a password setup link. Leave " + "this field blank to send it.", + ) + try: + password_validation.validate_password(password, self.instance) + except ValidationError as error: + self.add_error("initial_password", error) + return cleaned + + +class ManagerOnboardingView(UserPassesTestMixin, FormView): + form_class = ManagerOnboardingForm + template_name = "hosting/workspace_form.html" + extra_context = { + "title": "Add a new user", + "submit_label": "Create customer and hosting account", + "invitation_preview": True, + } + + def test_func(self): + self.manager = reseller_for_user(self.request.user) + return self.manager is not None + + def get_form_kwargs(self): + return super().get_form_kwargs() | { + "manager": self.manager, + "defaults": zone_defaults(), + } + + def form_valid(self, form): + data = form.cleaned_data + try: + with transaction.atomic(): + user = form.save(commit=False) + if data["initial_password"]: + user.set_password(data["initial_password"]) + user.save() + customer = Customer.objects.create( + user=user, reseller=self.manager + ) + account = HostingAccount( + name=user.get_username(), + primary_domain=data["primary_domain"], + customer=customer, + hosting_plan=data["plan"], + ) + create_reseller_account(self.manager, account) + defaults = zone_defaults() + setup_new_account( + account, + { + "setup_website": panel_feature_allowed( + "LOCAL_WEB_ACTIVATION" + ), + "setup_dns": data["manage_dns"], + "setup_email": data["manage_mail"], + "setup_www": defaults.include_www, + "setup_wildcard": defaults.include_wildcard, + }, + ) + if data["send_invitation"]: + queue_invitation( + user, welcome_message=data["welcome_message"] + ) + except ValidationError as error: + form.add_error(None, ValidationError(error.messages)) + return self.form_invalid(form) + except IntegrityError: + if not ( + HostingAccount.objects.filter( + primary_domain=data["primary_domain"] + ).exists() + or get_user_model() + .objects.filter(username__iexact=data["username"]) + .exists() + ): + raise + form.add_error(None, "The username or domain is already in use.") + return self.form_invalid(form) + messages.success( + self.request, "The customer and hosting account were created." + ) + return redirect(account) + + +class ManagerPackagesView(UserPassesTestMixin, ListView): + template_name = "hosting/manager_packages.html" + context_object_name = "plans" + + def test_func(self): + self.manager = reseller_for_user(self.request.user) + return self.manager is not None + + def get_queryset(self): + return self.manager.hosting_plans.order_by("name") + + +class AllUsersView(OperatorOnlyMixin, PermissionRequiredMixin, ListView): + permission_required = "hosting.view_customer" + template_name = "hosting/all_users.html" + context_object_name = "logins" + paginate_by = 40 + + def get_queryset(self): + profiles = [Q(hosting_customer__isnull=False)] + if self.request.user.has_perm("hosting.view_reseller"): + profiles.append( + Q(hosting_reseller__isnull=False, is_superuser=False) + ) + if self.request.user.is_superuser: + profiles.append(Q(is_superuser=True)) + scope = Q() + for profile in profiles: + scope |= profile + return ( + get_user_model() + .objects.filter(scope) + .filter(username__icontains=self.request.GET.get("q", "")[:150]) + .select_related( + "hosting_customer__reseller__user", "hosting_reseller" + ) + .annotate( + account_count=Count( + "hosting_customer__hostingaccount", + filter=Q( + hosting_customer__hostingaccount__retired_at__isnull=True + ), + distinct=True, + ) + ) + .order_by("username") + ) + + +class OperatorAuthorization(UserPassesTestMixin): + def test_func(self): + user = self.request.user + return user.is_superuser and user.is_verified() + + +class OperatorLoginForm(UserCreationForm): + email = forms.EmailField() + + class Meta(UserCreationForm.Meta): + fields = ("username", "email") + + +class OperatorCreateView(OperatorAuthorization, FormView): + form_class = OperatorLoginForm + template_name = "hosting/workspace_form.html" + success_url = reverse_lazy("panel:all_users") + extra_context = { + "title": "Add an operator", + "submit_label": "Create operator", + } + + @transaction.atomic + def form_valid(self, form): + user = form.save(commit=False) + user.is_staff = user.is_superuser = True + user.save() + from .panel_roles import ensure_operator_manager + + ensure_operator_manager(user) + LogEntry.objects.log_actions( + self.request.user.pk, [user], ADDITION, "Created panel operator." + ) + return super().form_valid(form) + + +class MoveHostingForm(forms.Form): + account = forms.ModelChoiceField( + queryset=HostingAccount.objects.filter( + retired_at__isnull=True + ).select_related("reseller__user") + ) + manager = forms.ModelChoiceField( + queryset=Reseller.objects.filter(user__is_active=True).select_related( + "user" + ) + ) + confirm = forms.BooleanField( + label="I reviewed the destination and its hosting plan policy" + ) + + +class MoveHostingView(OperatorAuthorization, FormView): + form_class = MoveHostingForm + template_name = "hosting/workspace_form.html" + extra_context = { + "title": "Move hosting to another manager", + "submit_label": "Move hosting account", + } + + def form_valid(self, form): + chosen = form.cleaned_data["manager"] + try: + with transaction.atomic(): + account = lock_hosting_account( + form.cleaned_data["account"].pk, customer_id=None + ) + require_open_account(account) + if account.reseller_id == chosen.pk: + raise ValidationError("Choose a different manager.") + managers = lock_resellers( + Reseller.objects.filter( + pk__in=[chosen.pk, account.reseller_id] + ) + ).select_related("user") + destination = next( + ( + manager + for manager in managers + if manager.pk == chosen.pk + ), + None, + ) + if destination is None or not destination.user.is_active: + raise ValidationError( + "The destination is no longer available." + ) + if ( + destination.hostingaccount_set.filter( + retired_at__isnull=True + ).count() + >= destination.account_limit + or not destination.hosting_plans.filter( + pk=account.hosting_plan_id + ).exists() + ): + raise ValidationError( + "The destination must have room and allow this plan." + ) + customer_id = account.customer_id + if customer_id is not None: + customer = Customer.objects.select_for_update().get( + pk=customer_id + ) + if ( + customer.hostingaccount_set.exclude(pk=account.pk) + .filter(retired_at__isnull=True) + .exists() + ): + raise ValidationError( + "This customer has other active hosting accounts. " + "Move them together when changing their manager." + ) + customer.reseller = destination + customer.save(update_fields=["reseller"]) + account.reseller = destination + save_operator_account( + account, + self.request.user.get_username(), + changed_fields=["reseller"], + ) + except ValidationError as error: + form.add_error(None, ValidationError(error.messages)) + return self.form_invalid(form) + return redirect(account) diff --git a/src/coulobre/hosting/account_backups.py b/src/coulobre/hosting/account_backups.py index c66e447..d6c4c70 100644 --- a/src/coulobre/hosting/account_backups.py +++ b/src/coulobre/hosting/account_backups.py @@ -41,8 +41,10 @@ def account_backup_manifest(account, *, include_mailboxes=False): @transaction.atomic -def queue_account_backup(account_id, *, include_mailboxes=False): - account = lock_hosting_account(account_id, customer_id=None) +def queue_account_backup( + account_id, *, include_mailboxes=False, customer_id=None +): + account = lock_hosting_account(account_id, customer_id=customer_id) require_open_account(account) _enqueue_backup(account, include_mailboxes=include_mailboxes) diff --git a/src/coulobre/hosting/customer_backup_views.py b/src/coulobre/hosting/customer_backup_views.py new file mode 100644 index 0000000..239717d --- /dev/null +++ b/src/coulobre/hosting/customer_backup_views.py @@ -0,0 +1,67 @@ +from django import forms +from django.contrib import messages +from django.contrib.auth.mixins import UserPassesTestMixin +from django.core.exceptions import ValidationError +from django.http import Http404 +from django.shortcuts import get_object_or_404, redirect +from django.utils.functional import cached_property +from django.views.generic import FormView + +from .access import customer_for_user +from .account_backups import mail_backups_enabled, queue_account_backup +from .installation_features import panel_feature_allowed +from .models import HostingAccount + + +class CustomerBackupForm(forms.Form): + include_mailboxes = forms.BooleanField( + required=False, label="Include mailboxes" + ) + + +class CustomerBackupView(UserPassesTestMixin, FormView): + template_name = "hosting/customer_backups.html" + form_class = CustomerBackupForm + + def test_func(self): + return customer_for_user(self.request.user) is not None + + @cached_property + def account(self): + return get_object_or_404( + HostingAccount, + pk=self.kwargs["pk"], + retired_at__isnull=True, + customer=customer_for_user(self.request.user), + ) + + def get_form(self, form_class=None): + form = super().get_form(form_class) + form.fields["include_mailboxes"].disabled = not mail_backups_enabled() + return form + + def get_context_data(self, **kwargs): + return super().get_context_data( + account=self.account, + backups=self.account.backup_jobs.order_by("-requested_at")[:30], + may_create=panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"), + **kwargs, + ) + + def form_valid(self, form): + if not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"): + raise Http404 + customer = customer_for_user(self.request.user) + try: + queue_account_backup( + self.account.pk, + include_mailboxes=form.cleaned_data["include_mailboxes"], + customer_id=customer.pk, + ) + except HostingAccount.DoesNotExist as error: + raise Http404 from error + except ValidationError as error: + form.add_error(None, error) + return self.form_invalid(form) + messages.success(self.request, "Backup requested.") + return redirect("panel:customer_backups", pk=self.account.pk) diff --git a/src/coulobre/hosting/installation_views.py b/src/coulobre/hosting/installation_views.py index 9e73056..254b8ce 100644 --- a/src/coulobre/hosting/installation_views.py +++ b/src/coulobre/hosting/installation_views.py @@ -3,10 +3,7 @@ from importlib.metadata import PackageNotFoundError, version from django import forms from django.contrib import messages from django.contrib.admin.models import CHANGE, LogEntry -from django.contrib.auth.mixins import ( - PermissionRequiredMixin, - UserPassesTestMixin, -) +from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.db import transaction from django.db.models import F from django.urls import reverse_lazy @@ -14,17 +11,14 @@ from django.utils.decorators import method_decorator from django.views.decorators.cache import never_cache from django.views.generic import FormView, TemplateView -from .access import OperatorOnlyMixin +from .access import is_tenant from .installation_features import FEATURES, FeaturePolicy from .models import PanelFeaturePolicy from .update_views import inspect_linked_nodes @method_decorator(never_cache, name="dispatch") -class InstallationView( - OperatorOnlyMixin, PermissionRequiredMixin, TemplateView -): - permission_required = "hosting.view_servicehealth" +class InstallationView(LoginRequiredMixin, TemplateView): template_name = "hosting/installation.html" def get_context_data(self, **kwargs): @@ -34,7 +28,10 @@ class InstallationView( installed_version = "Unavailable" policy = FeaturePolicy() features = [] - for feature in FEATURES: + may_view = not is_tenant( + self.request.user + ) and self.request.user.has_perm("hosting.view_servicehealth") + for feature in FEATURES if may_view else (): configured = feature.configured enabled = ( configured diff --git a/src/coulobre/hosting/invitations.py b/src/coulobre/hosting/invitations.py index 02c0499..ca35aa1 100644 --- a/src/coulobre/hosting/invitations.py +++ b/src/coulobre/hosting/invitations.py @@ -103,7 +103,7 @@ invitation_token = InvitationToken() @transaction.atomic -def queue_invitation(user): +def queue_invitation(user, *, welcome_message=None): user = lock_user(user.pk) if not may_accept_invitation(user): return None @@ -113,6 +113,11 @@ def queue_invitation(user): "revision": uuid.uuid4(), "created_at": timezone.now(), "delivery": PanelInvitation.Delivery.PENDING, + **( + {"welcome_message": welcome_message} + if welcome_message is not None + else {} + ), }, ) if not reset_enabled(): @@ -178,6 +183,7 @@ def deliver_invitation(invitation_id, revision): "hosting/panel_invitation.txt", { "username": user.get_username(), + "welcome_message": invitation.welcome_message, "setup_url": origin + path, "panel_url": origin + "/", "account": account, diff --git a/src/coulobre/hosting/migrations/0060_welcome_message.py b/src/coulobre/hosting/migrations/0060_welcome_message.py new file mode 100644 index 0000000..9722938 --- /dev/null +++ b/src/coulobre/hosting/migrations/0060_welcome_message.py @@ -0,0 +1,17 @@ +# Generated by Django 5.2.19 on 2026-11-23 21:06 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0059_panel_feature_policy"), + ] + + operations = [ + migrations.AddField( + model_name="panelinvitation", + name="welcome_message", + field=models.TextField(blank=True, default=""), + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index a2c0fc9..4f8e008 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -160,6 +160,8 @@ class Customer(models.Model): class PanelInvitation(models.Model): + welcome_message = models.TextField(blank=True, default="") + class Delivery(models.TextChoices): PENDING = "pending", "Waiting to send" SENT = "sent", "Sent" diff --git a/src/coulobre/hosting/panel_roles.py b/src/coulobre/hosting/panel_roles.py index 04aaff8..c2acc7e 100644 --- a/src/coulobre/hosting/panel_roles.py +++ b/src/coulobre/hosting/panel_roles.py @@ -23,7 +23,7 @@ SESSION_ROLE = "coulobre_panel_role" ROLE_LABELS = { PanelRole.ADMIN: "Server administrator", PanelRole.CUSTOMER: "Customer", - PanelRole.MANAGER: "Customer manager", + PanelRole.MANAGER: "Manager", } @@ -42,6 +42,20 @@ def assigned_roles(user): return roles +def ensure_operator_manager(user): + if not user.is_superuser or hasattr(user, "hosting_reseller"): + return + profile = ResellerProfile.objects.filter(default_slot=1).first() + defaults = {"account_limit": profile.account_limit} if profile else {} + with transaction.atomic(): + manager, created = Reseller.objects.get_or_create( + user=user, defaults=defaults + ) + if created and profile is not None: + manager.hosting_plans.set(profile.hosting_plans.all()) + user.hosting_reseller = manager + + def deny_permission(*args, **kwargs): return False @@ -84,7 +98,9 @@ class PanelRoleMiddleware: def __call__(self, request): response = self.get_response(request) - if getattr(request, "active_panel_role", None): + if getattr( + request, "active_panel_role", None + ) and "no-store" not in response.get("Cache-Control", ""): add_never_cache_headers(response) return response @@ -92,6 +108,7 @@ class PanelRoleMiddleware: if not request.user.is_authenticated: return None user = get_user(request) + ensure_operator_manager(user) roles = assigned_roles(user) selection = request.session.get(SESSION_ROLE) if selection is None: diff --git a/src/coulobre/hosting/reseller_views.py b/src/coulobre/hosting/reseller_views.py index 384f51a..7ee823f 100644 --- a/src/coulobre/hosting/reseller_views.py +++ b/src/coulobre/hosting/reseller_views.py @@ -163,8 +163,8 @@ class ResellerCreate( form_class = InviteLoginForm template_name = "hosting/reseller_form.html" extra_context = { - "page_title": "Add customer manager", - "submit_label": "Add customer manager", + "page_title": "Add manager", + "submit_label": "Add manager", } @cached_property @@ -220,7 +220,7 @@ class ResellerEdit( form_class = ResellerPolicyForm template_name = "hosting/reseller_form.html" extra_context = { - "page_title": "Edit customer manager", + "page_title": "Edit manager", "submit_label": "Save changes", } diff --git a/src/coulobre/hosting/static/hosting/panel.css b/src/coulobre/hosting/static/hosting/panel.css index f62287a..dfcf4f2 100644 --- a/src/coulobre/hosting/static/hosting/panel.css +++ b/src/coulobre/hosting/static/hosting/panel.css @@ -1179,3 +1179,29 @@ dd { padding-inline-end: max(var(--page-padding), 3.7rem); } } + +.workspace-context { + margin-bottom: var(--section-gap); +} + +.workspace-context select { + max-width: 100%; +} + +.workspace-list { + margin: 0; + padding: 1rem 1.2rem 1rem 2.3rem; +} + +.workspace-list li + li { + margin-top: 0.4rem; +} + +.sidebar-account .appearance-control { + display: block; + margin: 0.35rem 0; +} + +.sidebar-account .appearance-control[hidden] { + display: none; +} diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index a306962..270188c 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -17,7 +17,7 @@
Hosting plan
{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}Unassigned{% endif %}
{% endif %} {% if is_operator and perms.hosting.view_reseller %} -
Customer manager
{{ account.reseller|default_if_none:"Unassigned" }}
+
Manager
{{ account.reseller|default_if_none:"Unassigned" }}
{% endif %} {% if is_operator and perms.hosting.view_customer %}
Customer
{{ account.customer|default_if_none:"No customer linked" }}
diff --git a/src/coulobre/hosting/templates/hosting/account_retirement.html b/src/coulobre/hosting/templates/hosting/account_retirement.html index 9ebc7fa..8108e60 100644 --- a/src/coulobre/hosting/templates/hosting/account_retirement.html +++ b/src/coulobre/hosting/templates/hosting/account_retirement.html @@ -20,7 +20,7 @@
DNS zones
{% for zone in inventory.zones %}{{ zone.domain }}{% if zone.published is not None %} (published serial {{ zone.published }}){% endif %}{% if not forloop.last %}, {% endif %}{% empty %}None{% endfor %}
Existing backups
{{ inventory.backups }}
{% if inventory.customer %}
Customer
{{ inventory.customer }}
{% endif %} - {% if inventory.reseller %}
Customer manager
{{ inventory.reseller }}
{% endif %} + {% if inventory.reseller %}
Manager
{{ inventory.reseller }}
{% endif %} {% if retirement %} diff --git a/src/coulobre/hosting/templates/hosting/all_users.html b/src/coulobre/hosting/templates/hosting/all_users.html new file mode 100644 index 0000000..b99b68b --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/all_users.html @@ -0,0 +1,22 @@ +{% extends "hosting/base.html" %} +{% block title %}All users · Coulobre Panel{% endblock %} +{% block content %} +

All users

+
+
+ + +
+
+ + + + {% for login in logins %} + + {% empty %}{% endfor %} + +
UserWorkspaceManagerHosting accountsAdded
{{ login.get_username }}{% if login.is_superuser %}Operator{% elif login.hosting_reseller %}Manager{% else %}Customer{% endif %}{{ login.hosting_customer.reseller|default:"Unassigned" }}{{ login.account_count }}{{ login.date_joined|date:"j M Y" }}
No logins found.
+
+ {% include "hosting/pagination.html" %} +
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/base.html b/src/coulobre/hosting/templates/hosting/base.html index c17a9e7..e6025a7 100644 --- a/src/coulobre/hosting/templates/hosting/base.html +++ b/src/coulobre/hosting/templates/hosting/base.html @@ -22,74 +22,12 @@ Menu
+ {% if workspace_accounts %} + + + + + + {% endif %} {% if request.impersonation %}
@@ -132,9 +85,9 @@ {% else %} {% block public_content %}{% endblock %} + {% endif %} - diff --git a/src/coulobre/hosting/templates/hosting/customer_backups.html b/src/coulobre/hosting/templates/hosting/customer_backups.html new file mode 100644 index 0000000..49af019 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/customer_backups.html @@ -0,0 +1,19 @@ +{% extends "hosting/base.html" %} +{% block title %}Backup & Restore · Coulobre Panel{% endblock %} +{% block content %} +

Backup & Restore

{{ account.primary_domain }}

+ {% for message in messages %}

{{ message }}

{% endfor %} + {% if may_create %} +
+

Create a backup

+
{% csrf_token %}{{ form.as_div }}
+
+ {% endif %} +
+

Recent backups

+
    + {% for backup in backups %}
  • {{ backup.requested_at|date:"j M Y H:i" }} · {% if not backup.finished_at %}Queued{% elif backup.problem %}Failed{% else %}Ready{% endif %}
  • + {% empty %}
  • No backups yet.
  • {% endfor %} +
+
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/installation.html b/src/coulobre/hosting/templates/hosting/installation.html index af16dc4..195b471 100644 --- a/src/coulobre/hosting/templates/hosting/installation.html +++ b/src/coulobre/hosting/templates/hosting/installation.html @@ -10,9 +10,10 @@
Installed version
{{ installed_version }}
Core software license
Apache License 2.0
+
-
+ {% if features %}

Feature configuration

@@ -45,5 +46,5 @@
-
+
{% endif %} {% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/manager_packages.html b/src/coulobre/hosting/templates/hosting/manager_packages.html new file mode 100644 index 0000000..2e51623 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/manager_packages.html @@ -0,0 +1,11 @@ +{% extends "hosting/base.html" %} +{% block title %}User packages · Coulobre Panel{% endblock %} +{% block content %} +

User packages

+
+
    + {% for plan in plans %}
  • {{ plan.name }}{% if plan.description %}

    {{ plan.description }}

    {% endif %}
  • + {% empty %}
  • No packages have been made available to you.
  • {% endfor %} +
+
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/panel_invitation.txt b/src/coulobre/hosting/templates/hosting/panel_invitation.txt index 88a5c7a..91e0901 100644 --- a/src/coulobre/hosting/templates/hosting/panel_invitation.txt +++ b/src/coulobre/hosting/templates/hosting/panel_invitation.txt @@ -1,4 +1,6 @@ -Welcome to Coulobre Panel. +{% if welcome_message %}{{ welcome_message }} + +{% endif %}Welcome to Coulobre Panel. Username: {{ username }} Panel: {{ panel_url }} diff --git a/src/coulobre/hosting/templates/hosting/reseller_detail.html b/src/coulobre/hosting/templates/hosting/reseller_detail.html index bcad959..4df0dec 100644 --- a/src/coulobre/hosting/templates/hosting/reseller_detail.html +++ b/src/coulobre/hosting/templates/hosting/reseller_detail.html @@ -1,12 +1,12 @@ {% extends "hosting/base.html" %} {% block title %}{{ reseller }} · Coulobre Panel{% endblock %} {% block content %} - ← Customer managers + ← Managers

{{ reseller }}

{% if perms.hosting.change_reseller %} Contact and invitation - Edit customer manager + Edit manager {% endif %}
diff --git a/src/coulobre/hosting/templates/hosting/reseller_form.html b/src/coulobre/hosting/templates/hosting/reseller_form.html index 9ae0dec..02e92d4 100644 --- a/src/coulobre/hosting/templates/hosting/reseller_form.html +++ b/src/coulobre/hosting/templates/hosting/reseller_form.html @@ -1,14 +1,14 @@ {% extends "hosting/base.html" %} {% block title %}{{ page_title }} · Coulobre Panel{% endblock %} {% block content %} - ← {% if reseller %}{{ reseller }}{% else %}Customer managers{% endif %} + ← {% if reseller %}{{ reseller }}{% else %}Managers{% endif %}

{{ page_title }}

{% if profiles %}
- - {% for profile in profiles %}{% endfor %} diff --git a/src/coulobre/hosting/templates/hosting/reseller_list.html b/src/coulobre/hosting/templates/hosting/reseller_list.html index 7f8b29e..359a0c4 100644 --- a/src/coulobre/hosting/templates/hosting/reseller_list.html +++ b/src/coulobre/hosting/templates/hosting/reseller_list.html @@ -1,8 +1,8 @@ {% extends "hosting/base.html" %} -{% block title %}Customer managers · Coulobre Panel{% endblock %} +{% block title %}Managers · Coulobre Panel{% endblock %} {% block content %}
-

Customer managers

+

Managers

{% if perms.hosting.change_reseller and perms.hosting.view_hostingplan %} Profiles @@ -11,11 +11,11 @@ {% if request.user.is_superuser and request.user.is_verified %} Assign to existing login {% endif %} - Add customer manager + Add manager {% endif %}
-
+
@@ -40,9 +40,9 @@
{% elif search %} -

No customer managers match this search.

+

No managers match this search.

{% else %} -

No customer managers yet.

+

No managers yet.

{% endif %} {% include "hosting/pagination.html" %}
diff --git a/src/coulobre/hosting/templates/hosting/reseller_profile_form.html b/src/coulobre/hosting/templates/hosting/reseller_profile_form.html index fbe7961..4c15049 100644 --- a/src/coulobre/hosting/templates/hosting/reseller_profile_form.html +++ b/src/coulobre/hosting/templates/hosting/reseller_profile_form.html @@ -1,7 +1,7 @@ {% extends "hosting/base.html" %} {% block title %}{% if object %}Edit profile{% else %}Add profile{% endif %} · Coulobre Panel{% endblock %} {% block content %} - ← Customer manager profiles + ← Manager profiles

{% if object %}Edit profile{% else %}Add profile{% endif %}

diff --git a/src/coulobre/hosting/templates/hosting/reseller_profile_list.html b/src/coulobre/hosting/templates/hosting/reseller_profile_list.html index d096030..259660b 100644 --- a/src/coulobre/hosting/templates/hosting/reseller_profile_list.html +++ b/src/coulobre/hosting/templates/hosting/reseller_profile_list.html @@ -1,9 +1,9 @@ {% extends "hosting/base.html" %} -{% block title %}Customer manager profiles · Coulobre Panel{% endblock %} +{% block title %}Manager profiles · Coulobre Panel{% endblock %} {% block content %} - ← Customer managers + ← Managers
-

Customer manager profiles

+

Manager profiles

Add profile
diff --git a/src/coulobre/hosting/templates/hosting/system_workspace.html b/src/coulobre/hosting/templates/hosting/system_workspace.html new file mode 100644 index 0000000..561f3e2 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/system_workspace.html @@ -0,0 +1,16 @@ +{% extends "hosting/base.html" %} +{% block title %}{{ title }} · Coulobre Panel{% endblock %} +{% block content %} +

{{ title }}

+
+
    + {% for account in accounts %} +
  • + {% if target %}{{ account.primary_domain }} + {% else %}{{ account.primary_domain }}{% endif %} +
  • + {% empty %}
  • No hosting accounts are available.
  • {% endfor %} +
+ {% if not target %}

This service needs setup.

{% endif %} +
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/workspace_form.html b/src/coulobre/hosting/templates/hosting/workspace_form.html new file mode 100644 index 0000000..f3ce334 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/workspace_form.html @@ -0,0 +1,21 @@ +{% extends "hosting/base.html" %} +{% block title %}{{ title }} · Coulobre Panel{% endblock %} +{% block content %} +

{{ title }}

+
+ + {% csrf_token %} + {{ form.as_div }} + {% if invitation_preview %} +
+ Welcome email preview +

The message includes an invitation link for choosing a password and setup details for the new hosting account. Your welcome text appears before the setup details.

+
+ {% endif %} +
+ + Cancel +
+ +
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/workspace_navigation.html b/src/coulobre/hosting/templates/hosting/workspace_navigation.html new file mode 100644 index 0000000..9ddb800 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/workspace_navigation.html @@ -0,0 +1,8 @@ +{% for title, entries in navigation_groups %} + +{% endfor %} diff --git a/src/coulobre/hosting/test_service_health.py b/src/coulobre/hosting/test_service_health.py index d09117f..0b6cfd6 100644 --- a/src/coulobre/hosting/test_service_health.py +++ b/src/coulobre/hosting/test_service_health.py @@ -181,7 +181,9 @@ class ServiceHealthPanelTests(TestCase): for user in (self.viewer, self.customer, self.reseller): with self.subTest(user=user): self.client.force_login(user) - self.assertEqual(self.client.get(url).status_code, 403) + response = self.client.get(url) + self.assertContains(response, "Apache License 2.0") + self.assertNotContains(response, "Feature configuration") self.client.force_login(self.operator) with patch( diff --git a/src/coulobre/hosting/test_workspaces.py b/src/coulobre/hosting/test_workspaces.py new file mode 100644 index 0000000..b02839b --- /dev/null +++ b/src/coulobre/hosting/test_workspaces.py @@ -0,0 +1,122 @@ +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.test import TestCase +from django.urls import reverse + +from .models import Customer, HostingAccount, HostingPlan, Reseller + + +class WorkspaceTests(TestCase): + def test_operator_has_its_own_manager_workspace(self): + operator = get_user_model().objects.create_superuser("operator") + self.client.force_login(operator) + landing = self.client.get(reverse("panel:accounts")) + self.assertContains( + landing, '', html=True + ) + profile = Reseller.objects.get(user=operator) + unrelated = HostingAccount.objects.create( + name="Other hosting", primary_domain="other.test" + ) + account = HostingAccount.objects.create( + name="Managed hosting", + primary_domain="managed.test", + reseller=profile, + ) + self.assertRedirects( + self.client.post( + reverse("panel:switch_panel_role"), {"role": "manager"} + ), + reverse("panel:accounts"), + ) + self.assertContains( + self.client.get(reverse("panel:accounts")), account.primary_domain + ) + self.assertEqual( + self.client.get(unrelated.get_absolute_url()).status_code, 404 + ) + self.assertEqual( + self.client.get( + reverse("panel:feature_configuration") + ).status_code, + 403, + ) + + def test_customer_workspace_selection_checks_account_ownership(self): + customer = Customer.objects.create( + user=get_user_model().objects.create_user("customer") + ) + first = HostingAccount.objects.create( + name="First", primary_domain="first.test", customer=customer + ) + second = HostingAccount.objects.create( + name="Second", primary_domain="second.test", customer=customer + ) + foreign = HostingAccount.objects.create( + name="Other", primary_domain="other.test" + ) + self.client.force_login(customer.user) + dns = reverse("panel:customer_workspace", args=["dns"]) + self.assertRedirects( + self.client.get(dns, {"account": second.pk}), + second.get_absolute_url() + "#domains-dns", + ) + self.assertRedirects( + self.client.get(dns), second.get_absolute_url() + "#domains-dns" + ) + self.assertEqual( + self.client.get(dns, {"account": foreign.pk}).status_code, 404 + ) + HostingAccount.objects.filter(pk=second.pk).update(customer=None) + self.assertRedirects( + self.client.get(dns), first.get_absolute_url() + "#domains-dns" + ) + + def test_manager_creates_login_and_hosting_under_its_own_policy(self): + manager = Reseller.objects.create( + user=get_user_model().objects.create_user("manager"), + account_limit=1, + ) + plan = HostingPlan.objects.create(name="Available") + outside = HostingPlan.objects.create(name="Outside") + manager.hosting_plans.add(plan) + self.client.force_login(manager.user) + form = reverse("panel:customer_onboarding") + details = { + "username": "shop", + "email": "shop@example.test", + "primary_domain": "SHOP.EXAMPLE.TEST.", + "send_invitation": "on", + "welcome_message": "Welcome to your shop.", + } + with patch( + "coulobre.hosting.account_administration.queue_invitation" + ) as invite: + response = self.client.post(form, details | {"plan": outside.pk}) + self.assertEqual(response.status_code, 200) + self.assertFalse(Customer.objects.exists()) + response = self.client.post(form, details | {"plan": plan.pk}) + account = HostingAccount.objects.get( + primary_domain="shop.example.test" + ) + self.assertRedirects(response, account.get_absolute_url()) + invite.assert_called_once_with( + account.customer.user, welcome_message="Welcome to your shop." + ) + self.assertEqual(account.reseller, manager) + self.assertEqual(account.customer.reseller, manager) + self.assertFalse(account.customer.user.has_usable_password()) + response = self.client.post( + form, + details + | { + "plan": plan.pk, + "username": "overflow", + "primary_domain": "overflow.example.test", + }, + ) + self.assertContains(response, "hosting account limit") + self.assertFalse( + get_user_model().objects.filter(username="overflow").exists() + ) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index c151a2f..cac1d1c 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -2,6 +2,13 @@ from django.contrib.auth.views import LogoutView from django.urls import path from . import themes, views +from .account_administration import ( + AllUsersView, + ManagerOnboardingView, + ManagerPackagesView, + MoveHostingView, + OperatorCreateView, +) from .account_security import ( AccountSecurityView, ChangeEmailView, @@ -14,6 +21,7 @@ from .account_security import ( ) from .backup_restores import RestoreKind from .credential_views import DatabaseCredentialView, MailboxCredentialView +from .customer_backup_views import CustomerBackupView from .dns_defaults_views import DnsDefaultsView from .dns_replica_views import DnsReplicaView from .health_views import ServiceHealthView @@ -62,10 +70,35 @@ from .update_views import UpdateView from .website_file_views import WebsiteFilesView from .website_job_views import WebsiteJobEditor, WebsiteJobList from .website_usage_views import WebsiteUsageView +from .workspaces import customer_workspace, system_workspace app_name = "panel" urlpatterns = [ + path( + "hosting//", customer_workspace, name="customer_workspace" + ), + path("system//", system_workspace, name="system_workspace"), + path("users/", AllUsersView.as_view(), name="all_users"), + path( + "users/new/", + ManagerOnboardingView.as_view(), + name="customer_onboarding", + ), + path("users/move/", MoveHostingView.as_view(), name="move_accounts"), + path( + "operators/new/", OperatorCreateView.as_view(), name="operator_create" + ), + path( + "manager/packages/", + ManagerPackagesView.as_view(), + name="manager_packages", + ), + path( + "accounts//backup/", + CustomerBackupView.as_view(), + name="customer_backups", + ), path("panel-theme.css", themes.stylesheet, name="theme_stylesheet"), path("updates/", UpdateView.as_view(), name="updates"), path("dns-template/", DnsDefaultsView.as_view(), name="dns_defaults"), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 999f89c..a633d1a 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -460,7 +460,7 @@ class AccountEditor: "user" ).order_by("user__username") if "reseller" in form.fields: - form.fields["reseller"].label = "Customer manager" + form.fields["reseller"].label = "Manager" return form diff --git a/src/coulobre/hosting/workspaces.py b/src/coulobre/hosting/workspaces.py new file mode 100644 index 0000000..14b10d1 --- /dev/null +++ b/src/coulobre/hosting/workspaces.py @@ -0,0 +1,227 @@ +from django.conf import settings +from django.core.exceptions import PermissionDenied +from django.http import Http404 +from django.shortcuts import get_object_or_404, redirect, render +from django.urls import reverse +from django.views.decorators.cache import never_cache +from django.views.decorators.http import require_safe + +from .access import customer_for_user, reseller_for_user +from .installation_features import panel_feature_allowed +from .models import HostingAccount + +CUSTOMER_ACCOUNT = "coulobre_active_hosting_account" + +# Entries use stable URL names and the account page's existing sections. +CUSTOMER_PAGES = { + "domains": ("Domains", "account", "websites"), + "dns": ("DNS Editor", "account", "domains-dns"), + "php": ("PHP Settings", "account", "websites"), + "files": ("File Manager", "website_files", ""), + "sftp": ("SFTP Users", "sftp_keys", ""), + "databases": ("Databases", "account", "databases"), + "email": ("Email Accounts", "account", "email"), + "forwarders": ("Forwarders", "account", "email"), + "replies": ("Automatic replies", "account", "email"), + "backups": ("Backup & Restore", "customer_backups", ""), + "tasks": ("Scheduled Tasks", "website_jobs", ""), +} +SYSTEM_PAGES = { + "tasks": ("Scheduled Tasks", "website_jobs"), + "logs": ("Logs", "website_usage"), + "statistics": ("Statistics", "website_usage"), +} + + +def workspace_accounts(user): + accounts = HostingAccount.objects.filter(retired_at__isnull=True) + customer = customer_for_user(user) + manager = reseller_for_user(user) + if customer is not None: + return accounts.filter(customer=customer) + if manager is not None: + return accounts.filter(reseller=manager) + if user.has_perm("hosting.view_hostingaccount"): + return accounts + return accounts.none() + + +def customer_pages(request): + pages = CUSTOMER_PAGES.copy() + for key, enabled in ( + ("files", panel_feature_allowed("WEB_FILE_MANAGER")), + ("sftp", settings.LOCAL_WEB_SFTP), + ("backups", panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS")), + ("tasks", panel_feature_allowed("WEBSITE_JOBS")), + ): + if not enabled: + pages.pop(key) + return pages + + +@require_safe +@never_cache +def customer_workspace(request, page): + if customer_for_user(request.user) is None: + raise PermissionDenied + pages = customer_pages(request) + if page != "overview" and page not in pages: + raise Http404 + accounts = workspace_accounts(request.user).order_by("primary_domain") + selected = request.GET.get("account") + if selected is not None: + if ( + not selected.isascii() + or not selected.isdecimal() + or len(selected) > 18 + ): + raise Http404 + account = get_object_or_404(accounts, pk=int(selected)) + request.session[CUSTOMER_ACCOUNT] = account.pk + else: + account = accounts.filter( + pk=request.session.get(CUSTOMER_ACCOUNT) + ).first() + account = account or accounts.first() + if account is None: + return redirect("panel:accounts") + if page == "overview": + return redirect(account) + _, destination, fragment = pages[page] + return redirect( + reverse( + f"panel:{destination}", + args=[account.pk], + fragment=fragment or None, + ) + ) + + +@require_safe +@never_cache +def system_workspace(request, page): + if not request.user.is_authenticated: + raise PermissionDenied + if page not in SYSTEM_PAGES: + raise Http404 + title, target = SYSTEM_PAGES[page] + accounts = workspace_accounts(request.user).order_by("primary_domain") + if page == "tasks": + may_open = ( + panel_feature_allowed("WEBSITE_JOBS") + and reseller_for_user(request.user) is None + ) + else: + may_open = settings.WEBSITE_USAGE and ( + customer_for_user(request.user) is not None + or reseller_for_user(request.user) is not None + or request.user.has_perm("hosting.view_websiteusage") + ) + return render( + request, + "hosting/system_workspace.html", + { + "title": title, + "accounts": accounts, + "target": f"panel:{target}" if may_open else None, + }, + ) + + +def link(route, label, *args): + return (reverse(f"panel:{route}", args=args), label) + + +def groups_for(request, *, customer, manager): + user = request.user + if not user.is_authenticated: + return () + if getattr(request, "impersonation", None): + return (("Account Manager", [link("accounts", "My hosting")]),) + if customer: + pages = customer_pages(request) + + def hosted(*keys): + return [ + link("customer_workspace", pages[key][0], key) + for key in keys + if key in pages + ] + + groups = [ + ( + "Account Manager", + [ + link("accounts", "My hosting"), + *hosted( + "domains", "dns", "sftp", "databases", "php", "files" + ), + ], + ), + ("Email Manager", hosted("email", "forwarders", "replies")), + ( + "Advanced Features", + [ + *hosted("backups", "tasks"), + link("account_security", "Security"), + ], + ), + ] + elif manager: + groups = [ + ( + "Account Manager", + [ + link("customer_onboarding", "Add New User"), + link("customers", "My Users"), + link("accounts", "Customer hosting"), + link("manager_packages", "User Packages"), + ], + ) + ] + else: + accounts = [] + for permission, route, label in ( + ("view_hostingaccount", "accounts", "Hosting accounts"), + ("view_customer", "all_users", "Show All Users"), + ("view_reseller", "resellers", "Managers"), + ("add_reseller", "reseller_create", "Add New Reseller"), + ("view_hostingplan", "hosting_plans", "Hosting plans"), + ): + if user.has_perm(f"hosting.{permission}"): + accounts.append(link(route, label)) + server, admin_tools = [], [] + if user.has_perm("hosting.view_webprovisioningplan"): + server.append(link("plans", "Web provisioning")) + if user.has_perm("hosting.view_servicehealth"): + admin_tools.append(link("service_health", "System Services")) + if user.is_superuser: + accounts.extend( + ( + link("operator_create", "Add New Operator"), + link("reseller_profiles", "Reseller Packages"), + link("move_accounts", "Move Users"), + ) + ) + server.extend( + ( + link("feature_configuration", "Operator Settings"), + link("dns_defaults", "DNS Settings"), + ) + ) + groups = [ + ("Account Manager", accounts), + ("Server Manager", server), + ("Admin Tools", admin_tools), + ] + system = [ + link("system_workspace", title, key) + for key, (title, _) in SYSTEM_PAGES.items() + ] + if user.is_superuser: + system.append(link("updates", "Updates")) + groups += [ + ("System", system), + ("Support", [link("installation", "About Coulobre")]), + ] + return [(name, entries) for name, entries in groups if entries]