diff --git a/app/commands.py b/app/commands.py index 2ff6dd6b294e58f06521ce9ef505db46502f98e8..164cbb0d5eb1339b2eed32d19d8226d9274a9a6a 100644 --- a/app/commands.py +++ b/app/commands.py @@ -22,6 +22,15 @@ from .tasks import TaskWorker from . import models, utils, tokens +def disable_user(user): + """Clear users'groups, email and tokens""" + user.groups = [] + user.email = "" + # Revoke all user's tokens + for token in user.tokens: + db.session.delete(token) + + def sync_user(connection, user): """Synchronize the user from the database with information from the LDAP server""" search_attr = current_app.config.get("LDAP_USER_LOGIN_ATTR") @@ -33,26 +42,33 @@ def sync_user(connection, user): search_scope=getattr(ldap3, current_app.config.get("LDAP_USER_SEARCH_SCOPE")), attributes=current_app.config.get("LDAP_GET_USER_ATTRIBUTES"), ) - if len(connection.response) == 1: - ldap_user = connection.response[0] - attributes = ldap_user["attributes"] - user.display_name = utils.attribute_to_string(attributes["cn"]) - user.email = utils.attribute_to_string(attributes["mail"]) - groups = ldap_manager.get_user_groups( - dn=ldap3.utils.conv.escape_filter_chars(ldap_user["dn"]), - _connection=connection, - ) - user.groups = sorted( - [utils.attribute_to_string(group["cn"]) for group in groups] - ) - current_app.logger.info(f"{user} updated") + results = [ + result for result in connection.response if result["type"] == "searchResEntry" + ] + if len(results) == 1: + ldap_user = results[0] + # OU=InActiveUsers is specific to ESS AD + if "OU=InActiveUsers" in ldap_user["dn"]: + current_app.logger.info(f"{user} is inactive. User disabled.") + disable_user(user) + else: + attributes = ldap_user["attributes"] + user.display_name = utils.attribute_to_string(attributes["cn"]) + user.email = utils.attribute_to_string(attributes["mail"]) + groups = ldap_manager.get_user_groups( + dn=ldap3.utils.conv.escape_filter_chars(ldap_user["dn"]), + _connection=connection, + ) + user.groups = sorted( + [utils.attribute_to_string(group["cn"]) for group in groups] + ) + current_app.logger.info(f"{user} updated") + elif len(results) == 0: + current_app.logger.warning(f"{user} not found! User disabled.") + disable_user(user) else: - # Clear user's groups - user.groups = [] - # Revoke all user's tokens - for token in user.tokens: - db.session.delete(token) - current_app.logger.info(f"{user} disabled") + current_app.logger.warning(f"Too many results for {user}!") + current_app.logger.warning(f"results: {results}") return user