Add LDAP Aunthentication

This commit is contained in:
2026-08-06 18:17:33 +05:30
parent e7805b71a8
commit b380ed510b
11 changed files with 169 additions and 225 deletions

View File

@@ -1,6 +1,7 @@
from flask import current_app
from app.models.user_model import User
from app.services.db_service import db
from flask import current_app
from app.services.ldap_service import LDAPService
class UserService:
@@ -9,21 +10,57 @@ class UserService:
if User.query.filter_by(email=email).first():
return None
user = User(name=name, email=email)
user = User(name=name, email=email, auth_source="local")
user.set_password(password)
db.session.add(user)
db.session.commit()
current_app.logger.info("User list viewed")
return user
@staticmethod
def validate_login(email, password):
user = User.query.filter_by(email=email).first()
def validate_login(identifier, password):
"""
identifier = whatever was typed in the login form. Can be an email
(local users) or an LDAP username, depending on USE_LDAP_AUTH.
"""
if current_app.config.get("USE_LDAP_AUTH"):
ldap_user = UserService._validate_ldap_login(identifier, password)
if ldap_user:
return ldap_user
return None
user = User.query.filter_by(email=identifier).first()
if user and user.check_password(password):
return user
return None
@staticmethod
def _validate_ldap_login(username, password):
ldap_info = LDAPService.authenticate(username, password)
if not ldap_info:
return None
return UserService._get_or_create_ldap_user(ldap_info)
@staticmethod
def _get_or_create_ldap_user(ldap_info):
"""
LDAP is the source of truth for the password. We still keep a row in
our local `users` table (no password) so the rest of the app - which
expects a User with an id - keeps working unchanged.
"""
user = User.query.filter_by(email=ldap_info["email"]).first()
if user is None:
user = User(
name=ldap_info["name"],
email=ldap_info["email"],
auth_source="ldap",
)
db.session.add(user)
db.session.commit()
elif user.name != ldap_info["name"]:
user.name = ldap_info["name"]
db.session.commit()
return user
@staticmethod
def get_all_users():
return User.query.all()