email_service.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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 backend.app.core.db_dialect import upsert_setting
  123. settings_data = {
  124. "smtp_host": smtp_settings.smtp_host,
  125. "smtp_port": str(smtp_settings.smtp_port),
  126. "smtp_security": smtp_settings.smtp_security,
  127. "smtp_auth_enabled": "true" if smtp_settings.smtp_auth_enabled else "false",
  128. "smtp_from_email": smtp_settings.smtp_from_email,
  129. "smtp_from_name": smtp_settings.smtp_from_name,
  130. }
  131. # Only save username if auth is enabled or if provided
  132. if smtp_settings.smtp_username:
  133. settings_data["smtp_username"] = smtp_settings.smtp_username
  134. # Only save password if provided
  135. if smtp_settings.smtp_password:
  136. settings_data["smtp_password"] = smtp_settings.smtp_password
  137. for key, value in settings_data.items():
  138. await upsert_setting(db, Settings, key, value)
  139. def send_email(
  140. smtp_settings: SMTPSettings,
  141. to_email: str,
  142. subject: str,
  143. body_text: str,
  144. body_html: str | None = None,
  145. ) -> None:
  146. """Send an email using SMTP.
  147. Args:
  148. smtp_settings: SMTP configuration
  149. to_email: Recipient email address
  150. subject: Email subject
  151. body_text: Plain text body
  152. body_html: Optional HTML body
  153. Raises:
  154. Exception: If email sending fails
  155. """
  156. msg = MIMEMultipart("alternative")
  157. msg["From"] = f"{smtp_settings.smtp_from_name} <{smtp_settings.smtp_from_email}>"
  158. msg["To"] = to_email
  159. msg["Subject"] = subject
  160. # Attach plain text part
  161. msg.attach(MIMEText(body_text, "plain"))
  162. # Attach HTML part if provided
  163. if body_html:
  164. msg.attach(MIMEText(body_html, "html"))
  165. # Send email
  166. try:
  167. security = smtp_settings.smtp_security
  168. auth_enabled = smtp_settings.smtp_auth_enabled
  169. # Validate username is provided when authentication is enabled
  170. if auth_enabled and smtp_settings.smtp_password:
  171. if not smtp_settings.smtp_username:
  172. raise ValueError("SMTP username is required when authentication is enabled")
  173. if security == "ssl":
  174. # Direct SSL connection (typically port 465)
  175. with smtplib.SMTP_SSL(smtp_settings.smtp_host, smtp_settings.smtp_port, timeout=10) as server:
  176. if auth_enabled and smtp_settings.smtp_password and smtp_settings.smtp_username:
  177. server.login(smtp_settings.smtp_username, smtp_settings.smtp_password)
  178. server.send_message(msg)
  179. elif security == "starttls":
  180. # STARTTLS upgrade (typically port 587)
  181. with smtplib.SMTP(smtp_settings.smtp_host, smtp_settings.smtp_port, timeout=10) as server:
  182. server.starttls()
  183. if auth_enabled and smtp_settings.smtp_password and smtp_settings.smtp_username:
  184. server.login(smtp_settings.smtp_username, smtp_settings.smtp_password)
  185. server.send_message(msg)
  186. else:
  187. # No encryption (typically port 25) - use with caution
  188. with smtplib.SMTP(smtp_settings.smtp_host, smtp_settings.smtp_port, timeout=10) as server:
  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. logger.info(f"Email sent successfully to {to_email}")
  193. except Exception as e:
  194. logger.error(f"Failed to send email to {to_email}: {e}")
  195. raise
  196. def create_welcome_email(username: str, password: str, login_url: str) -> tuple[str, str, str]:
  197. """Create welcome email content for new user.
  198. Args:
  199. username: Username of the new user
  200. password: Auto-generated password
  201. login_url: URL to login page
  202. Returns:
  203. Tuple of (subject, text_body, html_body)
  204. """
  205. subject = "Welcome to BamBuddy - Your Account Details"
  206. text_body = f"""Welcome to BamBuddy!
  207. Your account has been created. Here are your login details:
  208. Username: {username}
  209. Password: {password}
  210. You can login at: {login_url}
  211. For security reasons, please change your password after your first login.
  212. Best regards,
  213. BamBuddy Team
  214. """
  215. html_body = f"""<!DOCTYPE html>
  216. <html>
  217. <head>
  218. <meta charset="utf-8">
  219. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  220. </head>
  221. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
  222. <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); background-color: #667eea; padding: 20px; border-radius: 8px 8px 0 0;">
  223. <h1 style="color: #ffffff; margin: 0; font-size: 24px; text-shadow: 0 1px 2px rgba(0,0,0,0.3);">Welcome to BamBuddy!</h1>
  224. </div>
  225. <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; border: 1px solid #ddd; border-top: none;">
  226. <p style="font-size: 16px;">Your account has been created. Here are your login details:</p>
  227. <div style="background: white; padding: 20px; border-radius: 4px; margin: 20px 0; border-left: 4px solid #667eea;">
  228. <p style="margin: 0 0 10px 0;"><strong>Username:</strong> <code style="background: #f0f0f0; padding: 2px 6px; border-radius: 3px;">{username}</code></p>
  229. <p style="margin: 0;"><strong>Password:</strong> <code style="background: #f0f0f0; padding: 2px 6px; border-radius: 3px;">{password}</code></p>
  230. </div>
  231. <div style="text-align: center; margin: 30px 0;">
  232. <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>
  233. </div>
  234. <p style="font-size: 14px; color: #666; border-top: 1px solid #ddd; padding-top: 20px; margin-top: 20px;">
  235. <strong>Security Note:</strong> For security reasons, please change your password after your first login.
  236. </p>
  237. <p style="font-size: 14px; color: #999; margin-top: 30px;">
  238. Best regards,<br>
  239. BamBuddy Team
  240. </p>
  241. </div>
  242. </body>
  243. </html>
  244. """
  245. return subject, text_body, html_body
  246. def create_password_reset_email(username: str, password: str, login_url: str) -> tuple[str, str, str]:
  247. """Create password reset email content.
  248. Args:
  249. username: Username of the user
  250. password: New auto-generated password
  251. login_url: URL to login page
  252. Returns:
  253. Tuple of (subject, text_body, html_body)
  254. """
  255. subject = "BamBuddy - Your Password Has Been Reset"
  256. text_body = f"""Your BamBuddy password has been reset.
  257. Your login details:
  258. Username: {username}
  259. New Password: {password}
  260. You can login at: {login_url}
  261. For security reasons, please change your password after logging in.
  262. If you did not request this password reset, please contact your administrator immediately.
  263. Best regards,
  264. BamBuddy Team
  265. """
  266. html_body = f"""<!DOCTYPE html>
  267. <html>
  268. <head>
  269. <meta charset="utf-8">
  270. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  271. </head>
  272. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
  273. <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); background-color: #667eea; padding: 20px; border-radius: 8px 8px 0 0;">
  274. <h1 style="color: #ffffff; margin: 0; font-size: 24px; text-shadow: 0 1px 2px rgba(0,0,0,0.3);">Password Reset</h1>
  275. </div>
  276. <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; border: 1px solid #ddd; border-top: none;">
  277. <p style="font-size: 16px;">Your BamBuddy password has been reset.</p>
  278. <div style="background: white; padding: 20px; border-radius: 4px; margin: 20px 0; border-left: 4px solid #667eea;">
  279. <p style="margin: 0 0 10px 0;"><strong>Username:</strong> <code style="background: #f0f0f0; padding: 2px 6px; border-radius: 3px;">{username}</code></p>
  280. <p style="margin: 0;"><strong>New Password:</strong> <code style="background: #f0f0f0; padding: 2px 6px; border-radius: 3px;">{password}</code></p>
  281. </div>
  282. <div style="text-align: center; margin: 30px 0;">
  283. <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>
  284. </div>
  285. <div style="background-color: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; padding: 15px; margin: 20px 0;">
  286. <p style="margin: 0; font-size: 14px; color: #856404;">
  287. <strong>⚠️ Security Alert:</strong> If you did not request this password reset, please contact your administrator immediately.
  288. </p>
  289. </div>
  290. <p style="font-size: 14px; color: #666; border-top: 1px solid #ddd; padding-top: 20px; margin-top: 20px;">
  291. <strong>Security Note:</strong> For security reasons, please change your password after logging in.
  292. </p>
  293. <p style="font-size: 14px; color: #999; margin-top: 30px;">
  294. Best regards,<br>
  295. BamBuddy Team
  296. </p>
  297. </div>
  298. </body>
  299. </html>
  300. """
  301. return subject, text_body, html_body
  302. async def create_welcome_email_from_template(
  303. db: AsyncSession, username: str, password: str, login_url: str, app_name: str = "BamBuddy"
  304. ) -> tuple[str, str, str]:
  305. """Create welcome email content using notification template from database.
  306. Args:
  307. db: Database session
  308. username: Username of the new user
  309. password: Auto-generated password
  310. login_url: URL to login page
  311. app_name: Application name (default: BamBuddy)
  312. Returns:
  313. Tuple of (subject, text_body, html_body)
  314. """
  315. # Try to get template from database
  316. template = await get_notification_template(db, "user_created")
  317. if template:
  318. # Render template with variables
  319. variables = {
  320. "app_name": app_name,
  321. "username": username,
  322. "password": password,
  323. "login_url": login_url,
  324. }
  325. subject = render_template(template.title_template, variables)
  326. text_body = render_template(template.body_template, variables)
  327. # Create HTML version with embedded login button
  328. # Escape text_body to prevent XSS vulnerabilities and convert newlines to <br> tags
  329. escaped_text_body = html.escape(text_body).replace("\n", "<br>\n")
  330. html_body = f"""<!DOCTYPE html>
  331. <html>
  332. <head>
  333. <meta charset="utf-8">
  334. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  335. </head>
  336. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
  337. <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); background-color: #667eea; padding: 30px; border-radius: 8px 8px 0 0;">
  338. <h1 style="color: #ffffff; margin: 0; font-size: 24px; text-shadow: 0 1px 2px rgba(0,0,0,0.3);">{html.escape(subject)}</h1>
  339. </div>
  340. <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; border: 1px solid #ddd; border-top: none;">
  341. <div style="font-size: 16px;">{escaped_text_body}</div>
  342. <div style="text-align: center; margin: 30px 0;">
  343. <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>
  344. </div>
  345. </div>
  346. </body>
  347. </html>
  348. """
  349. logger.info("Using custom welcome email template from database")
  350. return subject, text_body, html_body
  351. else:
  352. # Fallback to hardcoded template
  353. logger.warning("No welcome email template found in database, using default")
  354. return create_welcome_email(username, password, login_url)
  355. async def create_password_reset_email_from_template(
  356. db: AsyncSession, username: str, password: str, login_url: str, app_name: str = "BamBuddy"
  357. ) -> tuple[str, str, str]:
  358. """Create password reset email content using notification template from database.
  359. Args:
  360. db: Database session
  361. username: Username of the user
  362. password: New auto-generated password
  363. login_url: URL to login page
  364. app_name: Application name (default: BamBuddy)
  365. Returns:
  366. Tuple of (subject, text_body, html_body)
  367. """
  368. # Try to get template from database
  369. template = await get_notification_template(db, "password_reset")
  370. if template:
  371. # Render template with variables
  372. variables = {
  373. "app_name": app_name,
  374. "username": username,
  375. "password": password,
  376. "login_url": login_url,
  377. }
  378. subject = render_template(template.title_template, variables)
  379. text_body = render_template(template.body_template, variables)
  380. # Create HTML version with embedded login button
  381. # Escape text_body to prevent XSS vulnerabilities and convert newlines to <br> tags
  382. escaped_text_body = html.escape(text_body).replace("\n", "<br>\n")
  383. html_body = f"""<!DOCTYPE html>
  384. <html>
  385. <head>
  386. <meta charset="utf-8">
  387. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  388. </head>
  389. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
  390. <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); background-color: #667eea; padding: 30px; border-radius: 8px 8px 0 0;">
  391. <h1 style="color: #ffffff; margin: 0; font-size: 24px; text-shadow: 0 1px 2px rgba(0,0,0,0.3);">{html.escape(subject)}</h1>
  392. </div>
  393. <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; border: 1px solid #ddd; border-top: none;">
  394. <div style="font-size: 16px;">{escaped_text_body}</div>
  395. <div style="text-align: center; margin: 30px 0;">
  396. <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>
  397. </div>
  398. <div style="background-color: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; padding: 15px; margin: 20px 0;">
  399. <p style="margin: 0; font-size: 14px; color: #856404;">
  400. <strong>⚠️ Security Alert:</strong> If you did not request this password reset, please contact your administrator immediately.
  401. </p>
  402. </div>
  403. </div>
  404. </body>
  405. </html>
  406. """
  407. logger.info("Using custom password reset email template from database")
  408. return subject, text_body, html_body
  409. else:
  410. # Fallback to hardcoded template
  411. logger.warning("No password reset email template found in database, using default")
  412. return create_password_reset_email(username, password, login_url)
  413. async def send_user_print_notification(
  414. db: AsyncSession,
  415. event_type: str,
  416. user_email: str,
  417. username: str,
  418. variables: dict,
  419. ) -> None:
  420. """Send a print notification email to a user using Advanced Auth SMTP settings.
  421. Args:
  422. db: Database session
  423. event_type: One of 'user_print_start', 'user_print_complete', 'user_print_failed', 'user_print_stopped'
  424. user_email: Recipient email address
  425. username: Username of the recipient
  426. variables: Template variables (printer, filename, etc.)
  427. """
  428. # Check that advanced auth is enabled (SMTP settings must be configured)
  429. smtp_settings = await get_smtp_settings(db)
  430. if not smtp_settings:
  431. logger.warning("Cannot send user print notification: SMTP settings not configured")
  432. return
  433. # Get the template
  434. template = await get_notification_template(db, event_type)
  435. if template is None:
  436. logger.warning("No template found for event type: %s", event_type)
  437. return
  438. # Add common variables (username, timestamp, app_name) merged with caller-supplied variables
  439. all_variables = {
  440. "username": username,
  441. "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"),
  442. "app_name": "Bambuddy",
  443. **variables,
  444. }
  445. subject = render_template(template.title_template, all_variables)
  446. text_body = render_template(template.body_template, all_variables)
  447. # Build HTML body — content comes entirely from the database template
  448. escaped_text_body = html.escape(text_body).replace("\n", "<br>\n")
  449. html_body = f"""<!DOCTYPE html>
  450. <html>
  451. <head>
  452. <meta charset="utf-8">
  453. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  454. </head>
  455. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
  456. <div style="background: linear-gradient(135deg, #1db954 0%, #158a3e 100%); background-color: #1db954; padding: 20px; border-radius: 8px 8px 0 0;">
  457. <h1 style="color: #ffffff; margin: 0; font-size: 24px; text-shadow: 0 1px 2px rgba(0,0,0,0.3);">{html.escape(subject)}</h1>
  458. </div>
  459. <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; border: 1px solid #ddd; border-top: none;">
  460. <div style="font-size: 16px;">{escaped_text_body}</div>
  461. </div>
  462. </body>
  463. </html>
  464. """
  465. try:
  466. send_email(smtp_settings, user_email, subject, text_body, html_body)
  467. logger.info("Sent %s notification email to %s", event_type, user_email)
  468. except Exception as e:
  469. logger.error("Failed to send %s notification to %s: %s", event_type, user_email, e)