import random import jwt import datetime import os from dotenv import load_dotenv from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail # ----------------------------- # LOAD ENV VARIABLES # ----------------------------- load_dotenv() SECRET_KEY = os.getenv("JWT_SECRET", "fallback_secret") SENDGRID_API_KEY = os.getenv("SENDGRID_API_KEY") FROM_EMAIL = os.getenv("SENDGRID_FROM_EMAIL") # ----------------------------- # GENERATE 6 DIGIT OTP # ----------------------------- def generate_otp(): otp = str(random.randint(100000, 999999)) return otp # ----------------------------- # CREATE JWT TOKEN # ----------------------------- def create_jwt(email): payload = { "email": email, "exp": datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) } token = jwt.encode(payload, SECRET_KEY, algorithm="HS256") return token # ----------------------------- # VERIFY JWT TOKEN # ----------------------------- def verify_jwt(token): try: decoded = jwt.decode(token, SECRET_KEY, algorithms=["HS256"]) return decoded except jwt.ExpiredSignatureError: print("Token expired") return None except jwt.InvalidTokenError: print("Invalid token") return None # ----------------------------- # SEND OTP VIA SENDGRID EMAIL # ----------------------------- def send_otp_via_sendgrid(receiver_email, otp): message = Mail( from_email=FROM_EMAIL, to_emails=receiver_email, subject="FitPlan AI OTP Verification", html_content=f"""

Your FitPlan AI Login OTP

Your verification code is:

{otp}

This OTP is valid for login verification.

""" ) try: sg = SendGridAPIClient(SENDGRID_API_KEY) response = sg.send(message) if response.status_code == 202: return True else: return False except Exception as e: print("SendGrid Error:", e) return False