1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 17:06:09 +00:00

feat(accounts): the sign-in page keeps the username, warns of Caps Lock and shows the lock and a notice

A locked user got django-axes' plain-text 429 reply, untranslated and with
no way back; it is now a page in the panel's layout that says within how
many minutes the lock ends, and leads back to the sign-in page with the
destination kept (AXES_LOCKOUT_CALLABLE).

A failed sign-in emptied the username; it is kept, the password is marked
invalid and has the cursor (a refused username keeps it). A line under the
password says when Caps Lock is on. The fields carry autocomplete
(username, current-password, one-time-code) for password managers and
phones, and the show-password button is reachable with Tab again.

The lines under the forms are gone: "KVM / Libvirt" with a green dot
looked like a status it did not check, and "2FA Protection Active" was
shown to users without 2FA.

A new setting, Sign-in notice (Settings, Login), is shown above both
sign-in forms when set, e.g. planned maintenance or a terms-of-use line.
This commit is contained in:
catborise 2026-11-20 22:04:42 +03:00
parent 67357c844a
commit 5d3280f9ea
16 changed files with 217 additions and 28 deletions

View file

@ -783,7 +783,7 @@ What an update from an older version changes for operators and users. `manage.py
- Requests for a host not in `ALLOWED_HOSTS` get 400. The installer writes the server's names and IPs; add more with the `ALLOWED_HOSTS` env var. The cloud-init datasource host must be allowed too.
- Logging out needs a POST; a GET to `/accounts/logout/` gets 405.
- The API accepts only a session from the login form or an API token (no HTTP Basic), and the API docs need a login. Sessions opened through the old password-only doors skip OTP; end them once after the update (everyone signs in again): `manage.py shell -c "from django.contrib.sessions.models import Session; Session.objects.all().delete()"`.
- Failed logins lock a user (django-axes). The limit and lock time are on the Settings page; unlock with `manage.py axes_reset_username <username>`.
- Failed logins lock a user (django-axes): the sign-in page then says how long. The limit and lock time are on the Settings page; unlock with `manage.py axes_reset_username <username>`. A sign-in notice set there (e.g. planned maintenance) is shown above the sign-in form.
- Changing one's own password is the "Can change password" permission (per user or group; new users have it); `SHOW_PROFILE_EDIT_PASSWORD` is gone.
- The admin's first-login password change survives losing `data/admin_password` (migration `accounts.0007`); run `migrate` as a user who can read that file.
- A new VM and each clone get a random VNC password of their own (clones no longer share their source's). The console page sends it for a user with **Open a console without the VM's console password**, which a new user has unless unticked; others are asked for it. Existing VMs keep theirs.

View file

@ -8,6 +8,7 @@ from ipaddress import ip_address, ip_network
from appsettings.models import AppSettings
from django.conf import settings
from django.shortcuts import render
DEFAULT_FAILURE_LIMIT = 5
DEFAULT_LOCKOUT_MINUTES = 15
@ -52,3 +53,9 @@ def client_ip(request):
remote = request.META.get("REMOTE_ADDR", "")
real_ip = request.META.get("HTTP_X_REAL_IP", "").strip()
return real_ip if real_ip and _from_trusted_proxy(remote) else remote
def lockout_response(request, original_response, credentials):
"""AXES_LOCKOUT_CALLABLE: the locked sign-in page, with the lock time."""
minutes = cooloff_time(request) // timedelta(minutes=1)
return render(request, "accounts/lockout.html", {"minutes": minutes}, status=429)

View file

@ -0,0 +1,25 @@
{% extends "base.html" %}
{% load i18n %}
{% block title %}{% trans "WebVirtCloud" %} - {% trans "Sign-in locked" %}{% endblock title %}
{% block content %}
<div class="row justify-content-center pt-5">
<div class="col-sm-9 col-md-7 col-lg-6">
<div class="card shadow-sm">
<div class="card-body p-4 p-sm-5 text-center">
<div class="d-inline-block rounded-3 text-bg-warning fs-2 lh-1 p-3 mb-3"><i class="bi bi-lock"></i></div>
<h1 class="h3 fw-bold mb-3">{% trans "Sign-in locked" %}</h1>
<p class="mb-4">
{% blocktrans trimmed count minutes=minutes %}
Too many failed sign-ins. The lock ends within {{ minutes }} minute.
{% plural %}
Too many failed sign-ins. The lock ends within {{ minutes }} minutes.
{% endblocktrans %}
</p>
<a href="{% url 'accounts:login' %}{% if request.GET.next %}?next={{ request.GET.next|urlencode }}{% endif %}" class="btn btn-primary w-100 py-2">{% trans "Back to sign in" %}</a>
</div>
</div>
</div>
</div>
{% endblock %}

View file

@ -16,6 +16,13 @@
<p class="text-body-secondary small mb-0">{% trans "Enter your authentication code to continue" %}</p>
</div>
{% if app_settings.LOGIN_NOTICE %}
<div class="alert alert-info d-flex align-items-center mb-4" role="note">
<i class="bi bi-info-circle-fill fs-5 me-2 flex-shrink-0"></i>
<div>{{ app_settings.LOGIN_NOTICE }}</div>
</div>
{% endif %}
{% if form.errors %}
<div class="alert alert-danger d-flex align-items-center mb-4" role="alert">
<i class="bi bi-exclamation-triangle-fill fs-5 me-2 flex-shrink-0"></i>
@ -29,7 +36,7 @@
<label class="form-label small fw-medium" for="id_username">{% trans "Username" %}</label>
<div class="input-group">
<span class="input-group-text"><i class="bi bi-person"></i></span>
<input type="text" id="id_username" class="form-control" name="username" value="{{ form.username.value|default:'' }}" placeholder="{% trans 'Enter username' %}" autocapitalize="none" autocorrect="off" required>
<input type="text" id="id_username" class="form-control" name="username" value="{{ form.username.value|default:'' }}" placeholder="{% trans 'Enter username' %}" autocomplete="username" autocapitalize="none" autocorrect="off" {% if not form.non_field_errors %}autofocus {% endif %}required>
</div>
</div>
@ -37,11 +44,12 @@
<label class="form-label small fw-medium" for="id_password">{% trans "Password" %}</label>
<div class="input-group">
<span class="input-group-text"><i class="bi bi-shield-lock"></i></span>
<input type="password" id="id_password" class="form-control" name="password" placeholder="{% trans 'Enter password' %}" required>
<button class="btn btn-outline-secondary" type="button" id="btn-toggle-pwd" tabindex="-1" aria-label="{% trans 'Toggle password visibility' %}">
<input type="password" id="id_password" class="form-control" name="password" placeholder="{% trans 'Enter password' %}" autocomplete="current-password" {% if form.non_field_errors %}autofocus {% endif %}required>
<button class="btn btn-outline-secondary" type="button" id="btn-toggle-pwd" aria-label="{% trans 'Toggle password visibility' %}">
<i class="bi bi-eye" id="toggle-icon"></i>
</button>
</div>
<div id="caps-lock" class="form-text d-none"><i class="bi bi-capslock-fill text-warning me-1"></i>{% trans "Caps Lock is on" %}</div>
</div>
<div class="mb-4">
@ -51,7 +59,7 @@
</div>
<div class="input-group">
<span class="input-group-text"><i class="bi bi-key"></i></span>
<input type="text" id="id_otp_token" class="form-control font-monospace" name="otp_token" placeholder="000000" inputmode="numeric" pattern="[0-9]*" maxlength="6" autofocus>
<input type="text" id="id_otp_token" class="form-control font-monospace" name="otp_token" placeholder="000000" inputmode="numeric" pattern="[0-9]*" maxlength="6" autocomplete="one-time-code">
</div>
<div class="form-text">{% trans "Leave empty if you have not set up two-factor authentication." %}</div>
</div>
@ -61,11 +69,6 @@
<span id="btn-text">{% trans "Verify & Sign In" %}</span>
</button>
</form>
<div class="d-flex align-items-center small text-body-secondary border-top mt-4 pt-3">
<span class="d-inline-block rounded-circle p-1 bg-success me-2" aria-hidden="true"></span>
{% trans "2FA Protection Active" %}
</div>
</div>
</div>
</div>

View file

@ -15,6 +15,13 @@
<p class="text-body-secondary small mb-0">{% trans "Virtualization Management Console" %}</p>
</div>
{% if app_settings.LOGIN_NOTICE %}
<div class="alert alert-info d-flex align-items-center mb-4" role="note">
<i class="bi bi-info-circle-fill fs-5 me-2 flex-shrink-0"></i>
<div>{{ app_settings.LOGIN_NOTICE }}</div>
</div>
{% endif %}
{% if form.errors %}
<div class="alert alert-danger d-flex align-items-center mb-4" role="alert">
<i class="bi bi-exclamation-triangle-fill fs-5 me-2 flex-shrink-0"></i>
@ -28,7 +35,7 @@
<label class="form-label small fw-medium" for="id_username">{% trans "Username" %}</label>
<div class="input-group">
<span class="input-group-text"><i class="bi bi-person"></i></span>
<input type="text" id="id_username" class="form-control" name="username" placeholder="{% trans 'Enter username' %}" autocapitalize="none" autocorrect="off" autofocus required>
<input type="text" id="id_username" class="form-control" name="username" value="{{ form.username.value|default:'' }}" placeholder="{% trans 'Enter username' %}" autocomplete="username" autocapitalize="none" autocorrect="off" {% if not form.non_field_errors %}autofocus {% endif %}required>
</div>
</div>
@ -36,11 +43,12 @@
<label class="form-label small fw-medium" for="id_password">{% trans "Password" %}</label>
<div class="input-group">
<span class="input-group-text"><i class="bi bi-shield-lock"></i></span>
<input type="password" id="id_password" class="form-control" name="password" placeholder="{% trans 'Enter password' %}" required>
<button class="btn btn-outline-secondary" type="button" id="btn-toggle-pwd" tabindex="-1" aria-label="{% trans 'Toggle password visibility' %}">
<input type="password" id="id_password" class="form-control{% if form.non_field_errors %} is-invalid{% endif %}" name="password" placeholder="{% trans 'Enter password' %}" autocomplete="current-password" {% if form.non_field_errors %}autofocus {% endif %}required>
<button class="btn btn-outline-secondary" type="button" id="btn-toggle-pwd" aria-label="{% trans 'Toggle password visibility' %}">
<i class="bi bi-eye" id="toggle-icon"></i>
</button>
</div>
<div id="caps-lock" class="form-text d-none"><i class="bi bi-capslock-fill text-warning me-1"></i>{% trans "Caps Lock is on" %}</div>
</div>
<input type="hidden" name="next" value="{{ next }}">
@ -50,11 +58,6 @@
<span id="btn-text">{% trans "Sign In" %}</span>
</button>
</form>
<div class="d-flex align-items-center small text-body-secondary border-top mt-4 pt-3">
<span class="d-inline-block rounded-circle p-1 bg-success me-2" aria-hidden="true"></span>
KVM / Libvirt
</div>
</div>
</div>
</div>

View file

@ -0,0 +1,56 @@
"""The sign-in page: a failed sign-in keeps the username and puts the cursor
on the password, a locked user gets a page with the lock time, and the
administrator's notice from the Settings page is shown above the form."""
from appsettings.models import AppSettings
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.urls import reverse
@override_settings(OTP_ENABLED=False)
class LoginPageTests(TestCase):
def setUp(self):
get_user_model().objects.create_user("lp-user", password="right-pass-1")
def login(self, password, username="lp-user", url=None):
return self.client.post(url or reverse("accounts:login"), {"username": username, "password": password})
def test_a_failed_sign_in_keeps_the_username_and_marks_the_password(self):
page = self.login("wrong").content.decode()
self.assertIn('value="lp-user"', page)
self.assertRegex(page, r'id="id_password" class="form-control is-invalid"[^>]*autofocus')
self.assertNotRegex(page, r'id="id_username"[^>]*autofocus')
def test_a_username_error_keeps_the_cursor_on_the_username(self):
page = self.login("right-pass-1", username="u" * 151).content.decode()
self.assertRegex(page, r'id="id_username"[^>]*autofocus')
self.assertNotIn("is-invalid", page)
def test_the_lock_page_links_back_with_the_destination(self):
AppSettings.objects.filter(key="LOGIN_FAILURE_LIMIT").update(value="1")
url = reverse("accounts:login") + "?next=/computes/"
self.login("wrong", url=url)
self.assertContains(self.login("wrong", url=url), 'href="%s?next=/computes/"' % reverse("accounts:login"),
status_code=429)
def test_the_empty_page_focuses_the_username(self):
page = self.client.get(reverse("accounts:login")).content.decode()
self.assertRegex(page, r'id="id_username"[^>]*autocomplete="username"[^>]*autofocus')
self.assertIn('autocomplete="current-password"', page)
self.assertIn('id="caps-lock"', page)
def test_a_locked_user_gets_the_lock_page_with_the_lock_time(self):
AppSettings.objects.filter(key="LOGIN_FAILURE_LIMIT").update(value="2")
AppSettings.objects.filter(key="LOGIN_LOCKOUT_MINUTES").update(value="20")
self.login("wrong")
self.login("wrong")
response = self.login("right-pass-1")
self.assertEqual(response.status_code, 429)
self.assertTemplateUsed(response, "accounts/lockout.html")
self.assertContains(response, "The lock ends within 20 minutes.", status_code=429)
def test_the_notice_is_shown_only_when_set(self):
self.assertNotContains(self.client.get(reverse("accounts:login")), "alert-info")
AppSettings.objects.filter(key="LOGIN_NOTICE").update(value="Maintenance at <22:00>")
self.assertContains(self.client.get(reverse("accounts:login")), "Maintenance at &lt;22:00&gt;")

View file

@ -0,0 +1,29 @@
from django.core.management.color import no_style
from django.db import migrations
from django.utils.translation import gettext_noop as _
SETTING = (_("Sign-in notice"), "LOGIN_NOTICE", "",
_("Shown above the sign-in form, e.g. planned maintenance or a terms-of-use line; empty: none"))
def add_setting(apps, schema_editor):
setting = apps.get_model("appsettings", "AppSettings")
db_alias = schema_editor.connection.alias
# see 0014: move a PostgreSQL id sequence past the fixed ids first
with schema_editor.connection.cursor() as cursor:
for sql in schema_editor.connection.ops.sequence_reset_sql(no_style(), [setting]):
cursor.execute(sql)
name, key, value, description = SETTING
setting.objects.using(db_alias).get_or_create(
key=key, defaults={"name": name, "value": value, "choices": "", "description": description})
def del_setting(apps, schema_editor):
apps.get_model("appsettings", "AppSettings").objects.using(schema_editor.connection.alias).filter(
key=SETTING[1]).delete()
class Migration(migrations.Migration):
dependencies = [("appsettings", "0028_migration_bandwidth")]
operations = [migrations.RunPython(add_setting, del_setting)]

View file

@ -218,7 +218,7 @@ class AppSettingsTestCase(TestCase):
AppSettings.objects.filter(key="LOGIN_FAILURE_LIMIT").update(value="10")
self.client.post(reverse("appsettings"), {"LOGIN_FAILURE_LIMIT": "5", "was-LOGIN_FAILURE_LIMIT": "5",
"LOGIN_LOCKOUT_MINUTES": "30", "was-LOGIN_LOCKOUT_MINUTES": "15"})
values = dict(AppSettings.objects.filter(key__startswith="LOGIN_").values_list("key", "value"))
values = dict(AppSettings.objects.filter(key__in=["LOGIN_FAILURE_LIMIT", "LOGIN_LOCKOUT_MINUTES"]).values_list("key", "value"))
self.assertEqual(values, {"LOGIN_FAILURE_LIMIT": "10", "LOGIN_LOCKOUT_MINUTES": "30"})
def test_a_failed_save_changes_none_of_its_group(self):

View file

@ -28,7 +28,7 @@ class SequenceAfterFixedIdsTestCase(TransactionTestCase):
with connection.cursor() as cursor:
cursor.execute("SELECT setval(pg_get_serial_sequence('appsettings_appsettings', 'id'), 1, false)")
login_lockout.add_settings(apps, schema_editor)
self.assertEqual(AppSettings.objects.filter(key__startswith="LOGIN_").count(), 2)
self.assertEqual(AppSettings.objects.filter(key__in=["LOGIN_FAILURE_LIMIT", "LOGIN_LOCKOUT_MINUTES"]).count(), 2)
nic_type = importlib.import_module("appsettings.migrations.0016_nic_type_rtl8139")

View file

@ -57,7 +57,7 @@ GROUPS = [
(gettext_noop("Snapshots and jobs"), ["SNAPSHOT_FREE_SPACE_PERCENT", "SNAPSHOT_FREE_SPACE_MIN_GIB",
"WORKER_CONCURRENCY", "JOB_RETENTION_DAYS"]),
(gettext_noop("Migrations"), ["MIGRATION_BANDWIDTH"]),
(gettext_noop("Login"), ["LOGIN_FAILURE_LIMIT", "LOGIN_LOCKOUT_MINUTES"]),
(gettext_noop("Login"), ["LOGIN_FAILURE_LIMIT", "LOGIN_LOCKOUT_MINUTES", "LOGIN_NOTICE"]),
(gettext_noop("Alerts"), ["ALERT_EMAILS", "ALERT_WEBHOOK"]),
(gettext_noop("Lists and pages"), ["VIEW_INSTANCES_LIST_STYLE", "VM_DRBD_STATUS", "LOGS_PER_PAGE",
"LOG_RETENTION_DAYS"]),

Binary file not shown.

View file

@ -419,9 +419,6 @@ msgstr "Doğrulanıyor..."
msgid "Verify & Sign In"
msgstr "Doğrula ve oturum aç"
#: accounts/templates/accounts/otp_login.html:67
msgid "2FA Protection Active"
msgstr "2FA Koruması Etkin"
#: accounts/templates/accounts/otp_qr.html:4
#: accounts/templates/accounts/otp_qr.html:6 accounts/utils.py:66
@ -13020,3 +13017,33 @@ msgstr "Yerel sunucu"
#: webvirtcloud/settings.py:346
msgid "All interfaces"
msgstr "Tüm arabirimler"
#: accounts/templates/accounts/lockout.html:4
#: accounts/templates/accounts/lockout.html:12
msgid "Sign-in locked"
msgstr "Oturum açma kilitlendi"
#: accounts/templates/accounts/lockout.html:14
#, python-format
msgid "Too many failed sign-ins. The lock ends within %(minutes)s minute."
msgid_plural "Too many failed sign-ins. The lock ends within %(minutes)s minutes."
msgstr[0] "Çok fazla başarısız oturum açma denemesi. Kilit en geç %(minutes)s dakika içinde kalkar."
msgstr[1] "Çok fazla başarısız oturum açma denemesi. Kilit en geç %(minutes)s dakika içinde kalkar."
#: accounts/templates/accounts/lockout.html:20
msgid "Back to sign in"
msgstr "Oturum açmaya dön"
#: accounts/templates/accounts/otp_login.html:52 accounts/templates/login.html:51
msgid "Caps Lock is on"
msgstr "Caps Lock açık"
#: appsettings/migrations/0029_login_notice.py:5
msgid "Sign-in notice"
msgstr "Oturum açma duyurusu"
#: appsettings/migrations/0029_login_notice.py:6
msgid ""
"Shown above the sign-in form, e.g. planned maintenance or a terms-of-use "
"line; empty: none"
msgstr "Oturum açma formunun üstünde gösterilir; örneğin planlı bakım ya da kullanım koşulları satırı; boş: yok"

Binary file not shown.

View file

@ -414,9 +414,6 @@ msgstr "正在验证…"
msgid "Verify & Sign In"
msgstr "验证并登录"
#: accounts/templates/accounts/otp_login.html:67
msgid "2FA Protection Active"
msgstr "双因素保护已启用"
#: accounts/templates/accounts/otp_qr.html:4
#: accounts/templates/accounts/otp_qr.html:6 accounts/utils.py:66
@ -12193,3 +12190,32 @@ msgstr "本机"
#: webvirtcloud/settings.py:346
msgid "All interfaces"
msgstr "所有接口"
#: accounts/templates/accounts/lockout.html:4
#: accounts/templates/accounts/lockout.html:12
msgid "Sign-in locked"
msgstr "登录已锁定"
#: accounts/templates/accounts/lockout.html:14
#, python-format
msgid "Too many failed sign-ins. The lock ends within %(minutes)s minute."
msgid_plural "Too many failed sign-ins. The lock ends within %(minutes)s minutes."
msgstr[0] "登录失败次数过多。锁定将在 %(minutes)s 分钟内解除。"
#: accounts/templates/accounts/lockout.html:20
msgid "Back to sign in"
msgstr "返回登录"
#: accounts/templates/accounts/otp_login.html:52 accounts/templates/login.html:51
msgid "Caps Lock is on"
msgstr "大写锁定已开启"
#: appsettings/migrations/0029_login_notice.py:5
msgid "Sign-in notice"
msgstr "登录提示"
#: appsettings/migrations/0029_login_notice.py:6
msgid ""
"Shown above the sign-in form, e.g. planned maintenance or a terms-of-use "
"line; empty: none"
msgstr "显示在登录表单上方,例如计划维护或使用条款;留空:不显示"

View file

@ -1,5 +1,6 @@
// The sign-in forms (login, OTP login): the eye button shows or hides the
// password; while the form is sent, its button is disabled and says so.
// password, a line says when Caps Lock is on, and while the form is sent its
// button is disabled and says so.
document.getElementById("btn-toggle-pwd").addEventListener("click", function () {
var password = document.getElementById("id_password");
var shown = password.type === "password";
@ -9,6 +10,17 @@ document.getElementById("btn-toggle-pwd").addEventListener("click", function ()
icon.classList.toggle("bi-eye-slash", shown);
});
["keydown", "keyup"].forEach(function (type) {
document.getElementById("id_password").addEventListener(type, function (event) {
var on = event.getModifierState && event.getModifierState("CapsLock");
document.getElementById("caps-lock").classList.toggle("d-none", !on);
});
});
// Caps Lock may change elsewhere: the line waits for the next key here
document.getElementById("id_password").addEventListener("blur", function () {
document.getElementById("caps-lock").classList.add("d-none");
});
document.getElementById("form-signin").addEventListener("submit", function () {
var button = document.getElementById("btn-signin");
button.disabled = true;

View file

@ -220,6 +220,7 @@ AXES_RESET_ON_SUCCESS = True
# successful logins are on the Logs page; django-axes' own record of them would only grow
AXES_DISABLE_ACCESS_LOG = True
AXES_CLIENT_IP_CALLABLE = "accounts.lockout.client_ip"
AXES_LOCKOUT_CALLABLE = "accounts.lockout.lockout_response"
# Reverse proxies other than a local one whose X-Real-IP header gives the
# client address, e.g. ["10.0.0.5", "172.18.0.0/16"]
LOGIN_TRUSTED_PROXIES = []