From 40d9be927bce645fb308df74c2a9aeb1a55a2709 Mon Sep 17 00:00:00 2001 From: martinusnel Date: Thu, 2 Jan 2025 16:34:38 +0000 Subject: [PATCH] Email passwords (#10) * adding an empty line to requirements for branch checking * Adding email notification on password reset --------- Co-authored-by: Peter Simm --- config/config-template.yaml | 3 +++ requirements.txt | 1 + src/runners/user_sync.py | 25 +++++++++++++++++++++++++ 3 files changed, 29 insertions(+) diff --git a/config/config-template.yaml b/config/config-template.yaml index b356d9f..f4288a0 100644 --- a/config/config-template.yaml +++ b/config/config-template.yaml @@ -4,6 +4,9 @@ settings: total_change_threshold: 50 deletions_change_threshold: 30 additions_change_threshold: 30 + email_for_password_notifications: 'email@example.com' + email_server: 'localhost' + email_port: 25 exception_file: 'config/exceptions.yaml' country_control_file: 'config/country_control.yaml' monitoring_log_file: 'monitoring.log' diff --git a/requirements.txt b/requirements.txt index 821fc67..fd0112e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,3 +3,4 @@ pyasn1 pyyaml unidecode loguru +email diff --git a/src/runners/user_sync.py b/src/runners/user_sync.py index 5c68c17..39ea329 100644 --- a/src/runners/user_sync.py +++ b/src/runners/user_sync.py @@ -8,6 +8,8 @@ import sys import copy import utils.utilities as Utilities +import smtplib +from email.mime.text import MIMEText from ldap3 import ( Connection, MODIFY_REPLACE, @@ -52,6 +54,27 @@ def __init__( self.ldap_connections = ldap_connections self._main() + def _email_password(self, user: str, password: str) -> None: + smtp_server = self.basic_config["config"]["settings"]["email_server"] + smtp_port = self.basic_config["config"]["settings"]["email_port"] + recipient_email = self.basic_config["config"]["settings"]["email_for_password_notifications"] + sender_email = recipient_email + subject = f"AD-LDAP Auto-password change notification for {user}" + body = f""" +The password for {user} has been automatically reset by the ad-to-ldap-sync process. The new password is: + +{password} + +Good luck! +""" + message = MIMEText(body) + message['From'] = sender_email + message['To'] = recipient_email + message['Subject'] = subject + + with smtplib.SMTP(smtp_server, smtp_port) as server: + server.sendmail(sender_email, recipient_email, message.as_string()) + def _get_user_attributes(self) -> dict[str, list[str]]: """Get the relevant user attributes. @@ -279,6 +302,8 @@ def _set_random_ldap_password( """ password = self._generate_password() + self._email_password(user, password) + for password_type in password_types: if password_type == "userPassword": # nosec B105 openldap_password = str(