""" NeuroCheck — Email Utility Sends OTP emails for password reset via SMTP. Supported providers (set via environment variables): Option A — Brevo (recommended, free 300 emails/day): SMTP_EMAIL = your@email.com SMTP_PASSWORD = your Brevo SMTP key SMTP_HOST = smtp-relay.brevo.com SMTP_PORT = 587 Option B — Gmail (requires App Password): SMTP_EMAIL = yourname@gmail.com SMTP_PASSWORD = 16-char app password SMTP_HOST = smtp.gmail.com (default) SMTP_PORT = 587 (default) Option C — Any SMTP provider: Set SMTP_HOST, SMTP_PORT, SMTP_EMAIL, SMTP_PASSWORD accordingly If SMTP not configured: OTP is returned in API response (dev mode). """ from __future__ import annotations import os import smtplib import random import string import hashlib from datetime import datetime, timedelta, timezone from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from loguru import logger SMTP_EMAIL = os.environ.get("SMTP_EMAIL", "") SMTP_PASSWORD = os.environ.get("SMTP_PASSWORD", "") SMTP_HOST = os.environ.get("SMTP_HOST", "smtp.gmail.com") SMTP_PORT = int(os.environ.get("SMTP_PORT", "587")) OTP_EXPIRY_MINUTES = 15 def generate_otp(length: int = 6) -> str: """Generate a 6-digit numeric OTP.""" return "".join(random.choices(string.digits, k=length)) def hash_otp(otp: str) -> str: """Hash the OTP before storing (SHA-256).""" return hashlib.sha256(otp.encode()).hexdigest() def verify_otp(plain_otp: str, stored_hash: str) -> bool: """Check if plain OTP matches stored hash.""" return hash_otp(plain_otp) == stored_hash def otp_expiry() -> str: """Return UTC expiry timestamp (15 minutes from now).""" return (datetime.now(timezone.utc) + timedelta(minutes=OTP_EXPIRY_MINUTES)).isoformat() def send_otp_email(to_email: str, username: str, otp: str) -> bool: """ Send OTP email via Gmail SMTP. Returns True on success, False on failure. """ if not SMTP_EMAIL or not SMTP_PASSWORD: logger.warning("[Email] SMTP_EMAIL or SMTP_PASSWORD not set. Cannot send email.") return False subject = "NeuroCheck — Password Reset Code" html_body = f"""
MS Clinical Assistant
Hello {username}, we received a request to reset your NeuroCheck password. Use the code below to proceed:
This code expires in {OTP_EXPIRY_MINUTES} minutes
If you didn't request this, you can safely ignore this email. Your password will not be changed.
NeuroCheck AI — MS Clinical Decision Support
Built by Dr. Avasarala (UKY) & Dr. Kadambari (NITW)