forked from kompetenzinventar/ki-backend
implement ldap auth
This commit is contained in:
parent
b49a319848
commit
574ce1f982
1
.flake8
1
.flake8
@ -3,6 +3,7 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
[flake8]
|
||||
ignore = E722
|
||||
max-line-length = 120
|
||||
extend-exclude =
|
||||
migrations
|
||||
|
27
ki/auth.py
27
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
|
||||
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user