email_service.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. """Email service for sending authentication-related emails."""
  2. from __future__ import annotations
  3. import html
  4. import logging
  5. import re
  6. import secrets
  7. import smtplib
  8. import string
  9. from datetime import datetime, timezone
  10. from email.mime.multipart import MIMEMultipart
  11. from email.mime.text import MIMEText
  12. from typing import Any
  13. from sqlalchemy import select
  14. from sqlalchemy.ext.asyncio import AsyncSession
  15. from backend.app.models.notification_template import NotificationTemplate
  16. from backend.app.models.settings import Settings
  17. from backend.app.schemas.auth import SMTPSettings
  18. logger = logging.getLogger(__name__)
  19. def generate_secure_password(length: int = 16) -> str:
  20. """Generate a secure random password.
  21. Args:
  22. length: Length of the password (default: 16)
  23. Returns:
  24. A secure random password containing uppercase, lowercase, digits, and special characters
  25. """
  26. import random
  27. # Define character sets
  28. lowercase = string.ascii_lowercase
  29. uppercase = string.ascii_uppercase
  30. digits = string.digits
  31. special = "!@#$%^&*()_+-=[]{}|;:,.<>?"
  32. # Ensure at least one character from each set
  33. password_chars = [
  34. secrets.choice(lowercase),
  35. secrets.choice(uppercase),
  36. secrets.choice(digits),
  37. secrets.choice(special),
  38. ]
  39. # Fill the rest with random characters from all sets
  40. all_chars = lowercase + uppercase + digits + special
  41. password_chars.extend(secrets.choice(all_chars) for _ in range(length - 4))
  42. # Shuffle to avoid predictable patterns
  43. random.shuffle(password_chars)
  44. return "".join(password_chars)
  45. async def get_notification_template(db: AsyncSession, event_type: str) -> NotificationTemplate | None:
  46. """Get a notification template by event type from database.
  47. Args:
  48. db: Database session
  49. event_type: Type of event (e.g., 'user_created', 'password_reset')
  50. Returns:
  51. NotificationTemplate object or None if not found
  52. """
  53. result = await db.execute(select(NotificationTemplate).where(NotificationTemplate.event_type == event_type))
  54. return result.scalar_one_or_none()
  55. def render_template(template_str: str, variables: dict[str, Any]) -> str:
  56. """Render a template string with variables.
  57. Args:
  58. template_str: Template string with {variable} placeholders
  59. variables: Dictionary of variables to substitute
  60. Returns:
  61. Rendered template string
  62. """
  63. result = template_str
  64. for key, value in variables.items():
  65. result = result.replace("{" + key + "}", str(value) if value is not None else "")
  66. # Remove any remaining unreplaced placeholders (case-insensitive, alphanumeric + underscore)
  67. result = re.sub(r"\{[a-zA-Z0-9_]+\}", "", result)
  68. return result
  69. async def get_smtp_settings(db: AsyncSession) -> SMTPSettings | None:
  70. """Get SMTP settings from database.
  71. Args:
  72. db: Database session
  73. Returns:
  74. SMTPSettings object or None if not configured
  75. """
  76. # Fetch all SMTP-related settings
  77. result = await db.execute(
  78. select(Settings).where(
  79. Settings.key.in_(
  80. [
  81. "smtp_host",
  82. "smtp_port",
  83. "smtp_username",
  84. "smtp_password",
  85. "smtp_use_tls",
  86. "smtp_security",
  87. "smtp_auth_enabled",
  88. "smtp_from_email",
  89. "smtp_from_name",
  90. ]
  91. )
  92. )
  93. )
  94. settings_dict = {s.key: s.value for s in result.scalars().all()}
  95. # Check if minimum required settings are present
  96. required_keys = ["smtp_host", "smtp_port", "smtp_from_email"]
  97. if not all(key in settings_dict for key in required_keys):
  98. return None
  99. # Handle migration: convert old smtp_use_tls to smtp_security if needed
  100. smtp_security = settings_dict.get("smtp_security")
  101. if not smtp_security:
  102. # Migrate from old smtp_use_tls format
  103. smtp_use_tls = settings_dict.get("smtp_use_tls", "true").lower() == "true"
  104. smtp_security = "starttls" if smtp_use_tls else "ssl"
  105. smtp_auth_enabled = settings_dict.get("smtp_auth_enabled", "true").lower() == "true"
  106. return SMTPSettings(
  107. smtp_host=settings_dict["smtp_host"],
  108. smtp_port=int(settings_dict["smtp_port"]),
  109. smtp_username=settings_dict.get("smtp_username"),
  110. smtp_password=settings_dict.get("smtp_password"),
  111. smtp_security=smtp_security,
  112. smtp_auth_enabled=smtp_auth_enabled,
  113. smtp_from_email=settings_dict["smtp_from_email"],
  114. smtp_from_name=settings_dict.get("smtp_from_name", "BamBuddy"),
  115. )
  116. async def save_smtp_settings(db: AsyncSession, smtp_settings: SMTPSettings) -> None:
  117. """Save SMTP settings to database.
  118. Args:
  119. db: Database session
  120. smtp_settings: SMTP settings to save
  121. """
  122. from sqlalchemy import func
  123. from sqlalchemy.dialects.sqlite import insert as sqlite_insert
  124. settings_data = {
  125. "smtp_host": smtp_settings.smtp_host,
  126. "smtp_port": str(smtp_settings.smtp_port),
  127. "smtp_security": smtp_settings.smtp_security,
  128. "smtp_auth_enabled": "true" if smtp_settings.smtp_auth_enabled else "false",
  129. "smtp_from_email": smtp_settings.smtp_from_email,
  130. "smtp_from_name": smtp_settings.smtp_from_name,
  131. }
  132. # Only save username if auth is enabled or if provided
  133. if smtp_settings.smtp_username:
  134. settings_data["smtp_username"] = smtp_settings.smtp_username
  135. # Only save password if provided
  136. if smtp_settings.smtp_password:
  137. settings_data["smtp_password"] = smtp_settings.smtp_password
  138. for key, value in settings_data.items():
  139. stmt = sqlite_insert(Settings).values(key=key, value=value)
  140. stmt = stmt.on_conflict_do_update(
  141. index_elements=["key"],
  142. set_={"value": value, "updated_at": func.now()},
  143. )
  144. await db.execute(stmt)
  145. def send_email(
  146. smtp_settings: SMTPSettings,
  147. to_email: str,
  148. subject: str,
  149. body_text: str,
  150. body_html: str | None = None,
  151. ) -> None:
  152. """Send an email using SMTP.
  153. Args:
  154. smtp_settings: SMTP configuration
  155. to_email: Recipient email address
  156. subject: Email subject
  157. body_text: Plain text body
  158. body_html: Optional HTML body
  159. Raises:
  160. Exception: If email sending fails
  161. """
  162. msg = MIMEMultipart("alternative")
  163. msg["From"] = f"{smtp_settings.smtp_from_name} <{smtp_settings.smtp_from_email}>"
  164. msg["To"] = to_email
  165. msg["Subject"] = subject
  166. # Attach plain text part
  167. msg.attach(MIMEText(body_text, "plain"))
  168. # Attach HTML part if provided
  169. if body_html:
  170. msg.attach(MIMEText(body_html, "html"))
  171. # Send email
  172. try:
  173. security = smtp_settings.smtp_security
  174. auth_enabled = smtp_settings.smtp_auth_enabled
  175. # Validate username is provided when authentication is enabled
  176. if auth_enabled and smtp_settings.smtp_password:
  177. if not smtp_settings.smtp_username:
  178. raise ValueError("SMTP username is required when authentication is enabled")
  179. if security == "ssl":
  180. # Direct SSL connection (typically port 465)
  181. with smtplib.SMTP_SSL(smtp_settings.smtp_host, smtp_settings.smtp_port, timeout=10) as server:
  182. if auth_enabled and smtp_settings.smtp_password and smtp_settings.smtp_username:
  183. server.login(smtp_settings.smtp_username, smtp_settings.smtp_password)
  184. server.send_message(msg)
  185. elif security == "starttls":
  186. # STARTTLS upgrade (typically port 587)
  187. with smtplib.SMTP(smtp_settings.smtp_host, smtp_settings.smtp_port, timeout=10) as server:
  188. server.starttls()
  189. if auth_enabled and smtp_settings.smtp_password and smtp_settings.smtp_username:
  190. server.login(smtp_settings.smtp_username, smtp_settings.smtp_password)
  191. server.send_message(msg)
  192. else:
  193. # No encryption (typically port 25) - use with caution
  194. with smtplib.SMTP(smtp_settings.smtp_host, smtp_settings.smtp_port, timeout=10) as server:
  195. if auth_enabled and smtp_settings.smtp_password and smtp_settings.smtp_username:
  196. server.login(smtp_settings.smtp_username, smtp_settings.smtp_password)
  197. server.send_message(msg)
  198. logger.info(f"Email sent successfully to {to_email}")
  199. except Exception as e:
  200. logger.error(f"Failed to send email to {to_email}: {e}")
  201. raise
  202. def create_welcome_email(username: str, password: str, login_url: str) -> tuple[str, str, str]:
  203. """Create welcome email content for new user.
  204. Args:
  205. username: Username of the new user
  206. password: Auto-generated password
  207. login_url: URL to login page
  208. Returns:
  209. Tuple of (subject, text_body, html_body)
  210. """
  211. subject = "Welcome to BamBuddy - Your Account Details"
  212. text_body = f"""Welcome to BamBuddy!
  213. Your account has been created. Here are your login details:
  214. Username: {username}
  215. Password: {password}
  216. You can login at: {login_url}
  217. For security reasons, please change your password after your first login.
  218. Best regards,
  219. BamBuddy Team
  220. """
  221. html_body = f"""<!DOCTYPE html>
  222. <html>
  223. <head>
  224. <meta charset="utf-8">
  225. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  226. </head>
  227. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
  228. <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); background-color: #667eea; padding: 20px; border-radius: 8px 8px 0 0;">
  229. <h1 style="color: #ffffff; margin: 0; font-size: 24px; text-shadow: 0 1px 2px rgba(0,0,0,0.3);">Welcome to BamBuddy!</h1>
  230. </div>
  231. <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; border: 1px solid #ddd; border-top: none;">
  232. <p style="font-size: 16px;">Your account has been created. Here are your login details:</p>
  233. <div style="background: white; padding: 20px; border-radius: 4px; margin: 20px 0; border-left: 4px solid #667eea;">
  234. <p style="margin: 0 0 10px 0;"><strong>Username:</strong> <code style="background: #f0f0f0; padding: 2px 6px; border-radius: 3px;">{username}</code></p>
  235. <p style="margin: 0;"><strong>Password:</strong> <code style="background: #f0f0f0; padding: 2px 6px; border-radius: 3px;">{password}</code></p>
  236. </div>
  237. <div style="text-align: center; margin: 30px 0;">
  238. <a href="{login_url}" style="display: inline-block; background-color: #667eea; color: #ffffff; padding: 12px 30px; text-decoration: none; border-radius: 4px; font-weight: bold;">Login Now</a>
  239. </div>
  240. <p style="font-size: 14px; color: #666; border-top: 1px solid #ddd; padding-top: 20px; margin-top: 20px;">
  241. <strong>Security Note:</strong> For security reasons, please change your password after your first login.
  242. </p>
  243. <p style="font-size: 14px; color: #999; margin-top: 30px;">
  244. Best regards,<br>
  245. BamBuddy Team
  246. </p>
  247. </div>
  248. </body>
  249. </html>
  250. """
  251. return subject, text_body, html_body
  252. def create_password_reset_email(username: str, password: str, login_url: str) -> tuple[str, str, str]:
  253. """Create password reset email content.
  254. Args:
  255. username: Username of the user
  256. password: New auto-generated password
  257. login_url: URL to login page
  258. Returns:
  259. Tuple of (subject, text_body, html_body)
  260. """
  261. subject = "BamBuddy - Your Password Has Been Reset"
  262. text_body = f"""Your BamBuddy password has been reset.
  263. Your login details:
  264. Username: {username}
  265. New Password: {password}
  266. You can login at: {login_url}
  267. For security reasons, please change your password after logging in.
  268. If you did not request this password reset, please contact your administrator immediately.
  269. Best regards,
  270. BamBuddy Team
  271. """
  272. html_body = f"""<!DOCTYPE html>
  273. <html>
  274. <head>
  275. <meta charset="utf-8">
  276. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  277. </head>
  278. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
  279. <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); background-color: #667eea; padding: 20px; border-radius: 8px 8px 0 0;">
  280. <h1 style="color: #ffffff; margin: 0; font-size: 24px; text-shadow: 0 1px 2px rgba(0,0,0,0.3);">Password Reset</h1>
  281. </div>
  282. <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; border: 1px solid #ddd; border-top: none;">
  283. <p style="font-size: 16px;">Your BamBuddy password has been reset.</p>
  284. <div style="background: white; padding: 20px; border-radius: 4px; margin: 20px 0; border-left: 4px solid #667eea;">
  285. <p style="margin: 0 0 10px 0;"><strong>Username:</strong> <code style="background: #f0f0f0; padding: 2px 6px; border-radius: 3px;">{username}</code></p>
  286. <p style="margin: 0;"><strong>New Password:</strong> <code style="background: #f0f0f0; padding: 2px 6px; border-radius: 3px;">{password}</code></p>
  287. </div>
  288. <div style="text-align: center; margin: 30px 0;">
  289. <a href="{login_url}" style="display: inline-block; background-color: #667eea; color: #ffffff; padding: 12px 30px; text-decoration: none; border-radius: 4px; font-weight: bold;">Login Now</a>
  290. </div>
  291. <div style="background-color: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; padding: 15px; margin: 20px 0;">
  292. <p style="margin: 0; font-size: 14px; color: #856404;">
  293. <strong>⚠️ Security Alert:</strong> If you did not request this password reset, please contact your administrator immediately.
  294. </p>
  295. </div>
  296. <p style="font-size: 14px; color: #666; border-top: 1px solid #ddd; padding-top: 20px; margin-top: 20px;">
  297. <strong>Security Note:</strong> For security reasons, please change your password after logging in.
  298. </p>
  299. <p style="font-size: 14px; color: #999; margin-top: 30px;">
  300. Best regards,<br>
  301. BamBuddy Team
  302. </p>
  303. </div>
  304. </body>
  305. </html>
  306. """
  307. return subject, text_body, html_body
  308. async def create_welcome_email_from_template(
  309. db: AsyncSession, username: str, password: str, login_url: str, app_name: str = "BamBuddy"
  310. ) -> tuple[str, str, str]:
  311. """Create welcome email content using notification template from database.
  312. Args:
  313. db: Database session
  314. username: Username of the new user
  315. password: Auto-generated password
  316. login_url: URL to login page
  317. app_name: Application name (default: BamBuddy)
  318. Returns:
  319. Tuple of (subject, text_body, html_body)
  320. """
  321. # Try to get template from database
  322. template = await get_notification_template(db, "user_created")
  323. if template:
  324. # Render template with variables
  325. variables = {
  326. "app_name": app_name,
  327. "username": username,
  328. "password": password,
  329. "login_url": login_url,
  330. }
  331. subject = render_template(template.title_template, variables)
  332. text_body = render_template(template.body_template, variables)
  333. # Create HTML version with embedded login button
  334. # Escape text_body to prevent XSS vulnerabilities and convert newlines to <br> tags
  335. escaped_text_body = html.escape(text_body).replace("\n", "<br>\n")
  336. html_body = f"""<!DOCTYPE html>
  337. <html>
  338. <head>
  339. <meta charset="utf-8">
  340. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  341. </head>
  342. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
  343. <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); background-color: #667eea; padding: 30px; border-radius: 8px 8px 0 0;">
  344. <h1 style="color: #ffffff; margin: 0; font-size: 24px; text-shadow: 0 1px 2px rgba(0,0,0,0.3);">{html.escape(subject)}</h1>
  345. </div>
  346. <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; border: 1px solid #ddd; border-top: none;">
  347. <div style="font-size: 16px;">{escaped_text_body}</div>
  348. <div style="text-align: center; margin: 30px 0;">
  349. <a href="{login_url}" style="display: inline-block; background-color: #667eea; color: #ffffff; padding: 12px 30px; text-decoration: none; border-radius: 4px; font-weight: bold;">Login Now</a>
  350. </div>
  351. </div>
  352. </body>
  353. </html>
  354. """
  355. logger.info("Using custom welcome email template from database")
  356. return subject, text_body, html_body
  357. else:
  358. # Fallback to hardcoded template
  359. logger.warning("No welcome email template found in database, using default")
  360. return create_welcome_email(username, password, login_url)
  361. async def create_password_reset_email_from_template(
  362. db: AsyncSession, username: str, password: str, login_url: str, app_name: str = "BamBuddy"
  363. ) -> tuple[str, str, str]:
  364. """Create password reset email content using notification template from database.
  365. Args:
  366. db: Database session
  367. username: Username of the user
  368. password: New auto-generated password
  369. login_url: URL to login page
  370. app_name: Application name (default: BamBuddy)
  371. Returns:
  372. Tuple of (subject, text_body, html_body)
  373. """
  374. # Try to get template from database
  375. template = await get_notification_template(db, "password_reset")
  376. if template:
  377. # Render template with variables
  378. variables = {
  379. "app_name": app_name,
  380. "username": username,
  381. "password": password,
  382. "login_url": login_url,
  383. }
  384. subject = render_template(template.title_template, variables)
  385. text_body = render_template(template.body_template, variables)
  386. # Create HTML version with embedded login button
  387. # Escape text_body to prevent XSS vulnerabilities and convert newlines to <br> tags
  388. escaped_text_body = html.escape(text_body).replace("\n", "<br>\n")
  389. html_body = f"""<!DOCTYPE html>
  390. <html>
  391. <head>
  392. <meta charset="utf-8">
  393. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  394. </head>
  395. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
  396. <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); background-color: #667eea; padding: 30px; border-radius: 8px 8px 0 0;">
  397. <h1 style="color: #ffffff; margin: 0; font-size: 24px; text-shadow: 0 1px 2px rgba(0,0,0,0.3);">{html.escape(subject)}</h1>
  398. </div>
  399. <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; border: 1px solid #ddd; border-top: none;">
  400. <div style="font-size: 16px;">{escaped_text_body}</div>
  401. <div style="text-align: center; margin: 30px 0;">
  402. <a href="{login_url}" style="display: inline-block; background-color: #667eea; color: #ffffff; padding: 12px 30px; text-decoration: none; border-radius: 4px; font-weight: bold;">Login Now</a>
  403. </div>
  404. <div style="background-color: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; padding: 15px; margin: 20px 0;">
  405. <p style="margin: 0; font-size: 14px; color: #856404;">
  406. <strong>⚠️ Security Alert:</strong> If you did not request this password reset, please contact your administrator immediately.
  407. </p>
  408. </div>
  409. </div>
  410. </body>
  411. </html>
  412. """
  413. logger.info("Using custom password reset email template from database")
  414. return subject, text_body, html_body
  415. else:
  416. # Fallback to hardcoded template
  417. logger.warning("No password reset email template found in database, using default")
  418. return create_password_reset_email(username, password, login_url)
  419. async def send_user_print_notification(
  420. db: AsyncSession,
  421. event_type: str,
  422. user_email: str,
  423. username: str,
  424. variables: dict,
  425. ) -> None:
  426. """Send a print notification email to a user using Advanced Auth SMTP settings.
  427. Args:
  428. db: Database session
  429. event_type: One of 'user_print_start', 'user_print_complete', 'user_print_failed', 'user_print_stopped'
  430. user_email: Recipient email address
  431. username: Username of the recipient
  432. variables: Template variables (printer, filename, etc.)
  433. """
  434. # Check that advanced auth is enabled (SMTP settings must be configured)
  435. smtp_settings = await get_smtp_settings(db)
  436. if not smtp_settings:
  437. logger.warning("Cannot send user print notification: SMTP settings not configured")
  438. return
  439. # Get the template
  440. template = await get_notification_template(db, event_type)
  441. if template is None:
  442. logger.warning("No template found for event type: %s", event_type)
  443. return
  444. # Add common variables (username, timestamp, app_name) merged with caller-supplied variables
  445. all_variables = {
  446. "username": username,
  447. "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"),
  448. "app_name": "Bambuddy",
  449. **variables,
  450. }
  451. subject = render_template(template.title_template, all_variables)
  452. text_body = render_template(template.body_template, all_variables)
  453. # Build HTML body — content comes entirely from the database template
  454. escaped_text_body = html.escape(text_body).replace("\n", "<br>\n")
  455. html_body = f"""<!DOCTYPE html>
  456. <html>
  457. <head>
  458. <meta charset="utf-8">
  459. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  460. </head>
  461. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
  462. <div style="background: linear-gradient(135deg, #1db954 0%, #158a3e 100%); background-color: #1db954; padding: 20px; border-radius: 8px 8px 0 0;">
  463. <h1 style="color: #ffffff; margin: 0; font-size: 24px; text-shadow: 0 1px 2px rgba(0,0,0,0.3);">{html.escape(subject)}</h1>
  464. </div>
  465. <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; border: 1px solid #ddd; border-top: none;">
  466. <div style="font-size: 16px;">{escaped_text_body}</div>
  467. </div>
  468. </body>
  469. </html>
  470. """
  471. try:
  472. send_email(smtp_settings, user_email, subject, text_body, html_body)
  473. logger.info("Sent %s notification email to %s", event_type, user_email)
  474. except Exception as e:
  475. logger.error("Failed to send %s notification to %s: %s", event_type, user_email, e)