From ec750b845319eaabbf5ac4220f84a3b9438ba133 Mon Sep 17 00:00:00 2001
From: Dominik George <dominik.george@teckids.org>
Date: Sat, 25 Dec 2021 13:31:50 +0100
Subject: [PATCH] Add tests to ensure LDAP authentication for vanished accoutns
 fails

---
 aleksis/core/tests/views/test_account.py | 44 ++++++++++++++++++++++++
 tox.ini                                  |  2 +-
 2 files changed, 45 insertions(+), 1 deletion(-)

diff --git a/aleksis/core/tests/views/test_account.py b/aleksis/core/tests/views/test_account.py
index 28686eabf..ae598ab72 100644
--- a/aleksis/core/tests/views/test_account.py
+++ b/aleksis/core/tests/views/test_account.py
@@ -1,10 +1,23 @@
 from django.conf import settings
+from django.test import override_settings
 from django.urls import reverse
 
+import ldap
 import pytest
+from django_auth_ldap.config import LDAPSearch
+
+from aleksis.core.models import UserAdditionalAttributes
 
 pytestmark = pytest.mark.django_db
 
+LDAP_BASE = "dc=example,dc=com"
+LDAP_SETTINGS = {
+    "AUTH_LDAP_GLOBAL_OPTIONS": {
+        ldap.OPT_NETWORK_TIMEOUT: 1,
+    },
+    "AUTH_LDAP_USER_SEARCH": LDAPSearch(LDAP_BASE, ldap.SCOPE_SUBTREE),
+}
+
 
 def test_index_not_logged_in(client):
     response = client.get("/")
@@ -40,3 +53,34 @@ def test_logout(client, django_user_model):
 
     assert response.status_code == 200
     assert "Please login to see this page." in response.content.decode("utf-8")
+
+
+@override_settings(
+    AUTHENTICATION_BACKENDS=[
+        "aleksis.core.util.ldap.LDAPBackend",
+        "django.contrib.auth.backends.ModelBackend",
+    ],
+    AUTH_LDAP_SERVER_URI="ldap://[100::0]",
+    AUTH_LDAP_SET_USABLE_PASSWORD=True,
+    **LDAP_SETTINGS
+)
+def test_login_ldap_fail_if_previously_ldap_authenticated(client, django_user_model):
+    username = "foo"
+    password = "bar"
+
+    django_user_model.objects.create_user(username=username, password=password)
+
+    # Logging in with a fresh account should success
+    res = client.login(username=username, password=password)
+    assert res
+    client.get(reverse("logout"), follow=True)
+
+    # Logging in with a previously LDAP-authenticated account should fail
+    UserAdditionalAttributes.set_user_attribute(username, "ldap_authenticated", True)
+    res = client.login(username=username, password=password)
+    assert not res
+
+    # Explicitly noting account has not been used with LDAP should succeed
+    UserAdditionalAttributes.set_user_attribute(username, "ldap_authenticated", False)
+    res = client.login(username=username, password=password)
+    assert res
diff --git a/tox.ini b/tox.ini
index 6ba5d926e..4819e5b95 100644
--- a/tox.ini
+++ b/tox.ini
@@ -9,7 +9,7 @@ whitelist_externals = poetry
 skip_install = true
 envdir = {toxworkdir}/globalenv
 commands_pre =
-     poetry install
+     poetry install -E ldap
      poetry run aleksis-admin yarn install
      poetry run aleksis-admin collectstatic --no-input
 commands =
-- 
GitLab