diff --git a/src/coulobre/hosting/impersonation.py b/src/coulobre/hosting/impersonation.py
new file mode 100644
index 0000000..5a7cb0d
--- /dev/null
+++ b/src/coulobre/hosting/impersonation.py
@@ -0,0 +1,129 @@
+from datetime import timedelta
+
+from django.middleware.csrf import rotate_token
+from django.shortcuts import render
+from django.utils import timezone
+from django.utils.cache import add_never_cache_headers
+
+from .access import is_tenant
+from .models import CustomerImpersonation
+
+SESSION_KEY = "customer_impersonation"
+SESSION_DURATION = timedelta(minutes=30)
+IMPERSONATE_CUSTOMER = (
+ "hosting.view_customer",
+ "hosting.impersonate_customer",
+)
+PREVIEW_VIEWS = frozenset(
+ {
+ "panel:accounts",
+ "panel:account",
+ "panel:database_create",
+ "panel:mailbox_create",
+ }
+)
+EndReason = CustomerImpersonation.EndReason
+
+
+def can_impersonate_customer(user):
+ return (
+ user.is_authenticated
+ and user.is_active
+ and user.is_staff
+ and not is_tenant(user)
+ and user.has_perms(IMPERSONATE_CUSTOMER)
+ )
+
+
+def start_impersonation(request, customer):
+ now = timezone.now()
+ session = CustomerImpersonation.objects.create(
+ operator=request.user,
+ customer=customer,
+ operator_username=request.user.get_username(),
+ customer_username=customer.user.get_username(),
+ started_at=now,
+ expires_at=now + SESSION_DURATION,
+ )
+ request.session[SESSION_KEY] = session.pk
+ rotate_token(request)
+
+
+def end_impersonation(request, session, reason):
+ if session is not None:
+ CustomerImpersonation.objects.filter(
+ pk=session.pk, ended_at__isnull=True
+ ).update(
+ ended_at=min(timezone.now(), session.expires_at),
+ end_reason=reason,
+ )
+ request.session.pop(SESSION_KEY, None)
+ rotate_token(request)
+
+
+class CustomerImpersonationMiddleware:
+ def __init__(self, get_response):
+ self.get_response = get_response
+
+ def __call__(self, request):
+ had_preview = SESSION_KEY in request.session
+ response = self.get_response(request)
+ if had_preview or SESSION_KEY in request.session:
+ add_never_cache_headers(response)
+ return response
+
+ def process_view(self, request, view_func, view_args, view_kwargs):
+ session_id = request.session.get(SESSION_KEY)
+ if session_id is None:
+ return None
+
+ view_name = request.resolver_match.view_name
+ signing_out = view_name == "panel:logout" and request.method == "POST"
+ session = (
+ CustomerImpersonation.objects.select_related(
+ "customer__user__hosting_reseller"
+ )
+ .filter(
+ pk=session_id,
+ operator_id=request.user.pk,
+ ended_at__isnull=True,
+ )
+ .first()
+ )
+ if session is None:
+ reason = EndReason.ACCESS_REVOKED
+ elif session.expires_at <= timezone.now():
+ reason = EndReason.EXPIRED
+ elif (
+ not can_impersonate_customer(request.user)
+ or session.customer is None
+ or not session.customer.may_be_impersonated
+ ):
+ reason = EndReason.ACCESS_REVOKED
+ else:
+ reason = None
+
+ if signing_out:
+ end_impersonation(request, session, reason or EndReason.SIGNED_OUT)
+ return None
+ if reason is not None:
+ end_impersonation(request, session, reason)
+ # Block stale requests before restoring operator access.
+ return render(
+ request, "hosting/customer_preview_restricted.html", status=409
+ )
+
+ request.impersonation = session
+ if view_name == "panel:impersonation_stop":
+ return None
+
+ async def preview_user():
+ return session.customer.user
+
+ request.user = session.customer.user
+ request.auser = preview_user
+ if request.method in ("GET", "HEAD") and view_name in PREVIEW_VIEWS:
+ return None
+ return render(
+ request, "hosting/customer_preview_restricted.html", status=403
+ )
diff --git a/src/coulobre/hosting/migrations/0017_customer_impersonation.py b/src/coulobre/hosting/migrations/0017_customer_impersonation.py
new file mode 100644
index 0000000..14c259d
--- /dev/null
+++ b/src/coulobre/hosting/migrations/0017_customer_impersonation.py
@@ -0,0 +1,80 @@
+# Generated by Django 5.2.19 on 2026-11-21 01:18
+
+import django.db.models.deletion
+import django.utils.timezone
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("hosting", "0016_mailbox_provisioning"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="CustomerImpersonation",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("operator_username", models.CharField(max_length=150)),
+ ("customer_username", models.CharField(max_length=150)),
+ (
+ "started_at",
+ models.DateTimeField(default=django.utils.timezone.now),
+ ),
+ ("expires_at", models.DateTimeField()),
+ ("ended_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "end_reason",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("stopped", "Ended by administrator"),
+ ("signed_out", "Signed out"),
+ ("expired", "Expired"),
+ ("access_revoked", "Access revoked"),
+ ],
+ max_length=16,
+ ),
+ ),
+ (
+ "customer",
+ models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="hosting.customer",
+ ),
+ ),
+ (
+ "operator",
+ models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "verbose_name": "customer impersonation session",
+ "ordering": ("-started_at", "-pk"),
+ "permissions": (
+ (
+ "impersonate_customer",
+ "Can view the panel as a customer",
+ ),
+ ),
+ "default_permissions": ("view",),
+ },
+ ),
+ ]
diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py
index 30ca7a3..2bd3e9c 100644
--- a/src/coulobre/hosting/models.py
+++ b/src/coulobre/hosting/models.py
@@ -56,6 +56,56 @@ class Customer(models.Model):
def __str__(self):
return self.user.get_username()
+ @property
+ def may_be_impersonated(self):
+ user = self.user
+ return (
+ user.is_active
+ and not user.is_staff
+ and not user.is_superuser
+ and not hasattr(user, "hosting_reseller")
+ )
+
+
+class CustomerImpersonation(models.Model):
+ class EndReason(models.TextChoices):
+ STOPPED = "stopped", "Ended by administrator"
+ SIGNED_OUT = "signed_out", "Signed out"
+ EXPIRED = "expired", "Expired"
+ ACCESS_REVOKED = "access_revoked", "Access revoked"
+
+ operator = models.ForeignKey(
+ settings.AUTH_USER_MODEL,
+ on_delete=models.SET_NULL,
+ null=True,
+ related_name="+",
+ )
+ customer = models.ForeignKey(
+ Customer,
+ on_delete=models.SET_NULL,
+ null=True,
+ related_name="+",
+ )
+ operator_username = models.CharField(max_length=150)
+ customer_username = models.CharField(max_length=150)
+ started_at = models.DateTimeField(default=timezone.now)
+ expires_at = models.DateTimeField()
+ ended_at = models.DateTimeField(null=True, blank=True)
+ end_reason = models.CharField(
+ max_length=16, choices=EndReason.choices, blank=True
+ )
+
+ class Meta:
+ ordering = ("-started_at", "-pk")
+ default_permissions = ("view",)
+ verbose_name = "customer impersonation session"
+ permissions = (
+ ("impersonate_customer", "Can view the panel as a customer"),
+ )
+
+ def __str__(self):
+ return f"{self.operator_username} viewing as {self.customer_username}"
+
class HostingPlan(models.Model):
name = models.CharField(max_length=120, unique=True)
diff --git a/src/coulobre/hosting/static/hosting/panel.css b/src/coulobre/hosting/static/hosting/panel.css
index bcc92ed..88d7e1a 100644
--- a/src/coulobre/hosting/static/hosting/panel.css
+++ b/src/coulobre/hosting/static/hosting/panel.css
@@ -450,6 +450,25 @@ dd {
background: #e7eee5;
}
+.customer-preview, .table-actions {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 0.6rem;
+}
+
+.customer-preview {
+ justify-content: space-between;
+ border-color: var(--focus);
+ background: #f5ead6;
+ color: #6b431b;
+ overflow-wrap: anywhere;
+}
+
+.customer-preview p {
+ margin: 0.2rem 0 0;
+}
+
.status {
display: inline-block;
padding: 0.18rem 0.55rem;
diff --git a/src/coulobre/hosting/templates/hosting/base.html b/src/coulobre/hosting/templates/hosting/base.html
index 42569d3..760ec1a 100644
--- a/src/coulobre/hosting/templates/hosting/base.html
+++ b/src/coulobre/hosting/templates/hosting/base.html
@@ -52,6 +52,18 @@
+ {% if request.impersonation %}
+
+
+
Viewing as {{ request.impersonation.customer }}
+
Read-only support session
+
+
+
+ {% endif %}
{% block content %}{% endblock %}
diff --git a/src/coulobre/hosting/templates/hosting/customer_list.html b/src/coulobre/hosting/templates/hosting/customer_list.html
index fce179f..f02b8ca 100644
--- a/src/coulobre/hosting/templates/hosting/customer_list.html
+++ b/src/coulobre/hosting/templates/hosting/customer_list.html
@@ -21,7 +21,7 @@
| Username |
Sign-in status |
- {% if perms.hosting.change_customer %}Actions | {% endif %}
+ {% if perms.hosting.change_customer or can_impersonate %}Actions | {% endif %}
@@ -32,18 +32,26 @@
{% if customer.user.is_active %}Active
{% else %}Suspended{% endif %}
- {% if perms.hosting.change_customer %}
+ {% if perms.hosting.change_customer or can_impersonate %}
- {% if not customer.user.is_staff and not customer.user.is_superuser and not customer.user.hosting_reseller %}
-
- {% endif %}
+
+ {% if perms.hosting.change_customer and not customer.user.is_staff and not customer.user.is_superuser and not customer.user.hosting_reseller %}
+
+ {% endif %}
+ {% if can_impersonate and customer.may_be_impersonated %}
+
+ {% endif %}
+
|
{% endif %}
diff --git a/src/coulobre/hosting/templates/hosting/customer_preview_restricted.html b/src/coulobre/hosting/templates/hosting/customer_preview_restricted.html
new file mode 100644
index 0000000..281b606
--- /dev/null
+++ b/src/coulobre/hosting/templates/hosting/customer_preview_restricted.html
@@ -0,0 +1,20 @@
+{% extends "hosting/base.html" %}
+{% block title %}Customer view ยท Coulobre Panel{% endblock %}
+{% block content %}
+
+
+ {% if request.impersonation %}
+
Unavailable in customer view
+
End the customer view to use your administrator account.
+ {% else %}
+
Customer view ended
+
The session expired or access changed.
+ {% endif %}
+
+
+ {% if not request.impersonation and perms.hosting.view_customer %}
+ Back to customers
+ {% else %}
+ Back to hosting accounts
+ {% endif %}
+{% endblock %}
diff --git a/src/coulobre/hosting/templates/hosting/database_form.html b/src/coulobre/hosting/templates/hosting/database_form.html
index c75d694..754419c 100644
--- a/src/coulobre/hosting/templates/hosting/database_form.html
+++ b/src/coulobre/hosting/templates/hosting/database_form.html
@@ -8,7 +8,9 @@
{% csrf_token %}
{{ form.as_div }}
diff --git a/src/coulobre/hosting/templates/hosting/mailbox_form.html b/src/coulobre/hosting/templates/hosting/mailbox_form.html
index 6fba097..9f01cf8 100644
--- a/src/coulobre/hosting/templates/hosting/mailbox_form.html
+++ b/src/coulobre/hosting/templates/hosting/mailbox_form.html
@@ -13,7 +13,9 @@
{% csrf_token %}
{{ form.as_div }}
diff --git a/src/coulobre/hosting/test_impersonation.py b/src/coulobre/hosting/test_impersonation.py
new file mode 100644
index 0000000..60c93e4
--- /dev/null
+++ b/src/coulobre/hosting/test_impersonation.py
@@ -0,0 +1,270 @@
+from datetime import timedelta
+
+from django.conf import settings
+from django.contrib.auth import SESSION_KEY as AUTH_SESSION_KEY
+from django.contrib.auth import get_user_model
+from django.contrib.auth.models import Permission
+from django.test import Client, TestCase
+from django.urls import reverse
+from django.utils import timezone
+
+from .impersonation import SESSION_DURATION, SESSION_KEY
+from .models import (
+ Customer,
+ CustomerImpersonation,
+ HostingAccount,
+ HostingDatabase,
+ HostingMailbox,
+ Reseller,
+)
+
+
+class CustomerImpersonationTests(TestCase):
+ @classmethod
+ def setUpTestData(cls):
+ users = get_user_model().objects
+ cls.operator = users.create_superuser("operator")
+ cls.support = users.create_user("support", is_staff=True)
+ cls.alice = users.create_user("alice")
+ cls.customer = Customer.objects.create(user=cls.alice)
+ cls.account = HostingAccount.objects.create(
+ name="Alice website",
+ primary_domain="alice.example",
+ customer=cls.customer,
+ )
+ cls.other_account = HostingAccount.objects.create(
+ name="Operator website", primary_domain="operator.example"
+ )
+
+ def setUp(self):
+ self.client.force_login(self.operator)
+ self.accounts = reverse("panel:accounts")
+ self.customers = reverse("panel:customers")
+ self.start_url = reverse(
+ "panel:impersonation_start", args=[self.customer.pk]
+ )
+ self.stop_url = reverse("panel:impersonation_stop")
+
+ def grant_support_permissions(self, user, *codenames):
+ user.user_permissions.add(
+ *Permission.objects.filter(
+ content_type__app_label="hosting", codename__in=codenames
+ )
+ )
+
+ def start_preview(self):
+ response = self.client.post(self.start_url)
+ self.assertRedirects(
+ response, self.accounts, fetch_redirect_response=False
+ )
+ self.assertIn("no-store", response.headers["Cache-Control"])
+ return CustomerImpersonation.objects.get(
+ pk=self.client.session[SESSION_KEY]
+ )
+
+ def test_reads_only_customer_accounts_and_keeps_operator_login(self):
+ preview = self.start_preview()
+
+ self.assertEqual(preview.operator, self.operator)
+ self.assertEqual(preview.customer, self.customer)
+ self.assertEqual(preview.operator_username, "operator")
+ self.assertEqual(preview.customer_username, "alice")
+ self.assertEqual(
+ preview.expires_at - preview.started_at, SESSION_DURATION
+ )
+ self.assertEqual(
+ self.client.session[AUTH_SESSION_KEY], str(self.operator.pk)
+ )
+
+ response = self.client.get(self.accounts)
+ self.assertContains(response, "Viewing as alice")
+ self.assertContains(response, "Read-only support session")
+ self.assertContains(response, self.account.name)
+ self.assertNotContains(response, self.other_account.name)
+ self.assertNotContains(response, "Add hosting account")
+ self.assertIn("no-store", response.headers["Cache-Control"])
+ self.assertEqual(response.wsgi_request.user, self.alice)
+ self.assertEqual(
+ self.client.get(self.other_account.get_absolute_url()).status_code,
+ 404,
+ )
+ self.assertContains(
+ self.client.get(self.account.get_absolute_url()),
+ "Request mailbox",
+ )
+
+ another_browser = Client()
+ another_browser.force_login(self.operator)
+ self.assertContains(
+ another_browser.get(self.accounts), self.other_account.name
+ )
+
+ def test_disables_resource_forms_and_rejects_writes(self):
+ self.start_preview()
+ for route, field in (
+ ("panel:database_create", "suffix"),
+ ("panel:mailbox_create", "local_part"),
+ ):
+ with self.subTest(route=route):
+ url = reverse(route, args=[self.account.pk])
+ response = self.client.get(url)
+ self.assertTrue(
+ response.context["form"].fields[field].disabled
+ )
+ self.assertNotContains(response, 'class="button primary"')
+ self.assertContains(
+ self.client.post(url, {field: "support"}),
+ "Unavailable in customer view",
+ status_code=403,
+ )
+ self.assertFalse(HostingDatabase.objects.exists())
+ self.assertFalse(HostingMailbox.objects.exists())
+ for url in (reverse("admin:index"), self.customers, self.start_url):
+ with self.subTest(url=url):
+ method = "post" if url == self.start_url else "get"
+ self.assertContains(
+ getattr(self.client, method)(url),
+ "End customer view",
+ status_code=403,
+ )
+ self.assertEqual(CustomerImpersonation.objects.count(), 1)
+
+ def test_requires_staff_and_the_dedicated_permission(self):
+ self.grant_support_permissions(self.support, "view_customer")
+ self.client.force_login(self.support)
+ self.assertNotContains(
+ self.client.get(self.customers), "View as customer"
+ )
+ self.assertEqual(self.client.post(self.start_url).status_code, 403)
+
+ self.grant_support_permissions(self.support, "impersonate_customer")
+ self.assertContains(
+ self.client.get(self.customers), "View as customer alice"
+ )
+ self.start_preview()
+ self.assertRedirects(self.client.post(self.stop_url), self.customers)
+
+ Reseller.objects.create(user=self.support)
+ self.assertEqual(self.client.post(self.start_url).status_code, 403)
+ users = get_user_model().objects
+ users.filter(pk=self.support.pk).update(is_staff=False)
+ Reseller.objects.filter(user=self.support).delete()
+ self.assertEqual(self.client.post(self.start_url).status_code, 403)
+
+ def test_rejects_suspended_and_privileged_targets(self):
+ for flags in (
+ {"is_active": False},
+ {"is_staff": True},
+ {"is_superuser": True},
+ ):
+ with self.subTest(flags=flags):
+ user = get_user_model().objects.create_user(
+ next(iter(flags)), **flags
+ )
+ customer = Customer.objects.create(user=user)
+ url = reverse("panel:impersonation_start", args=[customer.pk])
+ self.assertEqual(self.client.post(url).status_code, 404)
+
+ Reseller.objects.create(user=self.alice)
+ self.assertEqual(self.client.post(self.start_url).status_code, 404)
+ self.assertFalse(CustomerImpersonation.objects.exists())
+
+ def test_start_and_stop_require_post_with_csrf(self):
+ self.client = Client(enforce_csrf_checks=True)
+ self.client.force_login(self.operator)
+ self.client.get(self.customers)
+ csrf = settings.CSRF_COOKIE_NAME
+ token = self.client.cookies[csrf].value
+ self.assertEqual(self.client.get(self.start_url).status_code, 405)
+ self.assertEqual(self.client.post(self.start_url).status_code, 403)
+ self.assertEqual(
+ self.client.post(
+ self.start_url, HTTP_X_CSRFTOKEN=token
+ ).status_code,
+ 302,
+ )
+ preview_token = self.client.cookies[csrf].value
+ self.assertNotEqual(preview_token, token)
+ self.assertEqual(self.client.get(self.stop_url).status_code, 405)
+ self.assertEqual(self.client.post(self.stop_url).status_code, 403)
+ self.assertEqual(
+ self.client.post(
+ self.stop_url, HTTP_X_CSRFTOKEN=preview_token
+ ).status_code,
+ 302,
+ )
+ self.assertNotEqual(self.client.cookies[csrf].value, preview_token)
+ self.assertNotIn(SESSION_KEY, self.client.session)
+ self.assertContains(
+ self.client.get(self.accounts), self.other_account.name
+ )
+ expired = CustomerImpersonation.objects.get()
+ self.assertEqual(expired.end_reason, expired.EndReason.STOPPED)
+ self.assertIsNotNone(expired.ended_at)
+
+ def test_signing_out_closes_audit_and_operator_session(self):
+ preview = self.start_preview()
+ self.client.post(reverse("panel:logout"))
+
+ preview.refresh_from_db()
+ self.assertEqual(preview.end_reason, preview.EndReason.SIGNED_OUT)
+ self.assertNotIn(AUTH_SESSION_KEY, self.client.session)
+ self.assertNotIn(SESSION_KEY, self.client.session)
+
+ def test_expired_preview_does_not_execute_stale_operator_action(self):
+ preview = self.start_preview()
+ cutoff = timezone.now() - timedelta(seconds=1)
+ CustomerImpersonation.objects.filter(pk=preview.pk).update(
+ expires_at=cutoff
+ )
+
+ response = self.client.post(
+ reverse("panel:customer_access", args=[self.customer.pk]),
+ {"access": "suspend"},
+ )
+
+ self.assertContains(response, "Customer view ended", status_code=409)
+ self.alice.refresh_from_db()
+ self.assertTrue(self.alice.is_active)
+ preview.refresh_from_db()
+ self.assertEqual(preview.end_reason, preview.EndReason.EXPIRED)
+ self.assertEqual(preview.ended_at, cutoff)
+ self.assertNotIn(SESSION_KEY, self.client.session)
+
+ def test_suspending_customer_ends_preview_on_next_request(self):
+ preview = self.start_preview()
+ get_user_model().objects.filter(pk=self.alice.pk).update(
+ is_active=False
+ )
+
+ response = self.client.get(self.accounts)
+ self.assertContains(response, "Customer view ended", status_code=409)
+ self.assertNotContains(response, self.account.name, status_code=409)
+ preview.refresh_from_db()
+ self.assertEqual(preview.end_reason, preview.EndReason.ACCESS_REVOKED)
+
+ def test_revoking_operator_permission_ends_preview_on_next_request(self):
+ self.grant_support_permissions(
+ self.support, "view_customer", "impersonate_customer"
+ )
+ self.client.force_login(self.support)
+ preview = self.start_preview()
+ self.support.user_permissions.clear()
+
+ response = self.client.get(self.accounts)
+ self.assertContains(response, "Customer view ended", status_code=409)
+ preview.refresh_from_db()
+ self.assertEqual(preview.end_reason, preview.EndReason.ACCESS_REVOKED)
+
+ def test_session_marker_cannot_be_used_by_another_operator(self):
+ preview = self.start_preview()
+ other = Client()
+ other.force_login(self.support)
+ session = other.session
+ session[SESSION_KEY] = preview.pk
+ session.save()
+
+ self.assertEqual(other.get(self.accounts).status_code, 409)
+ self.assertNotIn(SESSION_KEY, other.session)
+ preview.refresh_from_db()
+ self.assertIsNone(preview.ended_at)
diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py
index 00ed573..f5664e0 100644
--- a/src/coulobre/hosting/urls.py
+++ b/src/coulobre/hosting/urls.py
@@ -36,6 +36,16 @@ urlpatterns = [
views.CustomerAccess.as_view(),
name="customer_access",
),
+ path(
+ "customers//view-as/",
+ views.CustomerImpersonationStart.as_view(),
+ name="impersonation_start",
+ ),
+ path(
+ "customer-view/end/",
+ views.CustomerImpersonationStop.as_view(),
+ name="impersonation_stop",
+ ),
path(
"accounts//databases/new/",
views.DatabaseCreate.as_view(),
diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py
index 99b020b..4bd0b58 100644
--- a/src/coulobre/hosting/views.py
+++ b/src/coulobre/hosting/views.py
@@ -38,6 +38,12 @@ from .access import (
)
from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record
from .dns_publication import queue_dns_publication
+from .impersonation import (
+ EndReason,
+ can_impersonate_customer,
+ end_impersonation,
+ start_impersonation,
+)
from .models import (
Customer,
DatabaseProvisioning,
@@ -273,7 +279,11 @@ class CustomerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
return queryset
def get_context_data(self, **kwargs):
- return super().get_context_data(search=self.search, **kwargs)
+ return super().get_context_data(
+ search=self.search,
+ can_impersonate=can_impersonate_customer(self.request.user),
+ **kwargs,
+ )
@method_decorator(
@@ -324,6 +334,28 @@ class CustomerAccess(OperatorOnlyMixin, PermissionRequiredMixin, View):
return redirect(reverse("panel:customers", query=request.GET))
+class CustomerImpersonationStart(PermissionRequiredMixin, View):
+ def has_permission(self):
+ return can_impersonate_customer(self.request.user)
+
+ def post(self, request, pk):
+ customers = Customer.objects.select_related("user__hosting_reseller")
+ customer = get_object_or_404(customers, pk=pk)
+ if not customer.may_be_impersonated:
+ raise Http404
+ start_impersonation(request, customer)
+ return redirect("panel:accounts")
+
+
+class CustomerImpersonationStop(View):
+ def post(self, request):
+ session = getattr(request, "impersonation", None)
+ if session is not None:
+ end_impersonation(request, session, EndReason.STOPPED)
+ return redirect("panel:customers")
+ return redirect("panel:accounts")
+
+
class ResourceRequestCreate(PermissionRequiredMixin, CreateView):
@cached_property
def customer(self):
@@ -345,6 +377,13 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView):
def get_context_data(self, **kwargs):
return super().get_context_data(account=self.account, **kwargs)
+ def get_form(self, form_class=None):
+ form = super().get_form(form_class)
+ if getattr(self.request, "impersonation", None) is not None:
+ for field in form.fields.values():
+ field.disabled = True
+ return form
+
def form_valid(self, form):
try:
self.object = self.create_request(
diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py
index d8e65ae..410978a 100644
--- a/src/coulobre/settings.py
+++ b/src/coulobre/settings.py
@@ -43,6 +43,7 @@ MIDDLEWARE = [
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
+ "coulobre.hosting.impersonation.CustomerImpersonationMiddleware",
]
ROOT_URLCONF = "coulobre.urls"