Restore and extend operator customer impersonation #309

Merged
parkel merged 2 commits from fix/operator-impersonation into main 2026-12-04 15:20:47 +01:00
36 changed files with 720 additions and 126 deletions

No files matched your search

+37 -11
View File
@@ -109,12 +109,13 @@ requires password confirmation for each reveal.
## View the panel as a customer ## View the panel as a customer
In **Customers**, select **View as customer** next to an active customer. In the operator workspace, open **Show All Users** and select **Sign in as
The panel shows the customer's assigned hosting accounts and resource pages. customer** next to an eligible customer. The panel shows the customer's
Request forms are visible with their inputs disabled. The banner identifies assigned hosting accounts and supported resource pages. Request forms are
the customer and offers **End customer view**. Ending the view returns you visible with their inputs disabled. The banner identifies the customer and
to your administrator account. Signing out ends the view and signs you out the session mode. Select **Leave impersonation** below the sidebar account
of the panel. name, in place of the workspace switcher, to return to **All users** without
signing out. Signing out ends both sessions.
A support session lasts up to 30 minutes and applies to the current browser A support session lasts up to 30 minutes and applies to the current browser
session. The panel checks that both users remain eligible on each request. session. The panel checks that both users remain eligible on each request.
@@ -123,16 +124,41 @@ permission ends the view on the next request.
A staff user needs both **Can view customer** and **Can view the panel as a A staff user needs both **Can view customer** and **Can view the panel as a
customer**. The second permission is listed under **Customer impersonation customer**. The second permission is listed under **Customer impersonation
sessions**. In `/admin/`, users with **Can view customer impersonation sessions**. Manager and Customer workspaces cannot start impersonation.
Managers can use **Manage hosting** and **Contact and invitation** in
**My users** for their assigned customers without changing identity.
In `/admin/`, users with **Can view customer impersonation
session** can review the administrator, customer, timestamps, and outcome session** can review the administrator, customer, timestamps, and outcome
for each session. The audit records are read-only in Django admin. for each session. The audit records are read-only in Django admin.
### Make changes during a support session ### Manage hosting on behalf of a customer
Grant **Can manage hosting as a customer** under **Customer impersonation
sessions**, in addition to the two customer view permissions. In the operator
workspace, open **Show All Users** and select **Manage as customer**. You can
use the customer's hosting tools for their assigned accounts, with the same
feature availability and package limits as the customer. This includes website
management, DNS, email, databases, SFTP, and backups where enabled.
The operator remains signed in. The support banner and **Leave impersonation**
stay available while managing hosting. Personal account settings, sign-in
credentials, MFA, existing service credential reveals, and SSO are not
delegated. Service password rotation, where enabled, requires the operator's
own password and the normal service credential permissions.
Managed hosting submissions are audited with the operator and customer
session, route, HTTP outcome, and numeric resource identifiers when available.
The audit does not include form values or credentials. A queued submission's
HTTP outcome is not its eventual execution result.
### Make limited changes during a support session
Grant **Can start a support session with write access** in addition to the Grant **Can start a support session with write access** in addition to the
two customer view permissions. Select **Support with write access** next two customer view permissions. In the operator workspace, open the legacy
to the customer. The banner identifies the active customer, administrator, customer list at `/customers/` and select **Support with write access**
and mode. next to the customer. The banner identifies the active customer,
administrator, and mode. **Sign in as customer** in **All users** still
starts a read-only session.
In a writable session, the administrator can request a database or mailbox In a writable session, the administrator can request a database or mailbox
and manage SSH keys on the customer's hosting accounts. Each action also and manage SSH keys on the customer's hosting accounts. Each action also
+7
View File
@@ -103,6 +103,13 @@ heading, help, fields, and actions should share a left edge.
action that opens a form, confirmation page, or download is still an action that opens a form, confirmation page, or download is still an
`<a href>` styled as a button. An action that submits the change uses a `<a href>` styled as a button. An action that submits the change uses a
native `<button type="submit">` in its existing POST form. native `<button type="submit">` in its existing POST form.
- Show only actions available in the active workspace. For example, give
eligible operators **Sign in as customer** for a read-only preview and
**Manage as customer** for delegated hosting work. Give managers direct
actions for assigned hosting and invitations without impersonation.
- During impersonation, identify the customer and session mode in a
persistent banner. Replace the sidebar workspace switcher with **Leave
impersonation**, and keep it available when mobile navigation is closed.
### Checkboxes and radio choices ### Checkboxes and radio choices
+6 -4
View File
@@ -58,13 +58,15 @@ def owns_customer_operations(user, account):
def panel_access(request): def panel_access(request):
from .impersonation import restricted_preview
customer = customer_for_user(request.user) is not None customer = customer_for_user(request.user) is not None
reseller = not customer and reseller_for_user(request.user) is not None reseller = not customer and reseller_for_user(request.user) is not None
from .mailbox_imports import PERMISSIONS as IMPORT_PERMISSIONS from .mailbox_imports import PERMISSIONS as IMPORT_PERMISSIONS
from .mailbox_imports import available as mailbox_import_available from .mailbox_imports import available as mailbox_import_available
from .workspaces import ( from .workspaces import (
CUSTOMER_ACCOUNT,
active_navigation, active_navigation,
customer_account_key,
groups_for, groups_for,
workspace_accounts, workspace_accounts,
) )
@@ -80,9 +82,9 @@ def panel_access(request):
), ),
"", "",
) )
selected = request.session.get(CUSTOMER_ACCOUNT) selected = request.session.get(customer_account_key(request))
available = [] available = []
if customer and not getattr(request, "impersonation", None): if customer and not restricted_preview(request):
available = list( available = list(
workspace_accounts(request.user) workspace_accounts(request.user)
.only("id", "primary_domain") .only("id", "primary_domain")
@@ -102,7 +104,7 @@ def panel_access(request):
"workspace_selected": selected, "workspace_selected": selected,
"mailbox_import_enabled": ( "mailbox_import_enabled": (
mailbox_import_available() mailbox_import_available()
and not getattr(request, "impersonation", None) and not restricted_preview(request)
and can_manage_hosting(request.user, IMPORT_PERMISSIONS) and can_manage_hosting(request.user, IMPORT_PERMISSIONS)
), ),
} }
+11 -1
View File
@@ -25,6 +25,10 @@ from .access import OperatorOnlyMixin, reseller_for_user
from .account_metrics import customer_metrics from .account_metrics import customer_metrics
from .account_setup import setup_new_account from .account_setup import setup_new_account
from .dns_defaults import zone_defaults from .dns_defaults import zone_defaults
from .impersonation import (
can_impersonate_customer,
can_start_managed_support,
)
from .installation_features import ( from .installation_features import (
default_dns_zones_allowed, default_dns_zones_allowed,
panel_feature_allowed, panel_feature_allowed,
@@ -366,11 +370,16 @@ class AllUsersView(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
operator=self.request.user, operator=self.request.user,
) )
actor = self.request.user actor = self.request.user
may_impersonate = can_impersonate_customer(actor)
context["may_manage_as_customer"] = can_start_managed_support(actor)
context["login_rows"] = [ context["login_rows"] = [
( (
login, login,
measurements.get(profile.pk) if profile else None, measurements.get(profile.pk) if profile else None,
deletable_profile(actor, login) is not None, deletable_profile(actor, login) is not None,
may_impersonate
and profile is not None
and profile.may_be_impersonated,
) )
for login, profile in zip(context["logins"], profiles, strict=True) for login, profile in zip(context["logins"], profiles, strict=True)
] ]
@@ -378,7 +387,8 @@ class AllUsersView(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
"hosting.change_customer" "hosting.change_customer"
) or actor.has_perm("hosting.change_reseller") ) or actor.has_perm("hosting.change_reseller")
context["has_user_actions"] = context["may_manage_invitations"] or any( context["has_user_actions"] = context["may_manage_invitations"] or any(
row[2] for row in context["login_rows"] may_delete or may_view
for _, _, may_delete, may_view in context["login_rows"]
) )
return context return context
+2
View File
@@ -116,6 +116,7 @@ class CustomerImpersonationAdmin(admin.ModelAdmin):
"operator_username", "operator_username",
"customer_username", "customer_username",
"write_enabled", "write_enabled",
"managed_enabled",
"started_at", "started_at",
"expires_at", "expires_at",
"ended_at", "ended_at",
@@ -126,6 +127,7 @@ class CustomerImpersonationAdmin(admin.ModelAdmin):
"operator_username", "operator_username",
"customer_username", "customer_username",
"write_enabled", "write_enabled",
"managed_enabled",
"started_at", "started_at",
"expires_at", "expires_at",
"ended_at", "ended_at",
+11 -14
View File
@@ -31,7 +31,7 @@ from .service_credentials import (
CredentialMethod, CredentialMethod,
CredentialOutcome, CredentialOutcome,
can_reveal_credentials, can_reveal_credentials,
can_rotate_credentials, credential_actor,
enabled_credential_access, enabled_credential_access,
enabled_rotation, enabled_rotation,
fetch_service_credentials, fetch_service_credentials,
@@ -39,6 +39,7 @@ from .service_credentials import (
reserve_rotation, reserve_rotation,
rotation_history, rotation_history,
rotation_ticket, rotation_ticket,
show_rotation_action,
verify_credential_access, verify_credential_access,
) )
@@ -59,7 +60,7 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView):
def dispatch(self, request, *args, **kwargs): def dispatch(self, request, *args, **kwargs):
if not self.access_enabled(request): if not self.access_enabled(request):
raise Http404 raise Http404
if getattr(request, "impersonation", None) is not None: if not self.rotating and getattr(request, "impersonation", None):
return self.handle_no_permission() return self.handle_no_permission()
return super().dispatch(request, *args, **kwargs) return super().dispatch(request, *args, **kwargs)
@@ -75,10 +76,9 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView):
return response return response
def has_permission(self): def has_permission(self):
check = ( if self.rotating:
can_rotate_credentials if self.rotating else can_reveal_credentials return show_rotation_action(self.request, self.kind)
) return can_reveal_credentials(self.request.user, self.kind)
return check(self.request.user, self.kind)
def get_form_class(self): def get_form_class(self):
if self.rotating: if self.rotating:
@@ -98,7 +98,7 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView):
self.check_rotation_resource(self.resource, self.account) self.check_rotation_resource(self.resource, self.account)
form = self.get_form() form = self.get_form()
form.initial["ticket"] = rotation_ticket( form.initial["ticket"] = rotation_ticket(
self.resource, self.account.pk, request.user.pk self.resource, self.account.pk, credential_actor(request).pk
) )
except ValidationError as error: except ValidationError as error:
return self.rotation_problem(" ".join(error.messages), status=409) return self.rotation_problem(" ".join(error.messages), status=409)
@@ -128,11 +128,7 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView):
database=self.kind == CredentialKind.DATABASE, database=self.kind == CredentialKind.DATABASE,
**kwargs, **kwargs,
) )
if ( if not self.rotating and show_rotation_action(self.request, self.kind):
not self.rotating
and enabled_rotation(self.request, self.kind)
and can_rotate_credentials(self.request.user, self.kind)
):
context["rotation_url"] = reverse( context["rotation_url"] = reverse(
f"panel:{self.kind}_credential_rotation", f"panel:{self.kind}_credential_rotation",
args=[self.resource.pk], args=[self.resource.pk],
@@ -149,6 +145,7 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView):
@sensitive_variables() @sensitive_variables()
def form_valid(self, form): def form_valid(self, form):
actor = credential_actor(self.request)
rotation = None rotation = None
if self.rotating: if self.rotating:
try: try:
@@ -156,7 +153,7 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView):
form.cleaned_data["ticket"], form.cleaned_data["ticket"],
self.resource, self.resource,
self.account.pk, self.account.pk,
self.request.user, actor,
) )
except (BadSignature, ValueError): except (BadSignature, ValueError):
return self.rotation_problem( return self.rotation_problem(
@@ -164,7 +161,7 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView):
status=409, status=409,
) )
event = verify_credential_access( event = verify_credential_access(
self.request.user, actor,
form.cleaned_data["password"], form.cleaned_data["password"],
kind=self.kind, kind=self.kind,
resource=str(self.resource), resource=str(self.resource),
+2 -1
View File
@@ -15,6 +15,7 @@ from django.views.decorators.http import (
from .access import customer_for_user from .access import customer_for_user
from .account_backups import queue_account_backup from .account_backups import queue_account_backup
from .credential_views import DatabaseCredentialView from .credential_views import DatabaseCredentialView
from .impersonation import restricted_preview
from .installation_features import panel_feature_allowed from .installation_features import panel_feature_allowed
from .models import DatabaseLogin, HostingAccount, HostingDatabase from .models import DatabaseLogin, HostingAccount, HostingDatabase
from .phpmyadmin import phpmyadmin_available from .phpmyadmin import phpmyadmin_available
@@ -30,7 +31,7 @@ class AddDatabaseLoginForm(forms.Form):
def signed_in_customer(request): def signed_in_customer(request):
customer = customer_for_user(request.user) customer = customer_for_user(request.user)
if customer is None or getattr(request, "impersonation", None) is not None: if customer is None or restricted_preview(request):
raise PermissionDenied raise PermissionDenied
return customer return customer
+3 -2
View File
@@ -16,6 +16,7 @@ from .account_setup import website_records
from .dns_defaults import zone_defaults from .dns_defaults import zone_defaults
from .dns_forms import zone_record_rows from .dns_forms import zone_record_rows
from .domain_policies import managed_mail_domains, policy_for from .domain_policies import managed_mail_domains, policy_for
from .impersonation import restricted_preview
from .independent_websites import account_websites from .independent_websites import account_websites
from .installation_features import panel_feature_allowed from .installation_features import panel_feature_allowed
from .mailbox_imports import with_import_status from .mailbox_imports import with_import_status
@@ -281,10 +282,10 @@ def domain_workspace(request, pk, page):
"customer_mailbox_quota": ( "customer_mailbox_quota": (
panel_feature_allowed(MAIL_PROVISIONING) panel_feature_allowed(MAIL_PROVISIONING)
and customer_mailbox_quota_limit(account) is not None and customer_mailbox_quota_limit(account) is not None
and not getattr(request, "impersonation", None) and not restricted_preview(request)
), ),
"roundcube_enabled": ( "roundcube_enabled": (
not getattr(request, "impersonation", None) not restricted_preview(request)
and roundcube_available(request) and roundcube_available(request)
), ),
"mail_imap_host": settings.MAIL_IMAP_HOST, "mail_imap_host": settings.MAIL_IMAP_HOST,
+2 -1
View File
@@ -11,6 +11,7 @@ from coulobre.sftp_keys import normalize_public_keys
from coulobre.website_files import directory_parts from coulobre.website_files import directory_parts
from .access import customer_for_user from .access import customer_for_user
from .impersonation import restricted_preview
from .installation_features import panel_feature_allowed from .installation_features import panel_feature_allowed
from .models import FolderSftpLogin, HostingAccount from .models import FolderSftpLogin, HostingAccount
from .resource_requests import ( from .resource_requests import (
@@ -94,7 +95,7 @@ def save_folder_login(account_id, customer_id, action, login, data):
@require_http_methods(("GET", "HEAD", "POST")) @require_http_methods(("GET", "HEAD", "POST"))
def folder_sftp_users(request, pk): def folder_sftp_users(request, pk):
customer = customer_for_user(request.user) customer = customer_for_user(request.user)
if customer is None or getattr(request, "impersonation", None) is not None: if customer is None or restricted_preview(request):
raise PermissionDenied raise PermissionDenied
if not settings.LOCAL_WEB_SFTP: if not settings.LOCAL_WEB_SFTP:
raise Http404 raise Http404
+143 -19
View File
@@ -9,8 +9,9 @@ from django.shortcuts import render
from django.utils import timezone from django.utils import timezone
from django.utils.cache import add_never_cache_headers from django.utils.cache import add_never_cache_headers
from .access import is_tenant from .access import PanelRole, is_tenant
from .models import CustomerImpersonation from .models import CustomerImpersonation, CustomerImpersonationAction
from .panel_roles import scoped_user
from .sftp import MANAGE_SFTP_KEYS from .sftp import MANAGE_SFTP_KEYS
SESSION_KEY = "customer_impersonation" SESSION_KEY = "customer_impersonation"
@@ -40,6 +41,66 @@ PREVIEW_VIEWS = frozenset(
"panel:mail_dns_check", "panel:mail_dns_check",
} }
) | frozenset(CUSTOMER_WRITE_PERMISSIONS) ) | frozenset(CUSTOMER_WRITE_PERMISSIONS)
# Review customer hosting routes before adding them. Exclude account
# identity, credential reveals, SSO, and operator endpoints.
MANAGED_VIEWS = (
frozenset(
f"panel:{name}"
for name in [
"account_wordpress",
"customer_workspace",
"domain_workspace",
"system_workspace",
"website_usage",
"website_files",
"independent_website_files",
"website_jobs",
"website_job_create",
"website_job_edit",
"website_https",
"customer_certificates",
"site_php_settings",
"site_php_version",
"independent_php_settings",
"independent_website_create",
"independent_website_operation",
"website_alias_create",
"website_alias_action",
"customer_redirects",
"dns_zone_edit",
"dns_zone_publish",
"mail_dns_setup",
"mail_routing",
"mail_vacation",
"mail_spam",
"mail_delivery",
"mailbox_quota",
"mailbox_import",
"mailbox_removal",
"smtp_applications",
"mail_domain_alias",
"customer_databases",
"database_logins",
"database_export",
"folder_sftp_users",
"customer_backups",
"customer_restore",
"theme_stylesheet",
"user_stylesheet",
"mailbox_credential_rotation",
"database_credential_rotation",
]
)
| PREVIEW_VIEWS
)
SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
def restricted_preview(request):
session = getattr(request, "impersonation", None)
return session is not None and not session.managed_enabled
EndReason = CustomerImpersonation.EndReason EndReason = CustomerImpersonation.EndReason
@@ -48,6 +109,7 @@ def can_impersonate_customer(user):
user.is_authenticated user.is_authenticated
and user.is_active and user.is_active
and user.is_staff and user.is_staff
and getattr(user, "panel_role", None) in (None, PanelRole.ADMIN)
and not is_tenant(user) and not is_tenant(user)
and user.has_perms(IMPERSONATE_CUSTOMER) and user.has_perms(IMPERSONATE_CUSTOMER)
) )
@@ -57,9 +119,15 @@ def can_start_writable_support(user):
return can_impersonate_customer(user) and user.has_perm(WRITE_AS_CUSTOMER) return can_impersonate_customer(user) and user.has_perm(WRITE_AS_CUSTOMER)
def can_start_managed_support(user):
return can_impersonate_customer(user) and user.has_perm(
"hosting.manage_as_customer"
)
def can_edit_customer_resource(request): def can_edit_customer_resource(request):
session = getattr(request, "impersonation", None) session = getattr(request, "impersonation", None)
if session is None: if session is None or session.managed_enabled:
return True return True
permissions = CUSTOMER_WRITE_PERMISSIONS.get( permissions = CUSTOMER_WRITE_PERMISSIONS.get(
request.resolver_match.view_name request.resolver_match.view_name
@@ -88,6 +156,10 @@ def support_write_session(request):
yield None yield None
return return
if session.managed_enabled:
yield None
return
if str(session.pk) != submitted_session or not can_edit_customer_resource( if str(session.pk) != submitted_session or not can_edit_customer_resource(
request request
): ):
@@ -117,7 +189,9 @@ def support_write_session(request):
yield current yield current
def start_impersonation(request, customer, *, write_enabled=False): def start_impersonation(
request, customer, *, write_enabled=False, managed_enabled=False
):
now = timezone.now() now = timezone.now()
session = CustomerImpersonation.objects.create( session = CustomerImpersonation.objects.create(
operator=request.user, operator=request.user,
@@ -125,6 +199,7 @@ def start_impersonation(request, customer, *, write_enabled=False):
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, write_enabled=write_enabled,
managed_enabled=managed_enabled,
started_at=now, started_at=now,
expires_at=now + SESSION_DURATION, expires_at=now + SESSION_DURATION,
) )
@@ -145,6 +220,7 @@ def end_impersonation(request, session, reason):
end_reason=reason, end_reason=reason,
) )
request.session.pop(SESSION_KEY, None) request.session.pop(SESSION_KEY, None)
request.session.pop("support_hosting_account", None)
rotate_token(request) rotate_token(request)
@@ -154,11 +230,43 @@ class CustomerImpersonationMiddleware:
def __call__(self, request): def __call__(self, request):
had_preview = SESSION_KEY in request.session had_preview = SESSION_KEY in request.session
response = self.get_response(request) if had_preview and request.method not in SAFE_METHODS:
with transaction.atomic():
response = self.get_response(request)
if response.status_code == 500:
transaction.set_rollback(True)
elif session := getattr(
request, "managed_hosting_action", None
):
self.audit_hosting_action(request, session, response)
if response.status_code == 500 and (
session := getattr(request, "managed_hosting_action", None)
):
self.audit_hosting_action(request, session, response)
else:
response = self.get_response(request)
if had_preview or SESSION_KEY in request.session: if had_preview or SESSION_KEY in request.session:
add_never_cache_headers(response) add_never_cache_headers(response)
return response return response
@staticmethod
def audit_hosting_action(request, session, response):
match = request.resolver_match
# Audit only the route and numeric IDs, never submitted values,
# query strings, filenames, or credentials.
identifiers = {
key: value
for key, value in match.kwargs.items()
if isinstance(value, int)
}
CustomerImpersonationAction.objects.create(
session=session,
hosting_account_id=identifiers.get("account_id"),
operation=CustomerImpersonationAction.Operation.HOSTING,
resource=match.url_name,
details={"ids": identifiers, "status": response.status_code},
)
def process_view(self, request, view_func, view_args, view_kwargs): def process_view(self, request, view_func, view_args, view_kwargs):
session_id = request.session.get(SESSION_KEY) session_id = request.session.get(SESSION_KEY)
if session_id is None: if session_id is None:
@@ -166,17 +274,21 @@ class CustomerImpersonationMiddleware:
view_name = request.resolver_match.view_name view_name = request.resolver_match.view_name
signing_out = view_name == "panel:logout" and request.method == "POST" signing_out = view_name == "panel:logout" and request.method == "POST"
session = ( sessions = CustomerImpersonation.objects.select_related(
CustomerImpersonation.objects.select_related( "customer__user__hosting_reseller"
"customer__user__hosting_reseller" ).filter(
) pk=session_id,
.filter( operator_id=request.user.pk,
pk=session_id, ended_at__isnull=True,
operator_id=request.user.pk,
ended_at__isnull=True,
)
.first()
) )
mutating = request.method not in SAFE_METHODS
if mutating:
# Lock only the session row. The customer is nullable and is
# checked separately below.
locked = lock_session(sessions.select_related(None))
session = sessions.first() if locked is not None else None
else:
session = sessions.first()
if session is None: if session is None:
reason = EndReason.ACCESS_REVOKED reason = EndReason.ACCESS_REVOKED
elif session.expires_at <= timezone.now(): elif session.expires_at <= timezone.now():
@@ -185,6 +297,8 @@ class CustomerImpersonationMiddleware:
not can_impersonate_customer(request.user) not can_impersonate_customer(request.user)
or session.write_enabled or session.write_enabled
and not request.user.has_perm(WRITE_AS_CUSTOMER) and not request.user.has_perm(WRITE_AS_CUSTOMER)
or session.managed_enabled
and not can_start_managed_support(request.user)
or session.customer is None or session.customer is None
or not session.customer.may_be_impersonated or not session.customer.may_be_impersonated
): ):
@@ -207,14 +321,24 @@ class CustomerImpersonationMiddleware:
if view_name == "panel:impersonation_stop": if view_name == "panel:impersonation_stop":
return None return None
async def preview_user(): request.active_panel_role = PanelRole.CUSTOMER
return session.customer.user request.user = scoped_user(session.customer.user, PanelRole.CUSTOMER)
async def preview_user():
return request.user
request.user = session.customer.user
request.auser = preview_user request.auser = preview_user
if session.managed_enabled and view_name in MANAGED_VIEWS:
if mutating:
request.managed_hosting_action = session
return None
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): if (
not session.managed_enabled
and request.method == "POST"
and can_edit_customer_resource(request)
):
return None return None
return render( return render(
request, "hosting/customer_preview_restricted.html", status=403 request, "hosting/customer_preview_restricted.html", status=403
@@ -8,6 +8,7 @@ from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_http_methods from django.views.decorators.http import require_http_methods
from .access import can_manage_hosting, customer_for_user from .access import can_manage_hosting, customer_for_user
from .impersonation import restricted_preview
from .mail_domain_aliases import ( from .mail_domain_aliases import (
aliases_available, aliases_available,
queue_domain_alias, queue_domain_alias,
@@ -24,7 +25,7 @@ PERMISSIONS = (
def may_manage_aliases(request): def may_manage_aliases(request):
return ( return (
aliases_available() aliases_available()
and not getattr(request, "impersonation", None) and not restricted_preview(request)
and can_manage_hosting(request.user, PERMISSIONS) and can_manage_hosting(request.user, PERMISSIONS)
) )
+3 -2
View File
@@ -26,6 +26,7 @@ from .access import (
owns_customer_operations, owns_customer_operations,
reseller_for_user, reseller_for_user,
) )
from .impersonation import restricted_preview
from .mail_policies import ( from .mail_policies import (
mail_policy_available, mail_policy_available,
policy_account, policy_account,
@@ -53,7 +54,7 @@ VIEW_PERMISSIONS = (
def mail_policy_enabled(request, kind): def mail_policy_enabled(request, kind):
return ( return (
mail_policy_available(kind) mail_policy_available(kind)
and getattr(request, "impersonation", None) is None and not restricted_preview(request)
and can_manage_hosting( and can_manage_hosting(
request.user, (*VIEW_PERMISSIONS, POLICY_PERMISSIONS[kind]) request.user, (*VIEW_PERMISSIONS, POLICY_PERMISSIONS[kind])
) )
@@ -210,7 +211,7 @@ class MailPolicyEditor(
def has_permission(self): def has_permission(self):
return ( return (
reseller_for_user(self.request.user) is None reseller_for_user(self.request.user) is None
and getattr(self.request, "impersonation", None) is None and not restricted_preview(self.request)
and super().has_permission() and super().has_permission()
) )
+2 -1
View File
@@ -18,6 +18,7 @@ from coulobre.imap_import import MailboxImportError, source_hostname
from . import mailbox_import_preview as preview from . import mailbox_import_preview as preview
from .access import can_manage_hosting, customer_for_user from .access import can_manage_hosting, customer_for_user
from .impersonation import restricted_preview
from .mailbox_imports import PERMISSIONS, available, display_name, queue_import from .mailbox_imports import PERMISSIONS, available, display_name, queue_import
from .models import HostingMailbox, MailboxImport from .models import HostingMailbox, MailboxImport
@@ -62,7 +63,7 @@ class MailboxImportView(PermissionRequiredMixin, FormView):
def has_permission(self): def has_permission(self):
return ( return (
available() available()
and not getattr(self.request, "impersonation", None) and not restricted_preview(self.request)
and can_manage_hosting(self.request.user, PERMISSIONS) and can_manage_hosting(self.request.user, PERMISSIONS)
) )
+2 -1
View File
@@ -17,6 +17,7 @@ from coulobre.mail_policy import parse_mail_policy
from .access import can_manage_hosting, customer_for_user from .access import can_manage_hosting, customer_for_user
from .domain_policies import require_managed from .domain_policies import require_managed
from .impersonation import restricted_preview
from .models import HostingAccount, HostingMailbox, MailboxRemoval from .models import HostingAccount, HostingMailbox, MailboxRemoval
from .node_client import apply_on_local_node from .node_client import apply_on_local_node
from .resource_requests import lock_hosting_account, require_active_services from .resource_requests import lock_hosting_account, require_active_services
@@ -32,7 +33,7 @@ PERMISSIONS = ("hosting.view_hostingmailbox", "hosting.delete_hostingmailbox")
def can_remove_mailbox(request): def can_remove_mailbox(request):
return ( return (
settings.LOCAL_MAILBOX_PROVISIONING settings.LOCAL_MAILBOX_PROVISIONING
and getattr(request, "impersonation", None) is None and not restricted_preview(request)
and can_manage_hosting(request.user, PERMISSIONS) and can_manage_hosting(request.user, PERMISSIONS)
) )
@@ -0,0 +1,56 @@
# Generated by Django 5.2.19 on 2026-12-04 14:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0098_mailbox_import_preview"),
]
operations = [
migrations.AlterModelOptions(
name="customerimpersonation",
options={
"default_permissions": ("view",),
"ordering": ("-started_at", "-pk"),
"permissions": (
("manage_as_customer", "Can manage hosting as a customer"),
(
"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="managed_enabled",
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name="customerimpersonationaction",
name="hosting_account_id",
field=models.PositiveBigIntegerField(null=True),
),
migrations.AlterField(
model_name="customerimpersonationaction",
name="operation",
field=models.CharField(
choices=[
("hosting", "Customer hosting action"),
("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,
),
),
]
+4 -1
View File
@@ -245,6 +245,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) write_enabled = models.BooleanField(default=False)
managed_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)
@@ -257,6 +258,7 @@ class CustomerImpersonation(models.Model):
default_permissions = ("view",) default_permissions = ("view",)
verbose_name = "customer impersonation session" verbose_name = "customer impersonation session"
permissions = ( permissions = (
("manage_as_customer", "Can manage hosting as a customer"),
("impersonate_customer", "Can view the panel as a customer"), ("impersonate_customer", "Can view the panel as a customer"),
( (
"write_as_customer", "write_as_customer",
@@ -270,6 +272,7 @@ class CustomerImpersonation(models.Model):
class CustomerImpersonationAction(models.Model): class CustomerImpersonationAction(models.Model):
class Operation(models.TextChoices): class Operation(models.TextChoices):
HOSTING = "hosting", "Customer hosting action"
DATABASE = "database", "Requested database" DATABASE = "database", "Requested database"
MAILBOX = "mailbox", "Requested mailbox" MAILBOX = "mailbox", "Requested mailbox"
ADD_KEYS = "add_keys", "Queued SSH key upload" ADD_KEYS = "add_keys", "Queued SSH key upload"
@@ -279,7 +282,7 @@ class CustomerImpersonationAction(models.Model):
session = models.ForeignKey( session = models.ForeignKey(
CustomerImpersonation, on_delete=models.PROTECT, related_name="actions" CustomerImpersonation, on_delete=models.PROTECT, related_name="actions"
) )
hosting_account_id = models.PositiveBigIntegerField() hosting_account_id = models.PositiveBigIntegerField(null=True)
operation = models.CharField(max_length=16, choices=Operation.choices) operation = models.CharField(max_length=16, choices=Operation.choices)
resource = models.CharField(max_length=254) resource = models.CharField(max_length=254)
details = models.JSONField(default=dict) details = models.JSONField(default=dict)
+2 -1
View File
@@ -5,6 +5,7 @@ from django.db import transaction
from coulobre.php_runtime import available_php_versions from coulobre.php_runtime import available_php_versions
from .access import customer_for_user, is_tenant from .access import customer_for_user, is_tenant
from .impersonation import restricted_preview
from .models import SitePhpVersion, WebActivation from .models import SitePhpVersion, WebActivation
from .php_settings import plan_php_versions from .php_settings import plan_php_versions
from .resource_requests import lock_hosting_account, require_active_services from .resource_requests import lock_hosting_account, require_active_services
@@ -27,7 +28,7 @@ class SitePhpVersionForm(forms.Form):
def can_change_php_version(request): def can_change_php_version(request):
user = request.user user = request.user
return getattr(request, "impersonation", None) is None and ( return not restricted_preview(request) and (
customer_for_user(user) is not None customer_for_user(user) is not None
or (not is_tenant(user) and user.has_perms(CHANGE_PHP_VERSION)) or (not is_tenant(user) and user.has_perms(CHANGE_PHP_VERSION))
) )
+2 -1
View File
@@ -17,6 +17,7 @@ from coulobre.web_redirects import (
from .access import customer_for_user from .access import customer_for_user
from .certificate_views import account_certificate_sites from .certificate_views import account_certificate_sites
from .impersonation import restricted_preview
from .installation_features import panel_feature_allowed from .installation_features import panel_feature_allowed
from .models import HostingAccount, WebsiteAlias, WebsiteRedirectPolicy from .models import HostingAccount, WebsiteAlias, WebsiteRedirectPolicy
from .resource_requests import lock_hosting_account, require_active_services from .resource_requests import lock_hosting_account, require_active_services
@@ -137,7 +138,7 @@ def request_redirect_change(
@require_http_methods(("GET", "HEAD", "POST")) @require_http_methods(("GET", "HEAD", "POST"))
def customer_redirects(request, pk): def customer_redirects(request, pk):
customer = customer_for_user(request.user) customer = customer_for_user(request.user)
if customer is None or getattr(request, "impersonation", None) is not None: if customer is None or restricted_preview(request):
raise PermissionDenied raise PermissionDenied
if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"): if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"):
raise Http404 raise Http404
+13 -4
View File
@@ -121,11 +121,20 @@ def show_credential_action(request, kind):
) )
def credential_actor(request):
return getattr(request, "support_operator", request.user)
def show_rotation_action(request, kind): def show_rotation_action(request, kind):
return ( session = getattr(request, "impersonation", None)
getattr(request, "impersonation", None) is None if session is not None and not (
and enabled_rotation(request, kind) session.managed_enabled
and can_rotate_credentials(request.user, kind) and credential_actor(request).has_perms(CREDENTIAL_PERMISSIONS[kind])
and credential_actor(request).has_perm(ROTATION_PERMISSIONS[kind])
):
return False
return enabled_rotation(request, kind) and can_rotate_credentials(
request.user, kind
) )
+2 -1
View File
@@ -20,6 +20,7 @@ from coulobre.smtp_application import SmtpApplicationRequest
from .access import can_manage_hosting, customer_for_user from .access import can_manage_hosting, customer_for_user
from .domain_policies import require_managed from .domain_policies import require_managed
from .impersonation import restricted_preview
from .installation_features import panel_feature_allowed from .installation_features import panel_feature_allowed
from .mail_dns_setup import sync_mail_dns from .mail_dns_setup import sync_mail_dns
from .models import HostingAccount, HostingMailDomain, SmtpApplication from .models import HostingAccount, HostingMailDomain, SmtpApplication
@@ -41,7 +42,7 @@ def smtp_applications_available(request):
and settings.MAIL_SUBMISSION_HOST and settings.MAIL_SUBMISSION_HOST
and request.is_secure() and request.is_secure()
and not settings.DEBUG and not settings.DEBUG
and getattr(request, "impersonation", None) is None and not restricted_preview(request)
and can_manage_hosting(request.user, PERMISSIONS) and can_manage_hosting(request.user, PERMISSIONS)
) )
@@ -478,6 +478,12 @@ a.sidebar-identity:hover {
color: var(--sidebar-text); color: var(--sidebar-text);
} }
.sidebar-impersonation-exit .sidebar-action {
width: 100%;
text-align: start;
white-space: normal;
}
.sidebar-icon-action { .sidebar-icon-action {
display: grid; display: grid;
width: 2.2rem; width: 2.2rem;
@@ -921,7 +927,7 @@ dd {
background: var(--notice-bg); background: var(--notice-bg);
} }
.customer-preview, .table-actions { .table-actions {
display: flex; display: flex;
align-items: center; align-items: center;
flex-wrap: wrap; flex-wrap: wrap;
@@ -929,7 +935,6 @@ dd {
} }
.customer-preview { .customer-preview {
justify-content: space-between;
border-color: var(--focus); border-color: var(--focus);
background: var(--warning-bg); background: var(--warning-bg);
color: var(--warning-text); color: var(--warning-text);
@@ -168,6 +168,9 @@
{% if show_database_credentials %} {% if show_database_credentials %}
<a class="button secondary compact" href="{% url 'panel:database_credentials' database.pk %}" aria-label="Connection details for {{ database }}">Connection details</a> <a class="button secondary compact" href="{% url 'panel:database_credentials' database.pk %}" aria-label="Connection details for {{ database }}">Connection details</a>
{% endif %} {% endif %}
{% if show_database_rotation and database.provisioning.state == "configured" %}
<a class="button secondary compact" href="{% url 'panel:database_credential_rotation' database.pk %}" aria-label="Change password for {{ database }}">Change password</a>
{% endif %}
{% if show_phpmyadmin %} {% if show_phpmyadmin %}
<form method="post" action="{% url 'panel:phpmyadmin_launch' database.pk %}"> <form method="post" action="{% url 'panel:phpmyadmin_launch' database.pk %}">
{% csrf_token %} {% csrf_token %}
@@ -22,7 +22,7 @@
<table> <table>
<thead><tr><th scope="col">User</th><th scope="col">Workspace</th><th scope="col">Manager</th><th scope="col">Hosting accounts</th><th scope="col">Disk</th><th scope="col">Monthly traffic</th><th scope="col">Domains</th><th scope="col">Databases</th><th scope="col">Mailboxes</th><th scope="col">Added</th>{% if has_user_actions %}<th scope="col">Actions</th>{% endif %}</tr></thead> <thead><tr><th scope="col">User</th><th scope="col">Workspace</th><th scope="col">Manager</th><th scope="col">Hosting accounts</th><th scope="col">Disk</th><th scope="col">Monthly traffic</th><th scope="col">Domains</th><th scope="col">Databases</th><th scope="col">Mailboxes</th><th scope="col">Added</th>{% if has_user_actions %}<th scope="col">Actions</th>{% endif %}</tr></thead>
<tbody> <tbody>
{% for login, usage, may_delete in login_rows %} {% for login, usage, may_delete, may_impersonate in login_rows %}
<tr> <tr>
<th scope="row">{{ login.get_username }}</th> <th scope="row">{{ login.get_username }}</th>
<td>{% if login.is_superuser %}Operator{% elif login.hosting_reseller %}Manager{% else %}Customer{% endif %}</td> <td>{% if login.is_superuser %}Operator{% elif login.hosting_reseller %}Manager{% else %}Customer{% endif %}</td>
@@ -32,7 +32,19 @@
<td>{{ login.date_joined|date:"j M Y" }}</td> <td>{{ login.date_joined|date:"j M Y" }}</td>
{% if has_user_actions %} {% if has_user_actions %}
<td> <td>
<div class="form-actions"> <div class="table-actions">
{% if may_impersonate and may_manage_as_customer %}
<form method="post" action="{% url 'panel:impersonation_managed_start' login.hosting_customer.pk %}">
{% csrf_token %}
<button class="button secondary compact" type="submit" aria-label="Manage hosting as {{ login.get_username }}">Manage as customer</button>
</form>
{% endif %}
{% if may_impersonate %}
<form method="post" action="{% url 'panel:impersonation_start' login.hosting_customer.pk %}">
{% csrf_token %}
<button class="button secondary compact" type="submit" aria-label="Sign in as customer {{ login.get_username }}">Sign in as customer</button>
</form>
{% endif %}
{% if not login.is_staff and not login.is_superuser %} {% if not login.is_staff and not login.is_superuser %}
{% if login.hosting_reseller and perms.hosting.change_reseller %} {% if login.hosting_reseller and perms.hosting.change_reseller %}
<a class="button secondary compact" href="{% url 'panel:manage_invitation' 'manager' login.hosting_reseller.pk %}" aria-label="Contact and invitation for {{ login.get_username }}">Contact and invitation</a> <a class="button secondary compact" href="{% url 'panel:manage_invitation' 'manager' login.hosting_reseller.pk %}" aria-label="Contact and invitation for {{ login.get_username }}">Contact and invitation</a>
@@ -50,7 +50,12 @@
</button> </button>
</form> </form>
</div> </div>
{% if not request.impersonation and request.panel_role_options|length > 1 %} {% if request.impersonation %}
<form class="sidebar-impersonation-exit" method="post" action="{% url 'panel:impersonation_stop' %}">
{% csrf_token %}
<button class="sidebar-action" type="submit">Leave impersonation</button>
</form>
{% elif request.panel_role_options|length > 1 %}
<details class="panel-role-switch" data-role-switch> <details class="panel-role-switch" data-role-switch>
<summary aria-label="Switch role from {{ request.panel_role_label }}"> <summary aria-label="Switch role from {{ request.panel_role_label }}">
<svg class="nav-icon" aria-hidden="true" focusable="false"><use href="{{ panel_icons }}#{{ request.panel_role_icon }}"></use></svg> <svg class="nav-icon" aria-hidden="true" focusable="false"><use href="{{ panel_icons }}#{{ request.panel_role_icon }}"></use></svg>
@@ -77,18 +82,14 @@
{% block account_selector %}{% include "hosting/workspace_account_selector.html" %}{% endblock %} {% block account_selector %}{% include "hosting/workspace_account_selector.html" %}{% endblock %}
{% if request.impersonation %} {% if request.impersonation %}
<section class="notice customer-preview" aria-label="Customer view"> <section class="notice customer-preview" aria-label="Customer view">
<div> <strong>Viewing as {{ request.impersonation.customer }}</strong>
<strong>Viewing as {{ request.impersonation.customer }}</strong> {% if request.impersonation.managed_enabled %}
{% if request.impersonation.write_enabled %} <p>Managing customer hosting · {{ request.impersonation.operator_username }}</p>
<p>Support session with write access · {{ request.impersonation.operator_username }}</p> {% elif request.impersonation.write_enabled %}
{% else %} <p>Support session with write access · {{ request.impersonation.operator_username }}</p>
<p>Read-only support session</p> {% else %}
{% endif %} <p>Read-only support session</p>
</div> {% endif %}
<form method="post" action="{% url 'panel:impersonation_stop' %}">
{% csrf_token %}
<button class="button secondary" type="submit">End customer view</button>
</form>
</section> </section>
{% endif %} {% endif %}
{% for announcement in panel_announcements %}<section class="notice"><strong>{{ announcement.subject }}</strong>{{ announcement.body|linebreaks }}</section>{% endfor %} {% for announcement in panel_announcements %}<section class="notice"><strong>{{ announcement.subject }}</strong>{{ announcement.body|linebreaks }}</section>{% endfor %}
@@ -3,7 +3,7 @@
{% block page_title %}SSL Certificates{% endblock %} {% block page_title %}SSL Certificates{% endblock %}
{% block page_metadata %}<p class="heading-meta">{{ account.primary_domain }}</p>{% endblock %} {% block page_metadata %}<p class="heading-meta">{{ account.primary_domain }}</p>{% endblock %}
{% block page_actions %} {% block page_actions %}
{% if not request.impersonation %}<a class="button secondary" href="{% url 'panel:website_https' account.pk %}">HTTPS by hostname</a>{% endif %} {% if not request.impersonation or request.impersonation.managed_enabled %}<a class="button secondary" href="{% url 'panel:website_https' account.pk %}">HTTPS by hostname</a>{% endif %}
{% endblock %} {% endblock %}
{% block page_tabs %} {% block page_tabs %}
{% if sites %} {% if sites %}
@@ -4,7 +4,7 @@
<header class="page-heading"> <header class="page-heading">
<div> <div>
<h1>{% if is_reseller %}My users{% else %}Customers{% endif %}</h1> <h1>{% if is_reseller %}My users{% else %}Customers{% endif %}</h1>
<p class="heading-meta">Manage the logins people use to access their assigned hosting.</p> <p class="heading-meta">{% if is_reseller %}Manage assigned hosting and invitations for your customers.{% else %}Manage the logins people use to access their assigned hosting.{% endif %}</p>
</div> </div>
{% if is_operator and perms.hosting.add_customer %} {% if is_operator and perms.hosting.add_customer %}
<div class="form-actions"> <div class="form-actions">
@@ -42,7 +42,7 @@
<tr> <tr>
<td> <td>
<strong>{{ customer }}</strong> <strong>{{ customer }}</strong>
{% if is_reseller or perms.hosting.view_hostingaccount %} {% if is_operator and perms.hosting.view_hostingaccount %}
<div><a href="{% url 'panel:accounts' %}?customer={{ customer.pk }}">View assigned hosting</a></div> <div><a href="{% url 'panel:accounts' %}?customer={{ customer.pk }}">View assigned hosting</a></div>
{% endif %} {% endif %}
</td> </td>
@@ -56,13 +56,16 @@
{% if is_operator and perms.hosting.change_customer or can_impersonate or is_reseller %} {% if is_operator and perms.hosting.change_customer or can_impersonate or is_reseller %}
<td> <td>
<div class="table-actions"> <div class="table-actions">
{% if is_reseller %}
<a class="button secondary compact" href="{% url 'panel:accounts' %}?customer={{ customer.pk }}" aria-label="Manage hosting for {{ customer }}">Manage hosting</a>
{% endif %}
{% if is_reseller or is_operator and perms.hosting.change_customer %} {% if is_reseller or is_operator and perms.hosting.change_customer %}
<a class="button secondary compact" href="{% url 'panel:manage_invitation' 'customer' customer.pk %}">Contact and invitation</a> <a class="button secondary compact" href="{% url 'panel:manage_invitation' 'customer' customer.pk %}" aria-label="Contact and invitation for {{ customer }}">Contact and invitation</a>
{% endif %} {% endif %}
{% if is_operator and perms.hosting.add_hostingaccount and perms.hosting.view_hostingaccount %} {% if is_operator and perms.hosting.add_hostingaccount and perms.hosting.view_hostingaccount %}
<a class="button secondary compact" href="{% url 'panel:account_create' %}?customer={{ customer.pk }}">Add hosting</a> <a class="button secondary compact" href="{% url 'panel:account_create' %}?customer={{ customer.pk }}">Add hosting</a>
{% endif %} {% endif %}
{% if perms.hosting.change_customer and not customer.user.is_staff and not customer.user.is_superuser and not customer.user.hosting_reseller %} {% if is_operator and perms.hosting.change_customer and not customer.user.is_staff and not customer.user.is_superuser and not customer.user.hosting_reseller %}
<form method="post" action="{% url 'panel:customer_access' customer.pk %}{% querystring %}"> <form method="post" action="{% url 'panel:customer_access' customer.pk %}{% querystring %}">
{% csrf_token %} {% csrf_token %}
{% if customer.user.is_active %} {% if customer.user.is_active %}
@@ -72,7 +75,7 @@
{% endif %} {% endif %}
</form> </form>
{% endif %} {% endif %}
{% if can_impersonate and customer.may_be_impersonated %} {% if is_operator and can_impersonate and customer.may_be_impersonated %}
<form method="post" action="{% url 'panel:impersonation_start' customer.pk %}"> <form method="post" action="{% url 'panel:impersonation_start' customer.pk %}">
{% csrf_token %} {% csrf_token %}
<button class="button secondary compact" type="submit" aria-label="View as customer {{ customer }}">View as customer</button> <button class="button secondary compact" type="submit" aria-label="View as customer {{ customer }}">View as customer</button>
@@ -5,7 +5,7 @@
<div> <div>
{% if request.impersonation %} {% if request.impersonation %}
<h1>Unavailable in customer view</h1> <h1>Unavailable in customer view</h1>
<p class="heading-meta">End the customer view to use your administrator account.</p> <p class="heading-meta">Choose Leave impersonation in the account controls to return to your operator workspace.</p>
{% else %} {% else %}
<h1>Customer view ended</h1> <h1>Customer view ended</h1>
<p class="heading-meta">The session expired or access changed.</p> <p class="heading-meta">The session expired or access changed.</p>
@@ -14,9 +14,11 @@
</header> </header>
{% endblock %} {% endblock %}
{% block page_content %} {% block page_content %}
{% if not request.impersonation and perms.hosting.view_customer %} {% if not request.impersonation %}
<a class="button secondary" href="{% url 'panel:customers' %}">Back to customers</a> {% if is_operator and perms.hosting.view_customer %}
{% else %} <a class="button secondary" href="{% url 'panel:all_users' %}">Back to all users</a>
<a class="button secondary" href="{% url 'panel:accounts' %}">Back to hosting accounts</a> {% else %}
<a class="button secondary" href="{% url 'panel:accounts' %}">Back to hosting accounts</a>
{% endif %}
{% endif %} {% endif %}
{% endblock %} {% endblock %}
@@ -13,7 +13,7 @@
<a class="quiet-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a> <a class="quiet-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
{% endblock %} {% endblock %}
{% block page_content %} {% block page_content %}
{% if not request.impersonation %} {% if not request.impersonation or request.impersonation.managed_enabled %}
<section class="surface editor-surface"> <section class="surface editor-surface">
<form method="post" class="editor"> <form method="post" class="editor">
{% csrf_token %} {% csrf_token %}
+298 -3
View File
@@ -1,12 +1,14 @@
from datetime import timedelta from datetime import timedelta
from unittest.mock import patch
from django.conf import settings from django.conf import settings
from django.contrib.auth import SESSION_KEY as AUTH_SESSION_KEY from django.contrib.auth import SESSION_KEY as AUTH_SESSION_KEY
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission from django.contrib.auth.models import Permission
from django.test import Client, TestCase from django.test import Client, TestCase, override_settings
from django.urls import reverse from django.urls import reverse
from django.utils import timezone from django.utils import timezone
from django_otp.plugins.otp_totp.models import TOTPDevice
from .impersonation import SESSION_DURATION, SESSION_KEY from .impersonation import SESSION_DURATION, SESSION_KEY
from .models import ( from .models import (
@@ -14,8 +16,12 @@ from .models import (
CustomerImpersonation, CustomerImpersonation,
HostingAccount, HostingAccount,
HostingDatabase, HostingDatabase,
HostingDnsZone,
HostingMailbox, HostingMailbox,
HostingMailDomain,
MailboxProvisioning,
Reseller, Reseller,
ServiceCredentialAccess,
) )
@@ -39,11 +45,15 @@ class CustomerImpersonationTests(TestCase):
def setUp(self): def setUp(self):
self.client.force_login(self.operator) self.client.force_login(self.operator)
self.accounts = reverse("panel:accounts") self.accounts = reverse("panel:accounts")
self.all_users = reverse("panel:all_users")
self.customers = reverse("panel:customers") self.customers = reverse("panel:customers")
self.start_url = reverse( self.start_url = reverse(
"panel:impersonation_start", args=[self.customer.pk] "panel:impersonation_start", args=[self.customer.pk]
) )
self.stop_url = reverse("panel:impersonation_stop") self.stop_url = reverse("panel:impersonation_stop")
self.write_start_url = reverse(
"panel:impersonation_write_start", args=[self.customer.pk]
)
def grant_support_permissions(self, user, *codenames): def grant_support_permissions(self, user, *codenames):
user.user_permissions.add( user.user_permissions.add(
@@ -62,6 +72,287 @@ class CustomerImpersonationTests(TestCase):
pk=self.client.session[SESSION_KEY] pk=self.client.session[SESSION_KEY]
) )
def start_managed(self):
url = reverse(
"panel:impersonation_managed_start", args=[self.customer.pk]
)
response = self.client.post(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_managed_session_can_make_customer_changes_and_audits_them(self):
self.assertContains(
self.client.get(self.all_users), "Manage as customer"
)
support = self.start_managed()
self.assertTrue(support.managed_enabled)
page = self.client.get(self.accounts)
self.assertContains(page, "Managing customer hosting")
self.assertNotContains(page, "Add hosting account")
self.assertNotContains(page, self.other_account.name)
self.assertContains(page, "Leave impersonation")
url = reverse("panel:database_create", args=[self.account.pk])
other = reverse("panel:database_create", args=[self.other_account.pk])
self.assertNotEqual(
self.client.post(other, {"suffix": "denied"}).status_code, 302
)
form = self.client.get(url).context["form"]
self.assertFalse(form.fields["suffix"].disabled)
response = self.client.post(url, {"suffix": "application"})
self.assertEqual(response.status_code, 302)
self.assertTrue(
self.account.databases.filter(suffix="application").exists()
)
self.assertFalse(self.other_account.databases.exists())
action = support.actions.get(details__status=302)
self.assertEqual(action.resource, "database_create")
self.assertEqual(
action.details,
{
"ids": {"pk": self.account.pk},
"status": 302,
},
)
self.assertRedirects(self.client.post(self.stop_url), self.all_users)
self.assertEqual(
self.client.session[AUTH_SESSION_KEY], str(self.operator.pk)
)
def test_managed_dns_edit_respects_customer_delegation(self):
zone = HostingDnsZone.objects.create(
account=self.account,
domain=self.account.primary_domain,
nameservers=["ns.provider.example"],
responsible_name="hostmaster.alice.example",
)
self.start_managed()
show = reverse("panel:dns_zone_edit", args=[zone.pk])
self.assertEqual(self.client.get(show).status_code, 403)
zone.delegate_dns = True
zone.save(update_fields=["delegate_dns"])
self.assertEqual(self.client.get(show).status_code, 200)
self.assertRedirects(
self.client.post(
show,
{
"serial": zone.serial,
"nameservers": "ns.unapproved.example",
"addresses": "alice.example 192.0.2.1",
},
),
self.account.get_absolute_url(),
)
zone.refresh_from_db()
self.assertEqual(zone.nameservers, ["ns.provider.example"])
self.assertEqual(len(zone.addresses), 1)
def test_managed_session_denies_account_identity_and_operator_changes(
self,
):
self.start_managed()
for name, args in (
("panel:account_security", []),
("panel:account_password", []),
("panel:account_authenticator", []),
("panel:all_users", []),
("panel:account_edit", [self.account.pk]),
("panel:impersonation_start", [self.customer.pk]),
("panel:switch_panel_role", []),
):
with self.subTest(route=name):
url = reverse(name, args=args)
self.assertEqual(self.client.get(url).status_code, 403)
self.assertEqual(self.client.post(url).status_code, 403)
def test_managed_permission_is_separate_and_revocation_ends_session(self):
self.grant_support_permissions(
self.support,
"view_customer",
"impersonate_customer",
"write_as_customer",
)
self.client.force_login(self.support)
start = reverse(
"panel:impersonation_managed_start", args=[self.customer.pk]
)
self.assertNotContains(self.client.get(self.all_users), start)
self.assertEqual(self.client.post(start).status_code, 403)
self.grant_support_permissions(self.support, "manage_as_customer")
managed = self.start_managed()
self.support.user_permissions.remove(
Permission.objects.get(codename="manage_as_customer")
)
self.assertEqual(
self.client.post(
reverse("panel:database_create", args=[self.account.pk]),
{"suffix": "denied"},
).status_code,
409,
)
managed.refresh_from_db()
self.assertEqual(managed.end_reason, managed.EndReason.ACCESS_REVOKED)
self.assertFalse(self.account.databases.exists())
@override_settings(
LOCAL_MAILBOX_PROVISIONING=True,
MAILBOX_PASSWORD_CHANGES=True,
REMOTE_MAILBOX_CREDENTIALS=True,
REMOTE_MAILBOX_CREDENTIAL_ROTATION=True,
)
def test_managed_mailbox_rotation_requires_operator_password(self):
self.operator.set_password("operator-password")
self.operator.save(update_fields=["password"])
self.alice.set_password("customer-password")
self.alice.save(update_fields=["password"])
self.client.force_login(self.operator)
domain = HostingMailDomain.objects.create(
account=self.account, domain=self.account.primary_domain
)
mailbox = HostingMailbox.objects.create(
mail_domain=domain, local_part="support"
)
MailboxProvisioning.objects.create(
mailbox=mailbox, finished_at=timezone.now()
)
self.start_managed()
self.assertEqual(
self.client.get(
reverse("panel:mailbox_credentials", args=[mailbox.pk])
).status_code,
403,
)
url = reverse("panel:mailbox_credential_rotation", args=[mailbox.pk])
with patch(
"coulobre.hosting.service_credentials.apply_on_local_node",
side_effect=[
{"generation": None},
{
"user": str(mailbox),
"password": "new-mailbox-password",
},
],
) as node:
page = self.client.get(url, secure=True)
self.assertEqual(page.status_code, 200)
ticket = page.context["form"]["ticket"].value()
result = self.client.post(
url,
{"ticket": ticket, "password": "customer-password"},
secure=True,
)
self.assertContains(result, "Enter your current panel password.")
self.assertEqual(node.call_count, 1)
result = self.client.post(
url,
{"ticket": ticket, "password": "operator-password"},
secure=True,
)
self.assertContains(result, "new-mailbox-password")
self.assertIn("no-store", result.headers["Cache-Control"])
self.assertEqual(
ServiceCredentialAccess.objects.get(outcome="rotated").actor,
self.operator,
)
def test_operator_starts_from_all_users_and_leaves_in_sidebar(self):
response = self.client.get(self.all_users)
self.assertContains(response, f'action="{self.start_url}"', count=1)
self.assertContains(response, "Sign in as customer alice")
self.assertNotContains(response, self.write_start_url)
self.assertContains(response, "data-role-switch")
preview = self.start_preview()
self.assertFalse(preview.write_enabled)
response = self.client.get(self.accounts)
self.assertContains(
response,
f'<form class="sidebar-impersonation-exit" method="post" '
f'action="{self.stop_url}">',
count=1,
)
self.assertContains(response, "Leave impersonation", count=1)
self.assertNotContains(response, "data-role-switch")
self.assertRedirects(self.client.post(self.stop_url), self.all_users)
self.assertEqual(
self.client.session[AUTH_SESSION_KEY], str(self.operator.pk)
)
self.assertNotIn(SESSION_KEY, self.client.session)
preview.refresh_from_db()
self.assertEqual(preview.operator, self.operator)
self.assertEqual(preview.end_reason, preview.EndReason.STOPPED)
def test_manager_actions_remain_scoped_without_impersonation(self):
manager = Reseller.objects.create(
user=get_user_model().objects.create_user("manager")
)
self.customer.reseller = manager
self.customer.save(update_fields=["reseller"])
self.account.reseller = manager
self.account.save(update_fields=["reseller"])
other = Customer.objects.create(
user=get_user_model().objects.create_user("unassigned")
)
invite = reverse(
"panel:manage_invitation", args=["customer", self.customer.pk]
)
other_invite = reverse(
"panel:manage_invitation", args=["customer", other.pk]
)
self.client.force_login(manager.user)
response = self.client.get(self.customers)
self.assertContains(response, "Manage hosting for alice")
self.assertContains(
response, f"{self.accounts}?customer={self.customer.pk}"
)
self.assertContains(response, invite)
self.assertNotContains(response, "unassigned")
self.assertNotContains(response, self.start_url)
self.assertNotContains(response, self.write_start_url)
self.assertNotContains(response, "Suspend sign-in")
self.assertEqual(self.client.get(invite).status_code, 200)
self.assertEqual(self.client.get(other_invite).status_code, 404)
self.assertContains(
self.client.get(self.accounts, {"customer": self.customer.pk}),
self.account.name,
)
for route in (
self.start_url,
self.write_start_url,
reverse(
"panel:impersonation_managed_start", args=[self.customer.pk]
),
):
self.assertEqual(self.client.post(route).status_code, 403)
def test_operator_cannot_impersonate_in_another_workspace(self):
self.client.get(self.accounts)
Customer.objects.create(
user=self.operator,
reseller=Reseller.objects.get(user=self.operator),
)
device = TOTPDevice.objects.create(user=self.operator, name="Panel")
session = self.client.session
session["otp_device_id"] = device.persistent_id
session.save()
self.assertContains(self.client.get(self.all_users), self.start_url)
switch = reverse("panel:switch_panel_role")
for role in ("manager", "customer"):
with self.subTest(role=role):
self.assertRedirects(
self.client.post(switch, {"role": role}), self.accounts
)
self.assertEqual(
self.client.get(self.all_users).status_code, 403
)
for route in (self.start_url, self.write_start_url):
self.assertEqual(self.client.post(route).status_code, 403)
self.assertFalse(CustomerImpersonation.objects.exists())
def test_reads_only_customer_accounts_and_keeps_operator_login(self): def test_reads_only_customer_accounts_and_keeps_operator_login(self):
preview = self.start_preview() preview = self.start_preview()
@@ -124,7 +415,7 @@ class CustomerImpersonationTests(TestCase):
method = "post" if url == self.start_url else "get" method = "post" if url == self.start_url else "get"
self.assertContains( self.assertContains(
getattr(self.client, method)(url), getattr(self.client, method)(url),
"End customer view", "Leave impersonation",
status_code=403, status_code=403,
) )
self.assertEqual(CustomerImpersonation.objects.count(), 1) self.assertEqual(CustomerImpersonation.objects.count(), 1)
@@ -135,14 +426,16 @@ class CustomerImpersonationTests(TestCase):
self.assertNotContains( self.assertNotContains(
self.client.get(self.customers), "View as customer" self.client.get(self.customers), "View as customer"
) )
self.assertNotContains(self.client.get(self.all_users), self.start_url)
self.assertEqual(self.client.post(self.start_url).status_code, 403) self.assertEqual(self.client.post(self.start_url).status_code, 403)
self.grant_support_permissions(self.support, "impersonate_customer") self.grant_support_permissions(self.support, "impersonate_customer")
self.assertContains( self.assertContains(
self.client.get(self.customers), "View as customer alice" self.client.get(self.customers), "View as customer alice"
) )
self.assertContains(self.client.get(self.all_users), self.start_url)
self.start_preview() self.start_preview()
self.assertRedirects(self.client.post(self.stop_url), self.customers) self.assertRedirects(self.client.post(self.stop_url), self.all_users)
Reseller.objects.create(user=self.support) Reseller.objects.create(user=self.support)
self.assertEqual(self.client.post(self.start_url).status_code, 403) self.assertEqual(self.client.post(self.start_url).status_code, 403)
@@ -163,9 +456,11 @@ class CustomerImpersonationTests(TestCase):
) )
customer = Customer.objects.create(user=user) customer = Customer.objects.create(user=user)
url = reverse("panel:impersonation_start", args=[customer.pk]) url = reverse("panel:impersonation_start", args=[customer.pk])
self.assertNotContains(self.client.get(self.all_users), url)
self.assertEqual(self.client.post(url).status_code, 404) self.assertEqual(self.client.post(url).status_code, 404)
Reseller.objects.create(user=self.alice) Reseller.objects.create(user=self.alice)
self.assertNotContains(self.client.get(self.all_users), self.start_url)
self.assertEqual(self.client.post(self.start_url).status_code, 404) self.assertEqual(self.client.post(self.start_url).status_code, 404)
self.assertFalse(CustomerImpersonation.objects.exists()) self.assertFalse(CustomerImpersonation.objects.exists())
+5
View File
@@ -685,6 +685,11 @@ urlpatterns = [
views.CustomerImpersonationStart.as_view(write_enabled=True), views.CustomerImpersonationStart.as_view(write_enabled=True),
name="impersonation_write_start", name="impersonation_write_start",
), ),
path(
"customers/<int:pk>/manage-as/",
views.CustomerImpersonationStart.as_view(managed_enabled=True),
name="impersonation_managed_start",
),
path( path(
"customer-view/end/", "customer-view/end/",
views.CustomerImpersonationStop.as_view(), views.CustomerImpersonationStop.as_view(),
+26 -20
View File
@@ -89,8 +89,10 @@ from .impersonation import (
EndReason, EndReason,
can_edit_customer_resource, can_edit_customer_resource,
can_impersonate_customer, can_impersonate_customer,
can_start_managed_support,
can_start_writable_support, can_start_writable_support,
end_impersonation, end_impersonation,
restricted_preview,
start_impersonation, start_impersonation,
support_write_session, support_write_session,
) )
@@ -699,7 +701,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
) )
context["manage_wordpress"] = wordpress_available() and ( context["manage_wordpress"] = wordpress_available() and (
getattr(self.request, "impersonation", None) is None not restricted_preview(self.request)
and can_manage_wordpress(user, self.object) and can_manage_wordpress(user, self.object)
) )
context["manage_website_jobs"] = can_access_website_jobs( context["manage_website_jobs"] = can_access_website_jobs(
@@ -715,7 +717,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
website_provisioning website_provisioning
and not self.object.services_suspended and not self.object.services_suspended
and can_manage_hosting(user, (CHANGE_ACCOUNTS,)) and can_manage_hosting(user, (CHANGE_ACCOUNTS,))
and getattr(self.request, "impersonation", None) is None and not restricted_preview(self.request)
) )
context["independent_websites"] = [ context["independent_websites"] = [
(website, website_actions(website) if can_manage else ()) (website, website_actions(website) if can_manage else ())
@@ -893,6 +895,14 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
"apache_config" "apache_config"
).order_by("-requested_at", "-pk") ).order_by("-requested_at", "-pk")
context["apache_history"] = list(history[:10]) context["apache_history"] = list(history[:10])
context["show_mailbox_rotation"] = show_rotation_action(
self.request, CredentialKind.MAILBOX
)
context["show_database_rotation"] = getattr(
self.request, "impersonation", None
) is not None and show_rotation_action(
self.request, CredentialKind.DATABASE
)
if getattr(self.request, "impersonation", None) is None: if getattr(self.request, "impersonation", None) is None:
context["show_database_credentials"] = show_credential_action( context["show_database_credentials"] = show_credential_action(
self.request, CredentialKind.DATABASE self.request, CredentialKind.DATABASE
@@ -900,9 +910,6 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["show_mailbox_credentials"] = show_credential_action( context["show_mailbox_credentials"] = show_credential_action(
self.request, CredentialKind.MAILBOX self.request, CredentialKind.MAILBOX
) )
context["show_mailbox_rotation"] = show_rotation_action(
self.request, CredentialKind.MAILBOX
)
context["show_phpmyadmin"] = context[ context["show_phpmyadmin"] = context[
"show_database_credentials" "show_database_credentials"
] and phpmyadmin_available(self.request) ] and phpmyadmin_available(self.request)
@@ -926,10 +933,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["databases"] = databases context["databases"] = databases
if tenant or user.has_perm(VIEW_DNS_ZONES): if tenant or user.has_perm(VIEW_DNS_ZONES):
zone_list = self.object.dns_zones.all() zone_list = self.object.dns_zones.all()
if ( if customer and not restricted_preview(self.request):
customer
and getattr(self.request, "impersonation", None) is None
):
zone_list = zone_list.select_related("publication").defer( zone_list = zone_list.select_related("publication").defer(
"publication__manifest" "publication__manifest"
) )
@@ -1060,9 +1064,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["change_mailbox_quota"] = ( context["change_mailbox_quota"] = (
not tenant and user.has_perms(CHANGE_MAILBOX_QUOTA) not tenant and user.has_perms(CHANGE_MAILBOX_QUOTA)
) )
elif customer is not None and not getattr( elif customer is not None and not restricted_preview(self.request):
self.request, "impersonation", None
):
context["customer_mailbox_quota"] = ( context["customer_mailbox_quota"] = (
panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING") panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
and customer_mailbox_quota_limit(self.object) is not None and customer_mailbox_quota_limit(self.object) is not None
@@ -2096,8 +2098,11 @@ class CustomerAccess(OperatorOnlyMixin, PermissionRequiredMixin, View):
class CustomerImpersonationStart(PermissionRequiredMixin, View): class CustomerImpersonationStart(PermissionRequiredMixin, View):
write_enabled = False write_enabled = False
managed_enabled = False
def has_permission(self): def has_permission(self):
if self.managed_enabled:
return can_start_managed_support(self.request.user)
if self.write_enabled: if self.write_enabled:
return can_start_writable_support(self.request.user) return can_start_writable_support(self.request.user)
return can_impersonate_customer(self.request.user) return can_impersonate_customer(self.request.user)
@@ -2108,7 +2113,10 @@ class CustomerImpersonationStart(PermissionRequiredMixin, View):
if not customer.may_be_impersonated: if not customer.may_be_impersonated:
raise Http404 raise Http404
start_impersonation( start_impersonation(
request, customer, write_enabled=self.write_enabled request,
customer,
write_enabled=self.write_enabled,
managed_enabled=self.managed_enabled,
) )
return redirect("panel:accounts") return redirect("panel:accounts")
@@ -2118,7 +2126,7 @@ class CustomerImpersonationStop(View):
session = getattr(request, "impersonation", None) session = getattr(request, "impersonation", None)
if session is not None: if session is not None:
end_impersonation(request, session, EndReason.STOPPED) end_impersonation(request, session, EndReason.STOPPED)
return redirect("panel:customers") return redirect("panel:all_users")
return redirect("panel:accounts") return redirect("panel:accounts")
@@ -2438,7 +2446,7 @@ class DnsZoneEdit(DnsZoneEditor):
if reseller_for_user(self.request.user) is not None: if reseller_for_user(self.request.user) is not None:
return False return False
if is_tenant(self.request.user): if is_tenant(self.request.user):
return getattr(self.request, "impersonation", None) is None and ( return not restricted_preview(self.request) and (
self.zone.delegate_dns self.zone.delegate_dns
and manages_account(self.request.user, self.account) and manages_account(self.request.user, self.account)
) )
@@ -2588,7 +2596,7 @@ class RequestDnsPublication(PermissionRequiredMixin, View):
if reseller_for_user(self.request.user) is not None: if reseller_for_user(self.request.user) is not None:
return False return False
if is_tenant(self.request.user): if is_tenant(self.request.user):
return getattr(self.request, "impersonation", None) is None return not restricted_preview(self.request)
return super().has_permission() return super().has_permission()
def post(self, request, pk): def post(self, request, pk):
@@ -2628,9 +2636,7 @@ class MailboxCreate(ResourceRequestCreate):
domain = self.request.GET.get("domain") domain = self.request.GET.get("domain")
if domain is None: if domain is None:
return None return None
if self.customer is None or getattr( if self.customer is None or restricted_preview(self.request):
self.request, "impersonation", None
):
raise Http404 raise Http404
from .domain_policies import managed_mail_domains from .domain_policies import managed_mail_domains
from .domain_services import allowed_domains from .domain_services import allowed_domains
@@ -2702,7 +2708,7 @@ class MailboxQuotaEdit(PermissionRequiredMixin, UpdateView):
return customer_for_user(self.request.user) return customer_for_user(self.request.user)
def has_permission(self): def has_permission(self):
if getattr(self.request, "impersonation", None): if restricted_preview(self.request):
return False return False
if self.customer is not None: if self.customer is not None:
return panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING") return panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
+2 -1
View File
@@ -24,6 +24,7 @@ from .access import (
can_manage_hosting, can_manage_hosting,
owns_customer_operations, owns_customer_operations,
) )
from .impersonation import restricted_preview
from .independent_websites import active_websites from .independent_websites import active_websites
from .installation_features import panel_feature_allowed from .installation_features import panel_feature_allowed
from .models import HostingAccount from .models import HostingAccount
@@ -39,7 +40,7 @@ def can_manage_website_files(request):
user = request.user user = request.user
return ( return (
panel_feature_allowed("WEB_FILE_MANAGER") panel_feature_allowed("WEB_FILE_MANAGER")
and getattr(request, "impersonation", None) is None and not restricted_preview(request)
and can_manage_hosting(user, MANAGE_FILES) and can_manage_hosting(user, MANAGE_FILES)
) )
+2 -1
View File
@@ -16,6 +16,7 @@ from coulobre.domain_names import canonical_domain
from .access import customer_for_user, is_tenant from .access import customer_for_user, is_tenant
from .certificate_views import account_certificate_sites, queue_certificate from .certificate_views import account_certificate_sites, queue_certificate
from .dns_forms import record_rows from .dns_forms import record_rows
from .impersonation import restricted_preview
from .independent_websites import account_websites from .independent_websites import account_websites
from .installation_features import panel_feature_allowed from .installation_features import panel_feature_allowed
from .models import HostingAccount, WebsiteAlias from .models import HostingAccount, WebsiteAlias
@@ -48,7 +49,7 @@ NOT_MAPPED = HostStatus("", "Not mapped to a website")
def may_manage_https(request, account): def may_manage_https(request, account):
if getattr(request, "impersonation", None): if restricted_preview(request):
return False return False
customer = customer_for_user(request.user) customer = customer_for_user(request.user)
if customer is not None: if customer is not None:
+2 -1
View File
@@ -20,6 +20,7 @@ from .access import (
can_manage_hosting, can_manage_hosting,
owns_customer_operations, owns_customer_operations,
) )
from .impersonation import restricted_preview
from .independent_websites import check_actor from .independent_websites import check_actor
from .installation_features import panel_feature_allowed from .installation_features import panel_feature_allowed
from .models import HostingAccount from .models import HostingAccount
@@ -35,7 +36,7 @@ MANAGE_JOBS = ("hosting.view_hostingaccount", "hosting.manage_website_jobs")
def can_access_website_jobs(request): def can_access_website_jobs(request):
impersonating = getattr(request, "impersonation", None) is not None impersonating = restricted_preview(request)
return not impersonating and can_manage_hosting(request.user, MANAGE_JOBS) return not impersonating and can_manage_hosting(request.user, MANAGE_JOBS)
+2 -1
View File
@@ -14,6 +14,7 @@ from coulobre.wordpress_import import inspect_export
from coulobre.wordpress_updates import WordPressUpdate from coulobre.wordpress_updates import WordPressUpdate
from .access import TenantScopeMixin, customer_for_user, is_tenant from .access import TenantScopeMixin, customer_for_user, is_tenant
from .impersonation import restricted_preview
from .installation_features import panel_feature_allowed from .installation_features import panel_feature_allowed
from .models import HostingAccount from .models import HostingAccount
from .wordpress_import_workflow import ( from .wordpress_import_workflow import (
@@ -136,7 +137,7 @@ class AccountWordPressView(
def has_permission(self): def has_permission(self):
return ( return (
not getattr(self.request, "impersonation", None) not restricted_preview(self.request)
and super().has_permission() and super().has_permission()
and can_manage_wordpress(self.request.user, self.get_object()) and can_manage_wordpress(self.request.user, self.get_object())
) )
+16 -4
View File
@@ -147,6 +147,12 @@ def customer_pages(request):
return pages return pages
def customer_account_key(request):
if getattr(request, "impersonation", None):
return "support_hosting_account"
return CUSTOMER_ACCOUNT
@require_safe @require_safe
@never_cache @never_cache
def customer_workspace(request, page): def customer_workspace(request, page):
@@ -165,10 +171,10 @@ def customer_workspace(request, page):
): ):
raise Http404 raise Http404
account = get_object_or_404(accounts, pk=int(selected)) account = get_object_or_404(accounts, pk=int(selected))
request.session[CUSTOMER_ACCOUNT] = account.pk request.session[customer_account_key(request)] = account.pk
else: else:
account = accounts.filter( account = accounts.filter(
pk=request.session.get(CUSTOMER_ACCOUNT) pk=request.session.get(customer_account_key(request))
).first() ).first()
account = account or accounts.first() account = account or accounts.first()
if account is None: if account is None:
@@ -336,7 +342,9 @@ def groups_for(request, *, customer, manager):
user = request.user user = request.user
if not user.is_authenticated: if not user.is_authenticated:
return () return ()
if getattr(request, "impersonation", None): from .impersonation import restricted_preview
if restricted_preview(request):
return (("Account Manager", [link("accounts", "My hosting")]),) return (("Account Manager", [link("accounts", "My hosting")]),)
if customer: if customer:
pages = customer_pages(request) pages = customer_pages(request)
@@ -378,7 +386,11 @@ def groups_for(request, *, customer, manager):
"Advanced Features", "Advanced Features",
[ [
*hosted("backups", "tasks"), *hosted("backups", "tasks"),
link("account_security", "Security"), *(
[]
if getattr(request, "impersonation", None)
else [link("account_security", "Security")]
),
], ],
), ),
] ]