email_service.py 19 KB

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