email_service.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. """Email service for sending authentication-related emails."""
  2. from __future__ import annotations
  3. import logging
  4. import secrets
  5. import smtplib
  6. import string
  7. from email.mime.multipart import MIMEMultipart
  8. from email.mime.text import MIMEText
  9. from typing import TYPE_CHECKING
  10. from sqlalchemy import select
  11. from sqlalchemy.ext.asyncio import AsyncSession
  12. from backend.app.models.settings import Settings
  13. if TYPE_CHECKING:
  14. from backend.app.schemas.auth import SMTPSettings
  15. logger = logging.getLogger(__name__)
  16. def generate_secure_password(length: int = 16) -> str:
  17. """Generate a secure random password.
  18. Args:
  19. length: Length of the password (default: 16)
  20. Returns:
  21. A secure random password containing uppercase, lowercase, digits, and special characters
  22. """
  23. # Define character sets
  24. lowercase = string.ascii_lowercase
  25. uppercase = string.ascii_uppercase
  26. digits = string.digits
  27. special = "!@#$%^&*()_+-=[]{}|;:,.<>?"
  28. # Ensure at least one character from each set
  29. password_chars = [
  30. secrets.choice(lowercase),
  31. secrets.choice(uppercase),
  32. secrets.choice(digits),
  33. secrets.choice(special),
  34. ]
  35. # Fill the rest with random characters from all sets
  36. all_chars = lowercase + uppercase + digits + special
  37. password_chars.extend(secrets.choice(all_chars) for _ in range(length - 4))
  38. # Shuffle to avoid predictable patterns
  39. secrets.SystemRandom().shuffle(password_chars)
  40. return "".join(password_chars)
  41. async def get_smtp_settings(db: AsyncSession) -> SMTPSettings | None:
  42. """Get SMTP settings from database.
  43. Args:
  44. db: Database session
  45. Returns:
  46. SMTPSettings object or None if not configured
  47. """
  48. from backend.app.schemas.auth import SMTPSettings
  49. # Fetch all SMTP-related settings
  50. result = await db.execute(
  51. select(Settings).where(
  52. Settings.key.in_([
  53. "smtp_host",
  54. "smtp_port",
  55. "smtp_username",
  56. "smtp_password",
  57. "smtp_use_tls",
  58. "smtp_from_email",
  59. "smtp_from_name",
  60. ])
  61. )
  62. )
  63. settings_dict = {s.key: s.value for s in result.scalars().all()}
  64. # Check if minimum required settings are present
  65. required_keys = ["smtp_host", "smtp_port", "smtp_username", "smtp_from_email"]
  66. if not all(key in settings_dict for key in required_keys):
  67. return None
  68. return SMTPSettings(
  69. smtp_host=settings_dict["smtp_host"],
  70. smtp_port=int(settings_dict["smtp_port"]),
  71. smtp_username=settings_dict["smtp_username"],
  72. smtp_password=settings_dict.get("smtp_password"),
  73. smtp_use_tls=settings_dict.get("smtp_use_tls", "true").lower() == "true",
  74. smtp_from_email=settings_dict["smtp_from_email"],
  75. smtp_from_name=settings_dict.get("smtp_from_name", "BamBuddy"),
  76. )
  77. async def save_smtp_settings(db: AsyncSession, smtp_settings: SMTPSettings) -> None:
  78. """Save SMTP settings to database.
  79. Args:
  80. db: Database session
  81. smtp_settings: SMTP settings to save
  82. """
  83. from sqlalchemy import func
  84. from sqlalchemy.dialects.sqlite import insert as sqlite_insert
  85. settings_data = {
  86. "smtp_host": smtp_settings.smtp_host,
  87. "smtp_port": str(smtp_settings.smtp_port),
  88. "smtp_username": smtp_settings.smtp_username,
  89. "smtp_use_tls": "true" if smtp_settings.smtp_use_tls else "false",
  90. "smtp_from_email": smtp_settings.smtp_from_email,
  91. "smtp_from_name": smtp_settings.smtp_from_name,
  92. }
  93. # Only save password if provided
  94. if smtp_settings.smtp_password:
  95. settings_data["smtp_password"] = smtp_settings.smtp_password
  96. for key, value in settings_data.items():
  97. stmt = sqlite_insert(Settings).values(key=key, value=value)
  98. stmt = stmt.on_conflict_do_update(
  99. index_elements=["key"],
  100. set_={"value": value, "updated_at": func.now()},
  101. )
  102. await db.execute(stmt)
  103. def send_email(
  104. smtp_settings: SMTPSettings,
  105. to_email: str,
  106. subject: str,
  107. body_text: str,
  108. body_html: str | None = None,
  109. ) -> None:
  110. """Send an email using SMTP.
  111. Args:
  112. smtp_settings: SMTP configuration
  113. to_email: Recipient email address
  114. subject: Email subject
  115. body_text: Plain text body
  116. body_html: Optional HTML body
  117. Raises:
  118. Exception: If email sending fails
  119. """
  120. msg = MIMEMultipart("alternative")
  121. msg["From"] = f"{smtp_settings.smtp_from_name} <{smtp_settings.smtp_from_email}>"
  122. msg["To"] = to_email
  123. msg["Subject"] = subject
  124. # Attach plain text part
  125. msg.attach(MIMEText(body_text, "plain"))
  126. # Attach HTML part if provided
  127. if body_html:
  128. msg.attach(MIMEText(body_html, "html"))
  129. # Send email
  130. try:
  131. if smtp_settings.smtp_use_tls:
  132. # Use TLS (port 587 typically)
  133. with smtplib.SMTP(smtp_settings.smtp_host, smtp_settings.smtp_port, timeout=10) as server:
  134. server.starttls()
  135. if smtp_settings.smtp_password:
  136. server.login(smtp_settings.smtp_username, smtp_settings.smtp_password)
  137. server.send_message(msg)
  138. else:
  139. # Use SSL (port 465 typically) or no encryption
  140. with smtplib.SMTP_SSL(smtp_settings.smtp_host, smtp_settings.smtp_port, timeout=10) as server:
  141. if smtp_settings.smtp_password:
  142. server.login(smtp_settings.smtp_username, smtp_settings.smtp_password)
  143. server.send_message(msg)
  144. logger.info(f"Email sent successfully to {to_email}")
  145. except Exception as e:
  146. logger.error(f"Failed to send email to {to_email}: {e}")
  147. raise
  148. def create_welcome_email(username: str, password: str, login_url: str) -> tuple[str, str, str]:
  149. """Create welcome email content for new user.
  150. Args:
  151. username: Username of the new user
  152. password: Auto-generated password
  153. login_url: URL to login page
  154. Returns:
  155. Tuple of (subject, text_body, html_body)
  156. """
  157. subject = "Welcome to BamBuddy - Your Account Details"
  158. text_body = f"""Welcome to BamBuddy!
  159. Your account has been created. Here are your login details:
  160. Username: {username}
  161. Password: {password}
  162. You can login at: {login_url}
  163. For security reasons, please change your password after your first login.
  164. Best regards,
  165. BamBuddy Team
  166. """
  167. html_body = f"""<!DOCTYPE html>
  168. <html>
  169. <head>
  170. <meta charset="utf-8">
  171. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  172. </head>
  173. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
  174. <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 20px; border-radius: 8px 8px 0 0;">
  175. <h1 style="color: white; margin: 0; font-size: 24px;">Welcome to BamBuddy!</h1>
  176. </div>
  177. <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; border: 1px solid #ddd; border-top: none;">
  178. <p style="font-size: 16px;">Your account has been created. Here are your login details:</p>
  179. <div style="background: white; padding: 20px; border-radius: 4px; margin: 20px 0; border-left: 4px solid #667eea;">
  180. <p style="margin: 0 0 10px 0;"><strong>Username:</strong> <code style="background: #f0f0f0; padding: 2px 6px; border-radius: 3px;">{username}</code></p>
  181. <p style="margin: 0;"><strong>Password:</strong> <code style="background: #f0f0f0; padding: 2px 6px; border-radius: 3px;">{password}</code></p>
  182. </div>
  183. <div style="text-align: center; margin: 30px 0;">
  184. <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>
  185. </div>
  186. <p style="font-size: 14px; color: #666; border-top: 1px solid #ddd; padding-top: 20px; margin-top: 20px;">
  187. <strong>Security Note:</strong> For security reasons, please change your password after your first login.
  188. </p>
  189. <p style="font-size: 14px; color: #999; margin-top: 30px;">
  190. Best regards,<br>
  191. BamBuddy Team
  192. </p>
  193. </div>
  194. </body>
  195. </html>
  196. """
  197. return subject, text_body, html_body
  198. def create_password_reset_email(username: str, password: str, login_url: str) -> tuple[str, str, str]:
  199. """Create password reset email content.
  200. Args:
  201. username: Username of the user
  202. password: New auto-generated password
  203. login_url: URL to login page
  204. Returns:
  205. Tuple of (subject, text_body, html_body)
  206. """
  207. subject = "BamBuddy - Your Password Has Been Reset"
  208. text_body = f"""Your BamBuddy password has been reset.
  209. Your login details:
  210. Username: {username}
  211. New Password: {password}
  212. You can login at: {login_url}
  213. For security reasons, please change your password after logging in.
  214. If you did not request this password reset, please contact your administrator immediately.
  215. Best regards,
  216. BamBuddy Team
  217. """
  218. html_body = f"""<!DOCTYPE html>
  219. <html>
  220. <head>
  221. <meta charset="utf-8">
  222. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  223. </head>
  224. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
  225. <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 20px; border-radius: 8px 8px 0 0;">
  226. <h1 style="color: white; margin: 0; font-size: 24px;">Password Reset</h1>
  227. </div>
  228. <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; border: 1px solid #ddd; border-top: none;">
  229. <p style="font-size: 16px;">Your BamBuddy password has been reset.</p>
  230. <div style="background: white; padding: 20px; border-radius: 4px; margin: 20px 0; border-left: 4px solid #667eea;">
  231. <p style="margin: 0 0 10px 0;"><strong>Username:</strong> <code style="background: #f0f0f0; padding: 2px 6px; border-radius: 3px;">{username}</code></p>
  232. <p style="margin: 0;"><strong>New Password:</strong> <code style="background: #f0f0f0; padding: 2px 6px; border-radius: 3px;">{password}</code></p>
  233. </div>
  234. <div style="text-align: center; margin: 30px 0;">
  235. <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>
  236. </div>
  237. <div style="background: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; padding: 15px; margin: 20px 0;">
  238. <p style="margin: 0; font-size: 14px; color: #856404;">
  239. <strong>⚠️ Security Alert:</strong> If you did not request this password reset, please contact your administrator immediately.
  240. </p>
  241. </div>
  242. <p style="font-size: 14px; color: #666; border-top: 1px solid #ddd; padding-top: 20px; margin-top: 20px;">
  243. <strong>Security Note:</strong> For security reasons, please change your password after logging in.
  244. </p>
  245. <p style="font-size: 14px; color: #999; margin-top: 30px;">
  246. Best regards,<br>
  247. BamBuddy Team
  248. </p>
  249. </div>
  250. </body>
  251. </html>
  252. """
  253. return subject, text_body, html_body