From 574ce1f9821208baa71c85908ed0a86ff8cd9d8d Mon Sep 17 00:00:00 2001 From: Michael Weimann Date: Wed, 15 Sep 2021 19:16:45 +0200 Subject: [PATCH] implement ldap auth --- .flake8 | 1 + ki/auth.py | 27 ++++++++++++++++++++------- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/.flake8 b/.flake8 index 73a3a8e..daef5bf 100644 --- a/.flake8 +++ b/.flake8 @@ -3,6 +3,7 @@ # SPDX-License-Identifier: AGPL-3.0-or-later [flake8] +ignore = E722 max-line-length = 120 extend-exclude = migrations diff --git a/ki/auth.py b/ki/auth.py index 5dc7ae6..8b083bd 100644 --- a/ki/auth.py +++ b/ki/auth.py @@ -5,7 +5,8 @@ import uuid import yaml -from ldap3 import Server, Connection, ALL +from ldap3 import Server, Connection +from ldap3.utils.conv import escape_filter_chars from app import app, db from ki.models import User, Token @@ -46,18 +47,30 @@ def file_auth(username, password): def ldap_auth(username, password): app.logger.debug("performing LDAP authentication") - server = Server(app.config['KI_LDAP_URL'], get_info=ALL) - root_dn = app.config['KI_LDAP_ROOT_DN'] - ldap_user = f"cn={username},{root_dn}" + escaped_username = escape_filter_chars(username) + server = Server(app.config['KI_LDAP_URL']) - app.logger.debug(f"server: {server}") - connection = Connection(server, user=ldap_user, password=password) + try: + connection = Connection(server, + app.config['KI_LDAP_AUTH_USER'], + app.config['KI_LDAP_AUTH_PASSWORD'], + auto_bind=True) + except: + app.logger.error('ldap connection failed') + return None - if connection.bind(): + if not connection.search(app.config['KI_LDAP_BASE_DN'], f"(&(objectClass=inetOrgPerson)(uid={escaped_username}))"): + app.logger.info(f"ldap search of {username} failed") + return None + + user_dn = connection.entries[0].entry_dn + + if connection.rebind(user=user_dn, password=password): connection.unbind() return create_user_token(username) connection.unbind() + app.logger.info(f"ldap login of {username} failed") return None