email_service.py 11 KB

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