Allow scoped and audited writes during customer support

This commit is contained in:
parkel committed 2026-11-21 23:05:37 +01:00
1 parent 6e73e342ab
commit 930b692328
13 files changed
+378 -62

No files matched your search

+41
View File
@@ -5,6 +5,7 @@ from django.utils.timezone import now
from .models import ( from .models import (
Customer, Customer,
CustomerImpersonation, CustomerImpersonation,
CustomerImpersonationAction,
HostingAccount, HostingAccount,
HostingPlan, HostingPlan,
Reseller, Reseller,
@@ -98,6 +99,7 @@ class CustomerImpersonationAdmin(admin.ModelAdmin):
list_display = ( list_display = (
"operator_username", "operator_username",
"customer_username", "customer_username",
"write_enabled",
"started_at", "started_at",
"expires_at", "expires_at",
"ended_at", "ended_at",
@@ -107,6 +109,7 @@ class CustomerImpersonationAdmin(admin.ModelAdmin):
fields = ( fields = (
"operator_username", "operator_username",
"customer_username", "customer_username",
"write_enabled",
"started_at", "started_at",
"expires_at", "expires_at",
"ended_at", "ended_at",
@@ -132,6 +135,44 @@ class CustomerImpersonationAdmin(admin.ModelAdmin):
return False return False
@admin.register(CustomerImpersonationAction)
class CustomerImpersonationActionAdmin(admin.ModelAdmin):
list_display = (
"requested_at",
"operator_username",
"customer_username",
"hosting_account_id",
"operation",
"resource",
)
list_select_related = ("session",)
list_filter = ("operation",)
search_fields = (
"session__operator_username",
"session__customer_username",
"resource",
)
fields = list_display + ("session", "details")
readonly_fields = fields
@admin.display(description="Administrator")
def operator_username(self, obj):
return obj.session.operator_username
@admin.display(description="Customer")
def customer_username(self, obj):
return obj.session.customer_username
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
@admin.register(ServiceCredentialAccess) @admin.register(ServiceCredentialAccess)
class ServiceCredentialAccessAdmin(admin.ModelAdmin): class ServiceCredentialAccessAdmin(admin.ModelAdmin):
list_display = ( list_display = (
+101 -11
View File
@@ -1,5 +1,9 @@
from contextlib import contextmanager
from datetime import timedelta from datetime import timedelta
from django.core.exceptions import PermissionDenied
from django.db import connection, transaction
from django.db.models import F
from django.middleware.csrf import rotate_token from django.middleware.csrf import rotate_token
from django.shortcuts import render from django.shortcuts import render
from django.utils import timezone from django.utils import timezone
@@ -7,6 +11,7 @@ from django.utils.cache import add_never_cache_headers
from .access import is_tenant from .access import is_tenant
from .models import CustomerImpersonation from .models import CustomerImpersonation
from .sftp import MANAGE_SFTP_KEYS
SESSION_KEY = "customer_impersonation" SESSION_KEY = "customer_impersonation"
SESSION_DURATION = timedelta(minutes=30) SESSION_DURATION = timedelta(minutes=30)
@@ -14,16 +19,27 @@ IMPERSONATE_CUSTOMER = (
"hosting.view_customer", "hosting.view_customer",
"hosting.impersonate_customer", "hosting.impersonate_customer",
) )
WRITE_AS_CUSTOMER = "hosting.write_as_customer"
CUSTOMER_WRITE_PERMISSIONS = {
"panel:database_create": (
"hosting.view_hostingaccount",
"hosting.view_hostingdatabase",
"hosting.add_hostingdatabase",
),
"panel:mailbox_create": (
"hosting.view_hostingaccount",
"hosting.view_hostingmailbox",
"hosting.add_hostingmailbox",
),
"panel:sftp_keys": MANAGE_SFTP_KEYS,
}
PREVIEW_VIEWS = frozenset( PREVIEW_VIEWS = frozenset(
{ {
"panel:accounts", "panel:accounts",
"panel:account", "panel:account",
"panel:database_create",
"panel:mailbox_create",
"panel:mail_dns_check", "panel:mail_dns_check",
"panel:sftp_keys",
} }
) ) | frozenset(CUSTOMER_WRITE_PERMISSIONS)
EndReason = CustomerImpersonation.EndReason EndReason = CustomerImpersonation.EndReason
@@ -37,13 +53,78 @@ def can_impersonate_customer(user):
) )
def start_impersonation(request, customer): def can_start_writable_support(user):
return can_impersonate_customer(user) and user.has_perm(WRITE_AS_CUSTOMER)
def can_edit_customer_resource(request):
session = getattr(request, "impersonation", None)
if session is None:
return True
permissions = CUSTOMER_WRITE_PERMISSIONS.get(
request.resolver_match.view_name
)
return (
session.write_enabled
and permissions is not None
and request.support_operator.has_perms(permissions)
)
def lock_session(sessions):
if connection.vendor == "sqlite":
# Take the write lock before reading the session on SQLite.
sessions.update(write_enabled=F("write_enabled"))
return sessions.select_for_update().first()
@contextmanager
def support_write_session(request):
session = getattr(request, "impersonation", None)
submitted_session = request.POST.get("support_session")
if session is None:
if submitted_session is not None:
raise PermissionDenied
yield None
return
if str(session.pk) != submitted_session or not can_edit_customer_resource(
request
):
raise PermissionDenied
with transaction.atomic():
sessions = CustomerImpersonation.objects.filter(
pk=session.pk,
operator_id=request.support_operator.pk,
customer_id=session.customer_id,
ended_at__isnull=True,
write_enabled=True,
)
current = lock_session(sessions)
permissions = CUSTOMER_WRITE_PERMISSIONS[
request.resolver_match.view_name
]
if (
current is None
or current.expires_at <= timezone.now()
or current.customer is None
or current.customer.user_id != request.user.pk
or not current.customer.may_be_impersonated
or not can_start_writable_support(current.operator)
or not current.operator.has_perms(permissions)
):
raise PermissionDenied
yield current
def start_impersonation(request, customer, *, write_enabled=False):
now = timezone.now() now = timezone.now()
session = CustomerImpersonation.objects.create( session = CustomerImpersonation.objects.create(
operator=request.user, operator=request.user,
customer=customer, customer=customer,
operator_username=request.user.get_username(), operator_username=request.user.get_username(),
customer_username=customer.user.get_username(), customer_username=customer.user.get_username(),
write_enabled=write_enabled,
started_at=now, started_at=now,
expires_at=now + SESSION_DURATION, expires_at=now + SESSION_DURATION,
) )
@@ -53,12 +134,16 @@ def start_impersonation(request, customer):
def end_impersonation(request, session, reason): def end_impersonation(request, session, reason):
if session is not None: if session is not None:
CustomerImpersonation.objects.filter( with transaction.atomic():
pk=session.pk, ended_at__isnull=True sessions = CustomerImpersonation.objects.filter(
).update( pk=session.pk, ended_at__isnull=True
ended_at=min(timezone.now(), session.expires_at), )
end_reason=reason, current = lock_session(sessions)
) if current is not None:
sessions.update(
ended_at=min(timezone.now(), current.expires_at),
end_reason=reason,
)
request.session.pop(SESSION_KEY, None) request.session.pop(SESSION_KEY, None)
rotate_token(request) rotate_token(request)
@@ -98,6 +183,8 @@ class CustomerImpersonationMiddleware:
reason = EndReason.EXPIRED reason = EndReason.EXPIRED
elif ( elif (
not can_impersonate_customer(request.user) not can_impersonate_customer(request.user)
or session.write_enabled
and not request.user.has_perm(WRITE_AS_CUSTOMER)
or session.customer is None or session.customer is None
or not session.customer.may_be_impersonated or not session.customer.may_be_impersonated
): ):
@@ -116,6 +203,7 @@ class CustomerImpersonationMiddleware:
) )
request.impersonation = session request.impersonation = session
request.support_operator = request.user
if view_name == "panel:impersonation_stop": if view_name == "panel:impersonation_stop":
return None return None
@@ -126,6 +214,8 @@ class CustomerImpersonationMiddleware:
request.auser = preview_user request.auser = preview_user
if request.method in ("GET", "HEAD") and view_name in PREVIEW_VIEWS: if request.method in ("GET", "HEAD") and view_name in PREVIEW_VIEWS:
return None return None
if request.method == "POST" and can_edit_customer_resource(request):
return None
return render( return render(
request, "hosting/customer_preview_restricted.html", status=403 request, "hosting/customer_preview_restricted.html", status=403
) )
@@ -0,0 +1,84 @@
# Generated by Django 5.2.19 on 2026-11-21 22:01
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0040_remote_mail_archives"),
]
operations = [
migrations.AlterModelOptions(
name="customerimpersonation",
options={
"default_permissions": ("view",),
"ordering": ("-started_at", "-pk"),
"permissions": (
(
"impersonate_customer",
"Can view the panel as a customer",
),
(
"write_as_customer",
"Can start a support session with write access",
),
),
"verbose_name": "customer impersonation session",
},
),
migrations.AddField(
model_name="customerimpersonation",
name="write_enabled",
field=models.BooleanField(default=False),
),
migrations.CreateModel(
name="CustomerImpersonationAction",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("hosting_account_id", models.PositiveBigIntegerField()),
(
"operation",
models.CharField(
choices=[
("database", "Requested database"),
("mailbox", "Requested mailbox"),
("add_keys", "Queued SSH key upload"),
("remove_key", "Queued SSH key removal"),
("revoke_sftp", "Queued SFTP revocation"),
],
max_length=16,
),
),
("resource", models.CharField(max_length=254)),
("details", models.JSONField(default=dict)),
(
"requested_at",
models.DateTimeField(default=django.utils.timezone.now),
),
(
"session",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="actions",
to="hosting.customerimpersonation",
),
),
],
options={
"verbose_name": "customer impersonation action",
"ordering": ("-requested_at", "-pk"),
"default_permissions": ("view",),
},
),
]
+28
View File
@@ -137,6 +137,7 @@ class CustomerImpersonation(models.Model):
) )
operator_username = models.CharField(max_length=150) operator_username = models.CharField(max_length=150)
customer_username = models.CharField(max_length=150) customer_username = models.CharField(max_length=150)
write_enabled = models.BooleanField(default=False)
started_at = models.DateTimeField(default=timezone.now) started_at = models.DateTimeField(default=timezone.now)
expires_at = models.DateTimeField() expires_at = models.DateTimeField()
ended_at = models.DateTimeField(null=True, blank=True) ended_at = models.DateTimeField(null=True, blank=True)
@@ -150,12 +151,39 @@ class CustomerImpersonation(models.Model):
verbose_name = "customer impersonation session" verbose_name = "customer impersonation session"
permissions = ( permissions = (
("impersonate_customer", "Can view the panel as a customer"), ("impersonate_customer", "Can view the panel as a customer"),
(
"write_as_customer",
"Can start a support session with write access",
),
) )
def __str__(self): def __str__(self):
return f"{self.operator_username} viewing as {self.customer_username}" return f"{self.operator_username} viewing as {self.customer_username}"
class CustomerImpersonationAction(models.Model):
class Operation(models.TextChoices):
DATABASE = "database", "Requested database"
MAILBOX = "mailbox", "Requested mailbox"
ADD_KEYS = "add_keys", "Queued SSH key upload"
REMOVE_KEY = "remove_key", "Queued SSH key removal"
REVOKE_SFTP = "revoke_sftp", "Queued SFTP revocation"
session = models.ForeignKey(
CustomerImpersonation, on_delete=models.PROTECT, related_name="actions"
)
hosting_account_id = models.PositiveBigIntegerField()
operation = models.CharField(max_length=16, choices=Operation.choices)
resource = models.CharField(max_length=254)
details = models.JSONField(default=dict)
requested_at = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ("-requested_at", "-pk")
default_permissions = ("view",)
verbose_name = "customer impersonation action"
class ServiceCredentialAccess(models.Model): class ServiceCredentialAccess(models.Model):
class Kind(models.TextChoices): class Kind(models.TextChoices):
DATABASE = "database", "MariaDB database" DATABASE = "database", "MariaDB database"
+31 -16
View File
@@ -1,3 +1,5 @@
from dataclasses import dataclass
from django import forms from django import forms
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.db import transaction from django.db import transaction
@@ -12,13 +14,19 @@ from .access import customer_for_user, is_tenant
from .models import SiteSFTP from .models import SiteSFTP
from .resource_requests import lock_hosting_account, require_open_account from .resource_requests import lock_hosting_account, require_open_account
MANAGE_SFTP_KEYS = ("hosting.view_hostingaccount", "hosting.change_sitesftp")
@dataclass(frozen=True)
class SFTPKeyChange:
domain: str
added: list[str]
removed: list[str]
def can_manage_sftp(user): def can_manage_sftp(user):
return customer_for_user(user) is not None or ( return customer_for_user(user) is not None or (
not is_tenant(user) not is_tenant(user) and user.has_perms(MANAGE_SFTP_KEYS)
and user.has_perms(
("hosting.view_hostingaccount", "hosting.change_sitesftp")
)
) )
@@ -54,21 +62,28 @@ def queue_sftp_keys(
} }
if request is None: if request is None:
SiteSFTP.objects.create(account=account, **updates) SiteSFTP.objects.create(account=account, **updates)
return else:
same_keys = ( same_keys = (
request.domain == updates["domain"] request.domain == updates["domain"]
and request.public_keys == keys and request.public_keys == keys
and request.requested_customer_id == customer_id and request.requested_customer_id == customer_id
) )
if request.finished_at is None: if request.finished_at is None:
if not same_keys: if not same_keys:
raise ValidationError( raise ValidationError(
"Wait for the current SFTP key request to finish." "Wait for the current SFTP key request to finish."
) )
elif not same_keys or request.problem: return
if same_keys and not request.problem:
return
SiteSFTP.objects.requeue( SiteSFTP.objects.requeue(
SiteSFTP.objects.filter(pk=request.pk), **updates SiteSFTP.objects.filter(pk=request.pk), **updates
) )
before = {public_key_fingerprint(key) for key in previous.splitlines()}
after = {public_key_fingerprint(key) for key in keys.splitlines()}
return SFTPKeyChange(
updates["domain"], sorted(after - before), sorted(before - after)
)
def change_key_list(previous, operation, public_keys, fingerprint): def change_key_list(previous, operation, public_keys, fingerprint):
@@ -68,7 +68,11 @@
<section class="notice customer-preview" aria-label="Customer view"> <section class="notice customer-preview" aria-label="Customer view">
<div> <div>
<strong>Viewing as {{ request.impersonation.customer }}</strong> <strong>Viewing as {{ request.impersonation.customer }}</strong>
<p>Read-only support session</p> {% if request.impersonation.write_enabled %}
<p>Support session with write access · {{ request.impersonation.operator_username }}</p>
{% else %}
<p>Read-only support session</p>
{% endif %}
</div> </div>
<form method="post" action="{% url 'panel:impersonation_stop' %}"> <form method="post" action="{% url 'panel:impersonation_stop' %}">
{% csrf_token %} {% csrf_token %}
@@ -0,0 +1,5 @@
{% load l10n %}
{% csrf_token %}
{% if request.impersonation.write_enabled %}
<input type="hidden" name="support_session" value="{{ request.impersonation.pk|unlocalize }}">
{% endif %}
@@ -50,6 +50,12 @@
{% csrf_token %} {% csrf_token %}
<button class="button secondary" type="submit" aria-label="View as customer {{ customer }}">View as customer</button> <button class="button secondary" type="submit" aria-label="View as customer {{ customer }}">View as customer</button>
</form> </form>
{% if can_start_support %}
<form method="post" action="{% url 'panel:impersonation_write_start' customer.pk %}">
{% csrf_token %}
<button class="button secondary" type="submit" aria-label="Start support with write access for {{ customer }}">Support with write access</button>
</form>
{% endif %}
{% endif %} {% endif %}
</div> </div>
</td> </td>
@@ -5,10 +5,10 @@
<header class="page-heading"><h1>Request MariaDB database</h1></header> <header class="page-heading"><h1>Request MariaDB database</h1></header>
<section class="surface editor-surface"> <section class="surface editor-surface">
<form method="post" class="editor"> <form method="post" class="editor">
{% csrf_token %} {% include "hosting/customer_action_fields.html" %}
{{ form.as_div }} {{ form.as_div }}
<div class="form-actions"> <div class="form-actions">
{% if not request.impersonation %} {% if can_request_resource %}
<button class="button primary" type="submit">Request database</button> <button class="button primary" type="submit">Request database</button>
{% endif %} {% endif %}
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a> <a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
@@ -10,10 +10,10 @@
</header> </header>
<section class="surface editor-surface"> <section class="surface editor-surface">
<form method="post" class="editor"> <form method="post" class="editor">
{% csrf_token %} {% include "hosting/customer_action_fields.html" %}
{{ form.as_div }} {{ form.as_div }}
<div class="form-actions"> <div class="form-actions">
{% if not request.impersonation %} {% if can_request_resource %}
<button class="button primary" type="submit">Request mailbox</button> <button class="button primary" type="submit">Request mailbox</button>
{% endif %} {% endif %}
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a> <a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
@@ -62,7 +62,7 @@
{% if can_edit_keys %} {% if can_edit_keys %}
<td> <td>
<form method="post"> <form method="post">
{% csrf_token %} {% include "hosting/customer_action_fields.html" %}
<input type="hidden" name="fingerprint" value="{{ fingerprint }}"> <input type="hidden" name="fingerprint" value="{{ fingerprint }}">
<button class="button secondary" type="submit" name="operation" value="remove" aria-label="Remove SSH key {{ fingerprint }}">Remove key</button> <button class="button secondary" type="submit" name="operation" value="remove" aria-label="Remove SSH key {{ fingerprint }}">Remove key</button>
</form> </form>
@@ -78,7 +78,7 @@
{% if can_edit_keys or can_revoke_keys %} {% if can_edit_keys or can_revoke_keys %}
<section class="surface editor-surface" aria-label="SSH key management"> <section class="surface editor-surface" aria-label="SSH key management">
<form class="editor" method="post" enctype="multipart/form-data"> <form class="editor" method="post" enctype="multipart/form-data">
{% csrf_token %} {% include "hosting/customer_action_fields.html" %}
{% if can_edit_keys %} {% if can_edit_keys %}
{{ form.public_keys.as_field_group }} {{ form.public_keys.as_field_group }}
{% endif %} {% endif %}
+5
View File
@@ -156,6 +156,11 @@ urlpatterns = [
views.CustomerImpersonationStart.as_view(), views.CustomerImpersonationStart.as_view(),
name="impersonation_start", name="impersonation_start",
), ),
path(
"customers/<int:pk>/support/",
views.CustomerImpersonationStart.as_view(write_enabled=True),
name="impersonation_write_start",
),
path( path(
"customer-view/end/", "customer-view/end/",
views.CustomerImpersonationStop.as_view(), views.CustomerImpersonationStop.as_view(),
+66 -28
View File
@@ -68,16 +68,21 @@ from .backup_retention import change_backup_retention, protect_backup
from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record
from .dns_publication import queue_dns_publication from .dns_publication import queue_dns_publication
from .impersonation import ( from .impersonation import (
CUSTOMER_WRITE_PERMISSIONS,
EndReason, EndReason,
can_edit_customer_resource,
can_impersonate_customer, can_impersonate_customer,
can_start_writable_support,
end_impersonation, end_impersonation,
start_impersonation, start_impersonation,
support_write_session,
) )
from .models import ( from .models import (
AccountBackupJob, AccountBackupJob,
AccountBackupSchedule, AccountBackupSchedule,
ComponentRestoreJob, ComponentRestoreJob,
Customer, Customer,
CustomerImpersonationAction,
HostingAccount, HostingAccount,
HostingDatabase, HostingDatabase,
HostingDnsZone, HostingDnsZone,
@@ -1209,7 +1214,7 @@ class SiteSFTPKeys(PermissionRequiredMixin, FormView):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
status = getattr(self.account, "sftp", None) status = getattr(self.account, "sftp", None)
editable = getattr(self.request, "impersonation", None) is None editable = can_edit_customer_resource(self.request)
idle = status is None or status.finished_at is not None idle = status is None or status.finished_at is not None
keys = () if status is None else status.public_keys.splitlines() keys = () if status is None else status.public_keys.splitlines()
return super().get_context_data( return super().get_context_data(
@@ -1231,14 +1236,32 @@ class SiteSFTPKeys(PermissionRequiredMixin, FormView):
def form_valid(self, form): def form_valid(self, form):
customer = customer_for_user(self.request.user) customer = customer_for_user(self.request.user)
operation = form.cleaned_data["operation"]
try: try:
queue_sftp_keys( with support_write_session(self.request) as session:
self.account.pk, change = queue_sftp_keys(
form.cleaned_data["operation"], self.account.pk,
public_keys=form.cleaned_data["public_keys"], operation,
fingerprint=form.cleaned_data["fingerprint"], public_keys=form.cleaned_data["public_keys"],
customer_id=customer.pk if customer is not None else None, fingerprint=form.cleaned_data["fingerprint"],
) customer_id=customer.pk if customer is not None else None,
)
if session is not None and change is not None:
operations = CustomerImpersonationAction.Operation
CustomerImpersonationAction.objects.create(
session=session,
hosting_account_id=self.account.pk,
operation={
"add": operations.ADD_KEYS,
"remove": operations.REMOVE_KEY,
"revoke": operations.REVOKE_SFTP,
}[operation],
resource=change.domain,
details={
"added": change.added,
"removed": change.removed,
},
)
except HostingAccount.DoesNotExist as error: except HostingAccount.DoesNotExist as error:
raise Http404 from error raise Http404 from error
except ValidationError as error: except ValidationError as error:
@@ -1269,6 +1292,7 @@ class CustomerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
return super().get_context_data( return super().get_context_data(
search=self.search, search=self.search,
can_impersonate=can_impersonate_customer(self.request.user), can_impersonate=can_impersonate_customer(self.request.user),
can_start_support=can_start_writable_support(self.request.user),
**kwargs, **kwargs,
) )
@@ -1322,7 +1346,11 @@ class CustomerAccess(OperatorOnlyMixin, PermissionRequiredMixin, View):
class CustomerImpersonationStart(PermissionRequiredMixin, View): class CustomerImpersonationStart(PermissionRequiredMixin, View):
write_enabled = False
def has_permission(self): def has_permission(self):
if self.write_enabled:
return can_start_writable_support(self.request.user)
return can_impersonate_customer(self.request.user) return can_impersonate_customer(self.request.user)
def post(self, request, pk): def post(self, request, pk):
@@ -1330,7 +1358,9 @@ class CustomerImpersonationStart(PermissionRequiredMixin, View):
customer = get_object_or_404(customers, pk=pk) customer = get_object_or_404(customers, pk=pk)
if not customer.may_be_impersonated: if not customer.may_be_impersonated:
raise Http404 raise Http404
start_impersonation(request, customer) start_impersonation(
request, customer, write_enabled=self.write_enabled
)
return redirect("panel:accounts") return redirect("panel:accounts")
@@ -1372,6 +1402,8 @@ def provisioning_conflict(error):
class ResourceRequestCreate(PermissionRequiredMixin, CreateView): class ResourceRequestCreate(PermissionRequiredMixin, CreateView):
audit_operation = None
@cached_property @cached_property
def customer(self): def customer(self):
return customer_for_user(self.request.user) return customer_for_user(self.request.user)
@@ -1390,24 +1422,36 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView):
return get_object_or_404(accounts, pk=self.kwargs["pk"]) return get_object_or_404(accounts, pk=self.kwargs["pk"])
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
return super().get_context_data(account=self.account, **kwargs) return super().get_context_data(
account=self.account,
can_request_resource=can_edit_customer_resource(self.request),
**kwargs,
)
def get_form(self, form_class=None): def get_form(self, form_class=None):
form = super().get_form(form_class) form = super().get_form(form_class)
if getattr(self.request, "impersonation", None) is not None: if not can_edit_customer_resource(self.request):
for field in form.fields.values(): for field in form.fields.values():
field.disabled = True field.disabled = True
return form return form
def form_valid(self, form): def form_valid(self, form):
try: try:
self.object = self.create_request( with support_write_session(self.request) as session:
self.account.pk, self.object = self.create_request(
**form.cleaned_data, self.account.pk,
customer_id=self.customer.pk **form.cleaned_data,
if self.customer is not None customer_id=self.customer.pk
else None, if self.customer is not None
) else None,
)
if session is not None:
CustomerImpersonationAction.objects.create(
session=session,
hosting_account_id=self.account.pk,
operation=self.audit_operation,
resource=str(self.object),
)
except HostingAccount.DoesNotExist as error: except HostingAccount.DoesNotExist as error:
raise Http404 from error raise Http404 from error
except ValidationError as error: except ValidationError as error:
@@ -1420,11 +1464,8 @@ class DatabaseCreate(ResourceRequestCreate):
model = HostingDatabase model = HostingDatabase
fields = ("suffix",) fields = ("suffix",)
template_name = "hosting/database_form.html" template_name = "hosting/database_form.html"
permission_required = ( permission_required = CUSTOMER_WRITE_PERMISSIONS["panel:database_create"]
VIEW_ACCOUNTS, audit_operation = CustomerImpersonationAction.Operation.DATABASE
VIEW_DATABASES,
"hosting.add_hostingdatabase",
)
create_request = staticmethod(create_database_request) create_request = staticmethod(create_database_request)
@@ -1642,11 +1683,8 @@ class MailboxCreate(ResourceRequestCreate):
model = HostingMailbox model = HostingMailbox
fields = ("local_part",) fields = ("local_part",)
template_name = "hosting/mailbox_form.html" template_name = "hosting/mailbox_form.html"
permission_required = ( permission_required = CUSTOMER_WRITE_PERMISSIONS["panel:mailbox_create"]
VIEW_ACCOUNTS, audit_operation = CustomerImpersonationAction.Operation.MAILBOX
VIEW_MAILBOXES,
"hosting.add_hostingmailbox",
)
create_request = staticmethod(create_mailbox_request) create_request = staticmethod(create_mailbox_request)
def get_form(self, form_class=None): def get_form(self, form_class=None):