Files
ynh-create-user-script/main.py
2025-02-15 12:37:05 +01:00

143 lines
3.4 KiB
Python

import argparse
import os
import secrets
import smtplib
import string
import subprocess
import sys
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def generate_password(length: int) -> str:
alphabet = string.ascii_letters + string.digits
password = "".join(secrets.choice(alphabet) for i in range(length))
return password
def send_email(
sender_email,
receiver_email,
subject,
message,
smtp_username,
smtp_password,
):
# Create a multipart message
msg = MIMEMultipart()
msg["From"] = sender_email
msg["To"] = receiver_email
msg["Subject"] = subject
# Add body to the email
msg.attach(MIMEText(message, "plain"))
try:
# Create a secure SSL/TLS connection to the SMTP server
server = smtplib.SMTP("localhost", 25)
server.ehlo()
server.starttls()
server.ehlo()
# Login to the SMTP server
server.login(smtp_username, smtp_password)
# Send the email
server.sendmail(sender_email, receiver_email, msg.as_string())
# Close the SMTP connection
server.quit()
print("Email sent successfully!")
except Exception as e:
print("Failed to send email. Error:", str(e))
def create_user(
name: str,
email: str,
mail_text: str,
mail_user: str,
mail_password: str,
dry_run: bool = False,
):
username = name.split()[0].lower() + "." + name.split()[1].lower()[0]
password = generate_password(20)
cmd = [
"yunohost",
"user",
"create",
username,
"--password",
password,
]
if dry_run:
print(" ".join(cmd))
else:
result = subprocess.run(cmd)
result.check_returncode()
cmd = [
"yunohost",
"user",
"update",
username,
"--add-mailforward",
email,
]
if dry_run:
print(" ".join(cmd))
else:
result = subprocess.run(cmd)
result.check_returncode()
mail_text = mail_text.replace("{name}", name)
mail_text = mail_text.replace("{username}", username)
mail_text = mail_text.replace("{password}", password)
if dry_run:
print(mail_text)
else:
send_email(
f"{mail_user}@cloud.allmende-gufi.de",
email,
"Dein Zugang zur neuen Allmende Cloud",
mail_text,
mail_user,
mail_password,
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Creates Yunohost user from a csv file and sends them an email with the password",
)
parser.add_argument("filename", help="Input file name")
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()
mail_password = os.environ.get("MAIL_PASSWORD", None)
mail_user = os.environ.get("MAIL_USER", None)
if mail_user is None:
print("Missing environment variable: MAIL_USER")
sys.exit(1)
if mail_password is None:
print("Missing environment variable: MAIL_PASSWORD")
sys.exit(1)
with open(args.filename, "r") as f:
data = f.readlines()
with open("./email.txt", "r") as f:
email_text = f.read()
for line in data:
create_user(
*line.strip().split(","),
mail_text=email_text,
mail_user=mail_user,
mail_password=mail_password,
dry_run=args.dry_run,
)