Improve user removal and feature setup guidance #196
No files matched your search
@@ -1,6 +1,6 @@
|
||||
from django import forms
|
||||
from django.contrib import messages
|
||||
from django.contrib.admin.models import ADDITION, LogEntry
|
||||
from django.contrib.admin.models import ADDITION, DELETION, LogEntry
|
||||
from django.contrib.auth import get_user_model, password_validation
|
||||
from django.contrib.auth.forms import UserCreationForm
|
||||
from django.contrib.auth.mixins import (
|
||||
@@ -10,9 +10,12 @@ from django.contrib.auth.mixins import (
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import IntegrityError, transaction
|
||||
from django.db.models import Count, Q
|
||||
from django.shortcuts import redirect
|
||||
from django.db.models.deletion import ProtectedError
|
||||
from django.http import Http404
|
||||
from django.shortcuts import get_object_or_404, redirect
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.utils.functional import cached_property
|
||||
from django.views.decorators.debug import sensitive_post_parameters
|
||||
from django.views.generic import FormView, ListView
|
||||
|
||||
@@ -341,17 +344,127 @@ class AllUsersView(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
|
||||
[profile.pk for profile in profiles if profile],
|
||||
operator=self.request.user,
|
||||
)
|
||||
actor = self.request.user
|
||||
context["login_rows"] = [
|
||||
(login, measurements.get(profile.pk) if profile else None)
|
||||
(
|
||||
login,
|
||||
measurements.get(profile.pk) if profile else None,
|
||||
deletable_profile(actor, login) is not None,
|
||||
)
|
||||
for login, profile in zip(context["logins"], profiles, strict=True)
|
||||
]
|
||||
actor = self.request.user
|
||||
context["may_manage_invitations"] = actor.has_perm(
|
||||
"hosting.change_customer"
|
||||
) or actor.has_perm("hosting.change_reseller")
|
||||
context["has_user_actions"] = context["may_manage_invitations"] or any(
|
||||
row[2] for row in context["login_rows"]
|
||||
)
|
||||
return context
|
||||
|
||||
|
||||
def deletable_profile(actor, login):
|
||||
if login.pk == actor.pk or login.is_staff or login.is_superuser:
|
||||
return None
|
||||
manager = getattr(login, "hosting_reseller", None)
|
||||
if manager is not None:
|
||||
if actor.has_perms(
|
||||
("hosting.view_reseller", "hosting.delete_reseller")
|
||||
):
|
||||
return manager
|
||||
return None
|
||||
if actor.has_perm("hosting.delete_customer"):
|
||||
return getattr(login, "hosting_customer", None)
|
||||
return None
|
||||
|
||||
|
||||
def deletion_blocker(profile):
|
||||
if profile.hostingaccount_set.exists():
|
||||
return (
|
||||
"This user still has hosting accounts. Reassign or retire those "
|
||||
"accounts before deleting the login."
|
||||
)
|
||||
if isinstance(profile, Reseller) and profile.managed_customers.exists():
|
||||
return (
|
||||
"This manager still has assigned customers. Reassign those "
|
||||
"customers before deleting the login."
|
||||
)
|
||||
return ""
|
||||
|
||||
|
||||
class UserDeletionForm(forms.Form):
|
||||
username = forms.CharField(label="Username", max_length=150)
|
||||
|
||||
|
||||
class UserDeleteView(OperatorOnlyMixin, PermissionRequiredMixin, FormView):
|
||||
permission_required = "hosting.view_customer"
|
||||
template_name = "hosting/user_delete.html"
|
||||
form_class = UserDeletionForm
|
||||
success_url = reverse_lazy("panel:all_users")
|
||||
|
||||
@cached_property
|
||||
def login(self):
|
||||
return get_object_or_404(
|
||||
get_user_model().objects.select_related(
|
||||
"hosting_customer", "hosting_reseller"
|
||||
),
|
||||
pk=self.kwargs["pk"],
|
||||
)
|
||||
|
||||
@cached_property
|
||||
def profile(self):
|
||||
profile = deletable_profile(self.request.user, self.login)
|
||||
if profile is None:
|
||||
raise Http404
|
||||
return profile
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
return super().get_context_data(
|
||||
login=self.login, blocker=deletion_blocker(self.profile), **kwargs
|
||||
)
|
||||
|
||||
def form_valid(self, form):
|
||||
actor = self.request.user
|
||||
try:
|
||||
with transaction.atomic():
|
||||
profiles = type(self.profile).objects.filter(
|
||||
pk=self.profile.pk
|
||||
)
|
||||
locked = (
|
||||
lock_resellers(profiles)
|
||||
if isinstance(self.profile, Reseller)
|
||||
else profiles.select_for_update()
|
||||
)
|
||||
profile = get_object_or_404(locked, user_id=self.login.pk)
|
||||
login = get_object_or_404(
|
||||
get_user_model().objects.select_for_update(),
|
||||
pk=self.login.pk,
|
||||
is_staff=False,
|
||||
is_superuser=False,
|
||||
)
|
||||
if login.get_username() != form.cleaned_data["username"]:
|
||||
form.add_error(
|
||||
"username", "Enter the username shown above."
|
||||
)
|
||||
return self.form_invalid(form)
|
||||
if blocker := deletion_blocker(profile):
|
||||
raise ValidationError(blocker)
|
||||
LogEntry.objects.log_actions(
|
||||
actor.pk, [login], DELETION, "Deleted panel login."
|
||||
)
|
||||
profile.delete()
|
||||
login.delete()
|
||||
except ValidationError as error:
|
||||
form.add_error(None, error)
|
||||
except ProtectedError:
|
||||
form.add_error(None, "The login still has linked records.")
|
||||
else:
|
||||
messages.success(self.request, "The user was deleted.")
|
||||
return super().form_valid(form)
|
||||
return self.render_to_response(
|
||||
self.get_context_data(form=form), status=409
|
||||
)
|
||||
|
||||
|
||||
class OperatorAuthorization(UserPassesTestMixin):
|
||||
def test_func(self):
|
||||
user = self.request.user
|
||||
|
||||
@@ -20,9 +20,9 @@
|
||||
<section class="surface">
|
||||
<div class="table-scroll">
|
||||
<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 may_manage_invitations %}<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>
|
||||
{% for login, usage in login_rows %}
|
||||
{% for login, usage, may_delete in login_rows %}
|
||||
<tr>
|
||||
<th scope="row">{{ login.get_username }}</th>
|
||||
<td>{% if login.is_superuser %}Operator{% elif login.hosting_reseller %}Manager{% else %}Customer{% endif %}</td>
|
||||
@@ -30,8 +30,9 @@
|
||||
<td>{{ login.account_count }}</td>
|
||||
{% include "hosting/account_metrics_cells.html" %}
|
||||
<td>{{ login.date_joined|date:"j M Y" }}</td>
|
||||
{% if may_manage_invitations %}
|
||||
{% if has_user_actions %}
|
||||
<td>
|
||||
<div class="form-actions">
|
||||
{% if not login.is_staff and not login.is_superuser %}
|
||||
{% if login.hosting_reseller and perms.hosting.change_reseller %}
|
||||
<a href="{% url 'panel:manage_invitation' 'manager' login.hosting_reseller.pk %}" aria-label="Contact and invitation for {{ login.get_username }}">Contact and invitation</a>
|
||||
@@ -39,10 +40,14 @@
|
||||
<a href="{% url 'panel:manage_invitation' 'customer' login.hosting_customer.pk %}" aria-label="Contact and invitation for {{ login.get_username }}">Contact and invitation</a>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% if may_delete %}
|
||||
<a href="{% url 'panel:user_delete' login.pk %}" aria-label="Delete user {{ login.get_username }}">Delete user</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</td>
|
||||
{% endif %}
|
||||
</tr>
|
||||
{% empty %}<tr><td colspan="{% if may_manage_invitations %}11{% else %}10{% endif %}">No logins found.</td></tr>{% endfor %}
|
||||
{% empty %}<tr><td colspan="{% if has_user_actions %}11{% else %}10{% endif %}">No logins found.</td></tr>{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
{% extends "hosting/workspace_page.html" %}
|
||||
{% block title %}Delete user · Coulobre Panel{% endblock %}
|
||||
{% block page_title %}Delete user{% endblock %}
|
||||
{% block page_context %}
|
||||
<a class="quiet-link" href="{% url 'panel:all_users' %}">← All users</a>
|
||||
{% endblock %}
|
||||
{% block page_content %}
|
||||
<section class="surface editor-surface">
|
||||
<h2>{{ login.get_username }}</h2>
|
||||
{% if blocker %}
|
||||
<p>{{ blocker }}</p>
|
||||
{% else %}
|
||||
<p>Deleting this user permanently removes their panel login, sign-in methods, and invitation. Type the username above to confirm.</p>
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
{{ form.as_div }}
|
||||
<div class="form-actions">
|
||||
<button class="button primary" type="submit">Delete user</button>
|
||||
<a class="button secondary" href="{% url 'panel:all_users' %}">Cancel</a>
|
||||
</div>
|
||||
</form>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -1,8 +1,9 @@
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.contrib.admin.models import DELETION, LogEntry
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.auth.models import Permission
|
||||
from django.test import TestCase, override_settings
|
||||
from django.test import Client, TestCase, override_settings
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||
@@ -11,12 +12,119 @@ from .models import (
|
||||
Customer,
|
||||
HostingAccount,
|
||||
HostingPlan,
|
||||
PanelInvitation,
|
||||
Reseller,
|
||||
WebsiteScheduledJob,
|
||||
WebsiteUsage,
|
||||
)
|
||||
|
||||
|
||||
class UserDeletionTests(TestCase):
|
||||
@classmethod
|
||||
def setUpTestData(cls):
|
||||
users = get_user_model().objects
|
||||
cls.operator = users.create_superuser("operator")
|
||||
cls.customer = Customer.objects.create(user=users.create_user("user"))
|
||||
cls.manager = Reseller.objects.create(
|
||||
user=users.create_user("manager")
|
||||
)
|
||||
|
||||
def setUp(self):
|
||||
self.client.force_login(self.operator)
|
||||
self.index = reverse("panel:all_users")
|
||||
self.delete = reverse(
|
||||
"panel:user_delete", args=[self.customer.user_id]
|
||||
)
|
||||
|
||||
def test_confirmation_deletes_only_the_login_and_audits_the_deletion(self):
|
||||
invite = PanelInvitation.objects.create(user=self.customer.user)
|
||||
other = HostingAccount.objects.create(
|
||||
name="Unrelated", primary_domain="unrelated.example"
|
||||
)
|
||||
self.assertContains(self.client.get(self.index), self.delete)
|
||||
self.assertContains(self.client.get(self.delete), "Type the username")
|
||||
response = self.client.post(self.delete, {"username": "wrong"})
|
||||
self.assertContains(response, "Enter the username shown above.")
|
||||
self.assertTrue(Customer.objects.filter(pk=self.customer.pk).exists())
|
||||
self.assertFalse(LogEntry.objects.exists())
|
||||
|
||||
self.assertRedirects(
|
||||
self.client.post(self.delete, {"username": "user"}), self.index
|
||||
)
|
||||
self.assertFalse(Customer.objects.filter(pk=self.customer.pk).exists())
|
||||
self.assertFalse(
|
||||
get_user_model().objects.filter(pk=self.customer.user_id).exists()
|
||||
)
|
||||
self.assertFalse(PanelInvitation.objects.filter(pk=invite.pk).exists())
|
||||
self.assertTrue(HostingAccount.objects.filter(pk=other.pk).exists())
|
||||
event = LogEntry.objects.get(action_flag=DELETION)
|
||||
self.assertEqual(event.user, self.operator)
|
||||
self.assertEqual(event.object_repr, "user")
|
||||
self.assertEqual(self.client.get(self.delete).status_code, 404)
|
||||
|
||||
def test_attached_hosting_added_after_preview_blocks_deletion(self):
|
||||
self.assertContains(self.client.get(self.delete), "Type the username")
|
||||
account = HostingAccount.objects.create(
|
||||
name="Owned",
|
||||
primary_domain="owned.example",
|
||||
customer=self.customer,
|
||||
)
|
||||
response = self.client.post(self.delete, {"username": "user"})
|
||||
self.assertContains(
|
||||
response, "still has hosting accounts", status_code=409
|
||||
)
|
||||
account.refresh_from_db()
|
||||
self.assertEqual(account.customer_id, self.customer.pk)
|
||||
self.assertFalse(LogEntry.objects.exists())
|
||||
|
||||
def test_manager_cannot_be_deleted_until_its_customers_are_reassigned(
|
||||
self,
|
||||
):
|
||||
self.customer.reseller = self.manager
|
||||
self.customer.save(update_fields=["reseller"])
|
||||
url = reverse("panel:user_delete", args=[self.manager.user_id])
|
||||
self.assertContains(self.client.get(self.index), url)
|
||||
self.assertContains(
|
||||
self.client.post(url, {"username": "manager"}),
|
||||
"still has assigned customers",
|
||||
status_code=409,
|
||||
)
|
||||
self.customer.refresh_from_db()
|
||||
self.assertEqual(self.customer.reseller, self.manager)
|
||||
self.customer.reseller = None
|
||||
self.customer.save(update_fields=["reseller"])
|
||||
self.assertRedirects(
|
||||
self.client.post(url, {"username": "manager"}), self.index
|
||||
)
|
||||
self.assertFalse(Reseller.objects.filter(pk=self.manager.pk).exists())
|
||||
|
||||
def test_permission_and_csrf_checks_apply_to_direct_submissions(self):
|
||||
operator_url = reverse("panel:user_delete", args=[self.operator.pk])
|
||||
self.assertNotContains(self.client.get(self.index), operator_url)
|
||||
self.assertEqual(
|
||||
self.client.post(
|
||||
operator_url, {"username": "operator"}
|
||||
).status_code,
|
||||
404,
|
||||
)
|
||||
browser = Client(enforce_csrf_checks=True)
|
||||
browser.force_login(self.operator)
|
||||
self.assertEqual(
|
||||
browser.post(self.delete, {"username": "user"}).status_code, 403
|
||||
)
|
||||
viewer = get_user_model().objects.create_user("viewer", is_staff=True)
|
||||
viewer.user_permissions.add(
|
||||
Permission.objects.get(codename="view_customer")
|
||||
)
|
||||
self.client.force_login(viewer)
|
||||
self.assertNotContains(self.client.get(self.index), self.delete)
|
||||
self.assertEqual(
|
||||
self.client.post(self.delete, {"username": "user"}).status_code,
|
||||
404,
|
||||
)
|
||||
self.assertTrue(Customer.objects.filter(pk=self.customer.pk).exists())
|
||||
|
||||
|
||||
class WorkspaceTests(TestCase):
|
||||
def test_operator_creates_and_links_the_first_hosting_account(self):
|
||||
users = get_user_model().objects
|
||||
|
||||
@@ -8,6 +8,7 @@ from .account_administration import (
|
||||
ManagerPackagesView,
|
||||
MoveHostingView,
|
||||
OperatorCreateView,
|
||||
UserDeleteView,
|
||||
)
|
||||
from .account_security import (
|
||||
AccountSecurityView,
|
||||
@@ -242,6 +243,9 @@ urlpatterns = [
|
||||
),
|
||||
path("system/<slug:page>/", system_workspace, name="system_workspace"),
|
||||
path("users/", AllUsersView.as_view(), name="all_users"),
|
||||
path(
|
||||
"users/<int:pk>/delete/", UserDeleteView.as_view(), name="user_delete"
|
||||
),
|
||||
path(
|
||||
"users/new/",
|
||||
CustomerOnboardingView.as_view(),
|
||||
|
||||
@@ -67,6 +67,7 @@ CUSTOMER_NAV_ROUTES = {
|
||||
}
|
||||
|
||||
WORKSPACE_PARENT_ROUTES = {
|
||||
"user_delete": ("all_users", ()),
|
||||
"remote_deploy": ("connected_nodes", ()),
|
||||
"dns_topology": ("dns_defaults", ()),
|
||||
"operator_settings": ("operator_settings", ("general",)),
|
||||
|
||||
Reference in new issue
Block a user