diff --git a/.coveragerc b/.coveragerc index e3fd5b5..51616a7 100644 --- a/.coveragerc +++ b/.coveragerc @@ -13,7 +13,5 @@ omit = */admin.py */urls.py */apps.py - Users/views.py - Users/ldap_auth.py - Main/templatetags/form_tags.py + Users/ldap_errors.py \ No newline at end of file diff --git a/Instructor/views.py b/Instructor/views.py index 2ecd1b8..380e972 100644 --- a/Instructor/views.py +++ b/Instructor/views.py @@ -2,6 +2,7 @@ This file defines the back-end code that runs when a user requests a page for the Instructor app """ +from django.conf import settings from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import redirect @@ -10,7 +11,9 @@ from django.views.generic import View, ListView, TemplateView, CreateView, Updat from Main import models as main_models from Main.views import IsSuperUserMixin, FormNameMixin, FormAlertMixin, SuccessDeleteMixin -from Users.ldap_auth import LDAPAuthentication, LDAPAuthException +from Users.ldap_auth import LDAPAuthentication +from Users.ldap_errors import LDAPAuthException +from Users.ldap_mock import LDAPMockAuthentication from Users.models import User from . import models, forms @@ -37,8 +40,12 @@ class UserClearView(LoginRequiredMixin, IsSuperUserMixin, View): return redirect("user-list") else: try: - LDAPAuthentication().delete_old_users(self.request.user.username, password) + backend = LDAPMockAuthentication \ + if settings.AUTHENTICATION_BACKENDS[0] == "Users.ldap_mock.LDAPMockAuthentication" \ + else LDAPAuthentication + backend().delete_old_users(self.request.user.username, password) messages.add_message(self.request, messages.SUCCESS, "Users Cleared Successfully") + return redirect("user-list") except LDAPAuthException as error: messages.add_message(self.request, messages.ERROR, error.args[0]) return redirect("user-list") diff --git a/Users/ldap_auth.py b/Users/ldap_auth.py index 37b89ba..b27b209 100644 --- a/Users/ldap_auth.py +++ b/Users/ldap_auth.py @@ -12,30 +12,10 @@ from django.db.models import Q from ldap3 import Connection, Server, ALL, ObjectDef, Reader, NTLM, Entry from ldap3.core.exceptions import LDAPBindError, LDAPSocketOpenError +from .ldap_errors import LDAPConnectionError, LDAPInvalidCredentials, LDAPAuthException from .models import User -class LDAPAuthException(Exception): - """ - This exception is used to represent an error with authenticating through LDAP - """ - - pass - - -class LDAPInvalidCredentials(LDAPAuthException): - """ - This exception is used when the credentials provided are invalid - """ - pass - - -class LDAPConnectionError(LDAPAuthException): - """ - This exception is used when we can't contact ActiveDirectory - """ - - class LDAPAuthentication(BaseBackend): """ This authentication backend will log in the user to ldap and then create a User in the database @@ -63,7 +43,9 @@ class LDAPAuthentication(BaseBackend): return conn else: raise LDAPInvalidCredentials() - except (LDAPBindError, LDAPSocketOpenError): + except LDAPSocketOpenError: + raise LDAPConnectionError() + except LDAPBindError: raise LDAPConnectionError() @classmethod @@ -254,7 +236,7 @@ class LDAPAuthentication(BaseBackend): try: conn = self.get_connection(username, password) - ldap_user = self.get_ldap_user(conn, conn.extend.standard.who_am_i()) + ldap_user = self.get_ldap_user(conn, username) if self.check_user_is_admin(ldap_user): to_check = User.objects.filter(is_superuser=False).filter( Q(password__startswith='!') | Q(password__isnull=True)) diff --git a/Users/ldap_errors.py b/Users/ldap_errors.py new file mode 100644 index 0000000..9b4a748 --- /dev/null +++ b/Users/ldap_errors.py @@ -0,0 +1,25 @@ +""" + This file lists errors related to LDAP Authentication +""" + + +class LDAPAuthException(Exception): + """ + This exception is used to represent an error with authenticating through LDAP + """ + + pass + + +class LDAPInvalidCredentials(LDAPAuthException): + """ + This exception is used when the credentials provided are invalid + """ + + pass + + +class LDAPConnectionError(LDAPAuthException): + """ + This exception is used when we can't contact ActiveDirectory + """ diff --git a/Users/ldap_mock.py b/Users/ldap_mock.py new file mode 100644 index 0000000..53be40d --- /dev/null +++ b/Users/ldap_mock.py @@ -0,0 +1,112 @@ +""" + This file provides a fake ldap server to test with +""" + +from uuid import uuid4 + +from django.conf import settings +from ldap3 import Connection, Server, MOCK_SYNC, OFFLINE_AD_2012_R2 + +from .ldap_auth import LDAPAuthentication + + +class LDAPMockAuthentication(LDAPAuthentication): + """ + This class is a mock version of LDAPAuthentication meant for use in testing + *NEVER* **EVER** USE THIS IN PRODUCTION + """ + + server = Server('fake', get_info=OFFLINE_AD_2012_R2) + users = {} + + @staticmethod + def construct_dn(username, ou=None): + """ + This function constructs a distinguished name for a username + + :param username: The username of the user + :type username: str + :param ou: The optional Organizational Unit to include the user in + :type ou: str + :returns: The distinguished name of the user + :rtype: str + """ + if ou: + return f'cn={username},ou={ou},{settings.LDAP_BASE_CONTEXT}' + else: + return f'cn={username},{settings.LDAP_BASE_CONTEXT}' + + @classmethod + def extract_ou(cls, username): + """ + This function gets the organizational unit a test user is in from their username + + :param username: The username to get the ou for + :type username: str + :returns: The user's ou (if applicable) + :rtype: str + """ + + user = cls.users.get(username, {'ou': None}) + return user.get('ou') + + @classmethod + def create_fake_user(cls, conn: Connection, username, password, first, last, ou=None): + """ + This function creates a fake user to use in testing + + :param conn: The (fake) connection to create the user on + :type conn: Connection + :param username: The username of the user (domain\\username) + :type username: str + :param password: The password of the user + :type password: str + :param first: The first name of the user + :type first: str + :param last: The last name of the user + :type last: str + :param ou: The optional Organizational Unit to include the user in + :type ou: str + """ + + distinguished_name = cls.construct_dn(username, ou=ou) + conn.strategy.add_entry(distinguished_name, { + 'objectGUID': str(uuid4()), + 'objectClass': 'user', + 'distinguishedName': distinguished_name, + 'msDs-principalName': f"{settings.LDAP_DOMAIN}\\{username}", + 'userPassword': password, + 'givenName': first, + 'sn': last, + }) + + @classmethod + def create_fake_users(cls, conn): + """ + This function creates a series of fake users from a predefined list + + :param conn: The (fake) connection to create the users on + :type conn: Connection + """ + + for username in cls.users.keys(): + user = cls.users.get(username) + cls.create_fake_user(conn, username, user['password'], user['first'], user['last'], user['ou']) + + @classmethod + def get_connection(cls, username, password): + """ + This function overrides the base LDAPAuthentication function to provide a fake connection + instead of a real one + + :param username: The username to log in with (domain\\user) + :type username: str + :param password: The password to log in with + :type password: str + """ + + username = username.split('\\')[1] + conn = Connection(cls.server, cls.construct_dn(username, ou=cls.extract_ou(username)), password, + client_strategy=MOCK_SYNC) + cls.create_fake_users(conn) + return cls.bind_connection(conn) diff --git a/tests/test_auth.py b/tests/test_auth.py new file mode 100644 index 0000000..591b9aa --- /dev/null +++ b/tests/test_auth.py @@ -0,0 +1,140 @@ +from django.test import TestCase, override_settings +from django.urls import reverse + +from Users.ldap_mock import LDAPMockAuthentication +from Users.models import User + + +class LogoutTest(TestCase): + + def test_logout(self): + test_user = User.objects.create_user(username="test-user") + self.client.force_login(test_user) + self.client.get(reverse('logout')) + response = self.client.get(reverse('home')) + self.assertRedirects(response, f"{reverse('login')}?next=%2F") + + +@override_settings(AUTHENTICATION_BACKENDS=['Users.ldap_mock.LDAPMockAuthentication'], LDAP_DOMAIN="example", + LDAP_BASE_CONTEXT="ou=ITP Users,dc=itp,dc=example") +class LDAPAuthTest(TestCase): + url = reverse('login') + + def setUp(self) -> None: + LDAPMockAuthentication.users = { + 'admin': { + 'password': "admin_password123", + 'first': "Bob", + 'last': "Bobberson", + 'ou': None + }, + 'user_am': { + 'password': "am_user_password123", + 'first': "AMBob", + 'last': "AMBobberson", + 'ou': "AM" + }, + 'user_pm': { + 'password': "pm_user_password123", + 'first': "PMBob", + 'last': "PMBobberson", + 'ou': "PM" + }, + 'user_has_empty': { + 'password': "user_empty_password123", + 'first': "", + 'last': "", + 'ou': "AM" + } + } + + def test_admin_login(self) -> None: + self.client.post(self.url, {'username': "admin", "password": "admin_password123"}) + new_user = User.objects.get(username="example\\admin") + self.assertEqual(new_user.first_name, "Bob") + self.assertEqual(new_user.last_name, "Bobberson") + self.assertEqual(new_user.session, User.Session.AM) + self.assertTrue(new_user.is_superuser) + + def test_student_am_login(self) -> None: + self.client.post(self.url, {'username': "user_am", 'password': "am_user_password123"}) + new_user = User.objects.get(username="example\\user_am") + self.assertEqual(new_user.first_name, "AMBob") + self.assertEqual(new_user.last_name, "AMBobberson") + self.assertEqual(new_user.session, User.Session.AM) + self.assertFalse(new_user.is_superuser) + + def test_student_pm_login(self) -> None: + self.client.post(self.url, {'username': "user_pm", 'password': "pm_user_password123"}) + new_user = User.objects.get(username="example\\user_pm") + self.assertEqual(new_user.first_name, "PMBob") + self.assertEqual(new_user.last_name, "PMBobberson") + self.assertEqual(new_user.session, User.Session.PM) + self.assertFalse(new_user.is_superuser) + + def test_has_empty(self) -> None: + self.client.post(self.url, {'username': "user_has_empty", 'password': "user_empty_password123"}) + new_user = User.objects.get(username="example\\user_has_empty") + self.assertEqual(new_user.first_name, "") + self.assertEqual(new_user.last_name, "") + + def test_invalid(self) -> None: + response = self.client.post(self.url, {'username': "invalid_user", 'password': "invalid_password"}) + self.assertEqual(len(response.context.get('form').non_field_errors()), 1) + + def tearDown(self) -> None: + LDAPMockAuthentication.users = [] + + +@override_settings(AUTHENTICATION_BACKENDS=['Users.ldap_mock.LDAPMockAuthentication'], LDAP_DOMAIN="example", + LDAP_BASE_CONTEXT="ou=ITP Users,dc=itp,dc=example") +class UserCleanupTest(TestCase): + url = reverse('user-cleanup') + + def setUp(self) -> None: + LDAPMockAuthentication.users = { + 'admin': { + 'password': "admin_password123", + 'first': "First", + 'last': "Last", + 'ou': None + }, + 'student': { + 'password': "student_password123", + 'first': "SFirst", + 'last': "SLast", + 'ou': "AM" + } + } + self.client.post(reverse('login'), {'username': 'admin', 'password': "admin_password123"}) + self.client.post(reverse('login'), {'username': 'student', 'password': "student_password123"}) + self.old_user = User.objects.create_user(username='example\\old_user') + self.old_user.set_unusable_password() + self.old_user.save() + self.student = User.objects.get(username="example\\student") + self.client.force_login(User.objects.get(username="example\\admin")) + + def test_cleanup_users(self): + response = self.client.post(self.url, {'userPassword': "admin_password123"}) + self.assertRedirects(response, reverse('user-list')) + self.assertFalse(User.objects.filter(username="example\\old_user").exists()) + self.assertTrue(User.objects.filter(username="example\\student").exists()) + + def test_no_password(self): + self.client.post(self.url, {'userPassword': ""}) + self.assertTrue(User.objects.filter(username="example\\old_user").exists()) + self.assertTrue(User.objects.filter(username="example\\student").exists()) + + def test_password_wrong(self): + self.client.post(self.url, {'userPassword': "wrong password"}) + self.assertTrue(User.objects.filter(username="example\\old_user").exists()) + self.assertTrue(User.objects.filter(username="example\\student").exists()) + + def test_insufficient_perms(self): + self.client.force_login(self.student) + self.client.post(self.url, {'userPassword': "student_password123"}) + self.assertTrue(User.objects.filter(username="example\\old_user").exists()) + self.assertTrue(User.objects.filter(username="example\\student").exists()) + + def tearDown(self) -> None: + LDAPMockAuthentication.users = []