diff --git a/README.md b/README.md index 2a68e903..6462bd1b 100644 --- a/README.md +++ b/README.md @@ -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 `. +- 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 `. 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. diff --git a/accounts/lockout.py b/accounts/lockout.py index 0e4720d5..8bfa4785 100644 --- a/accounts/lockout.py +++ b/accounts/lockout.py @@ -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) diff --git a/accounts/templates/accounts/lockout.html b/accounts/templates/accounts/lockout.html new file mode 100644 index 00000000..485ef882 --- /dev/null +++ b/accounts/templates/accounts/lockout.html @@ -0,0 +1,25 @@ +{% extends "base.html" %} +{% load i18n %} + +{% block title %}{% trans "WebVirtCloud" %} - {% trans "Sign-in locked" %}{% endblock title %} + +{% block content %} +
+
+
+
+
+

{% trans "Sign-in locked" %}

+

+ {% 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 %} +

+ {% trans "Back to sign in" %} +
+
+
+
+{% endblock %} diff --git a/accounts/templates/accounts/otp_login.html b/accounts/templates/accounts/otp_login.html index 28fa5d48..89e45c50 100644 --- a/accounts/templates/accounts/otp_login.html +++ b/accounts/templates/accounts/otp_login.html @@ -16,6 +16,13 @@

{% trans "Enter your authentication code to continue" %}

+ {% if app_settings.LOGIN_NOTICE %} +
+ +
{{ app_settings.LOGIN_NOTICE }}
+
+ {% endif %} + {% if form.errors %} @@ -37,11 +44,12 @@
- -
+
{% trans "Caps Lock is on" %}
@@ -51,7 +59,7 @@
- +
{% trans "Leave empty if you have not set up two-factor authentication." %}
@@ -61,11 +69,6 @@ {% trans "Verify & Sign In" %} - -
- - {% trans "2FA Protection Active" %} -
diff --git a/accounts/templates/login.html b/accounts/templates/login.html index a9261a33..31f15213 100644 --- a/accounts/templates/login.html +++ b/accounts/templates/login.html @@ -15,6 +15,13 @@

{% trans "Virtualization Management Console" %}

+ {% if app_settings.LOGIN_NOTICE %} +
+ +
{{ app_settings.LOGIN_NOTICE }}
+
+ {% endif %} + {% if form.errors %} @@ -36,11 +43,12 @@
- -
+
{% trans "Caps Lock is on" %}
@@ -50,11 +58,6 @@ {% trans "Sign In" %} - -
- - KVM / Libvirt -
diff --git a/accounts/tests/test_login_page.py b/accounts/tests/test_login_page.py new file mode 100644 index 00000000..98196335 --- /dev/null +++ b/accounts/tests/test_login_page.py @@ -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 <22:00>") diff --git a/appsettings/migrations/0029_login_notice.py b/appsettings/migrations/0029_login_notice.py new file mode 100644 index 00000000..de535ad2 --- /dev/null +++ b/appsettings/migrations/0029_login_notice.py @@ -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)] diff --git a/appsettings/tests/test_appsettings.py b/appsettings/tests/test_appsettings.py index db7c04d9..c6474b40 100644 --- a/appsettings/tests/test_appsettings.py +++ b/appsettings/tests/test_appsettings.py @@ -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): diff --git a/appsettings/tests/test_migrations.py b/appsettings/tests/test_migrations.py index cc0c362d..93da3bbe 100644 --- a/appsettings/tests/test_migrations.py +++ b/appsettings/tests/test_migrations.py @@ -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") diff --git a/appsettings/views.py b/appsettings/views.py index 72ee341a..bfeeec8f 100644 --- a/appsettings/views.py +++ b/appsettings/views.py @@ -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"]), diff --git a/locale/tr/LC_MESSAGES/django.mo b/locale/tr/LC_MESSAGES/django.mo index 6a22f977..333554d7 100644 Binary files a/locale/tr/LC_MESSAGES/django.mo and b/locale/tr/LC_MESSAGES/django.mo differ diff --git a/locale/tr/LC_MESSAGES/django.po b/locale/tr/LC_MESSAGES/django.po index 43ba6403..ffc1204b 100644 --- a/locale/tr/LC_MESSAGES/django.po +++ b/locale/tr/LC_MESSAGES/django.po @@ -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" diff --git a/locale/zh/LC_MESSAGES/django.mo b/locale/zh/LC_MESSAGES/django.mo index 67874e48..600bd8c1 100644 Binary files a/locale/zh/LC_MESSAGES/django.mo and b/locale/zh/LC_MESSAGES/django.mo differ diff --git a/locale/zh/LC_MESSAGES/django.po b/locale/zh/LC_MESSAGES/django.po index 998fd860..7ce5daa5 100644 --- a/locale/zh/LC_MESSAGES/django.po +++ b/locale/zh/LC_MESSAGES/django.po @@ -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 "显示在登录表单上方,例如计划维护或使用条款;留空:不显示" diff --git a/static/js/login_form.js b/static/js/login_form.js index f03f9764..66e58779 100644 --- a/static/js/login_form.js +++ b/static/js/login_form.js @@ -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; diff --git a/webvirtcloud/settings.py b/webvirtcloud/settings.py index fc8b1e48..7811d069 100644 --- a/webvirtcloud/settings.py +++ b/webvirtcloud/settings.py @@ -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 = []