Spaces:
Paused
Paused
File size: 12,806 Bytes
feeca53 3141044 feeca53 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 | import os
import time
import random
import smtplib
from datetime import datetime
from functools import wraps
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# Flask & Extensions
from flask import Flask, request, jsonify
from flask_limiter import Limiter
from flask_cors import CORS
from flask_limiter.util import get_remote_address
from dotenv import load_dotenv
# REQUIRED FOR HUGGING FACE SPACES (Proxy Fix)
from werkzeug.middleware.proxy_fix import ProxyFix
# ================= LOAD ENV =================
load_dotenv()
app = Flask(__name__)
# ================= HUGGING FACE CONFIGURATION =================
# Hugging Face runs behind a proxy (Nginx). We must tell Flask to trust
# the X-Forwarded-For headers so Flask-Limiter sees the real user IP,
# not the proxy IP.
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1)
CORS(app)
# ================= BASIC CONFIG =================
YOUR_WEB_APP_NAME = os.getenv("WEBAPPNAME", "xyzapp")
CURRENT_YEAR = str(datetime.now().year)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# Ensure your Templates folder exists in the Space files
TEMPLATE_PATH = os.path.join(BASE_DIR, "Templates", "template1.html")
REMOVE_WATERMARK = False
# ================= RATE LIMIT =================
# With ProxyFix applied above, get_remote_address will now correctly
# grab the real user's IP address.
limiter = Limiter(
key_func=get_remote_address,
app=app,
default_limits=["200 per hour"],
storage_uri="memory://" # Explicitly use memory storage
)
# ================= SMTP CONFIG =================
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
GMAIL_EMAIL = os.getenv("GMAIL_EMAIL")
APP_PASSWORD = os.getenv("APP_PASSWORD")
FROM_EMAIL = os.getenv("FROM_EMAIL", GMAIL_EMAIL)
# ================= SECURITY CONFIG =================
OTP_EXPIRY_SECONDS = 300
MAX_ATTEMPTS = 5
LOCK_TIME = 600
RESEND_COOLDOWN = 60
IP_MAX_ATTEMPTS = 10
IP_BLOCK_TIME = 60
# ================= STORES (IN-MEMORY) =================
# Note: In-memory stores will reset if the Space restarts/sleeps.
otp_store = {}
ip_store = {}
# ================= HTML TEMPLATE =================
def load_template(path: str) -> str:
# Fallback if file is missing to prevent crash
if not os.path.exists(path):
return "<html><body><h1>Your OTP is {{OTP_CODE}}</h1></body></html>"
with open(path, "r", encoding="utf-8") as file:
return file.read()
def apply_template_changes(template: str) -> str:
template = template.replace("{{APP_NAME}}", YOUR_WEB_APP_NAME)
template = template.replace("{{YEAR}}", CURRENT_YEAR)
if REMOVE_WATERMARK:
template = template.replace(
"MailOTP Guard — made with ❤️ by TechBitForge",
""
)
return template
# Load template once on startup
HTML_TEMPLATE = apply_template_changes(
"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Your OTP Code</title>
<style>
/* Global Reset */
body, table, td, a { -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; }
table, td { mso-table-lspace: 0pt; mso-table-rspace: 0pt; }
img { -ms-interpolation-mode: bicubic; border: 0; height: auto; line-height: 100%; outline: none; text-decoration: none; }
table { border-collapse: collapse !important; }
body { height: 100% !important; margin: 0 !important; padding: 0 !important; width: 100% !important; background-color: #f4f7f9; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
/* Mobile Responsive */
@media screen and (max-width: 600px) {
.email-container { width: 100% !important; margin: auto !important; }
.content-padding { padding: 20px !important; }
.otp-code { font-size: 32px !important; letter-spacing: 8px !important; }
}
</style>
</head>
<body style="margin: 0; padding: 0; background-color: #f4f7f9;">
<center>
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px; margin: 40px auto; background-color: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.05);">
<tr>
<td style="padding: 40px 40px 20px 40px; text-align: center;">
<h1 style="margin: 0; font-size: 24px; color: #1a1a1a; font-weight: 700; letter-spacing: -0.5px;">{{APP_NAME}}</h1>
</td>
</tr>
<tr>
<td class="content-padding" style="padding: 0 50px 40px 50px; text-align: center;">
<p style="margin: 0 0 24px 0; font-size: 16px; line-height: 24px; color: #4b5563;">
To complete your sign-in, please use the following one-time password (OTP).
</p>
<table align="center" border="0" cellpadding="0" cellspacing="0" style="margin: 0 auto;">
<tr>
<td style="background-color: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 24px 40px;">
<span class="otp-code" style="font-family: 'Courier New', Courier, monospace; font-size: 42px; font-weight: 800; color: #2563eb; letter-spacing: 12px; display: block; margin-left: 12px;">{{OTP_CODE}}</span>
</td>
</tr>
</table>
<p style="margin: 24px 0 0 0; font-size: 14px; font-weight: 500; color: #64748b;">
This code is valid for <span style="color: #1e293b; font-weight: 600;">5 minutes</span>.
</p>
</td>
</tr>
<tr>
<td style="padding: 0 50px 40px 50px;">
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="background-color: #fffbeb; border-radius: 8px; border-left: 4px solid #f59e0b;">
<tr>
<td style="padding: 16px; font-size: 13px; line-height: 20px; color: #92400e;">
<strong>Security Alert:</strong> For your protection, never share this code with anyone. Our team will never ask for your OTP over the phone or email.
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="padding: 0 50px 40px 50px; text-align: center; border-top: 1px solid #f1f5f9;">
<p style="margin: 20px 0 8px 0; font-size: 12px; color: #94a3b8; line-height: 18px;">
If you did not request this code, you can safely ignore this email. Someone may have entered your email address by mistake.
</p>
<p style="margin: 0; font-size: 12px; color: #cbd5e1;">
© {{YEAR}} {{APP_NAME}}. All rights reserved.
</p>
<p style="margin: 20px 0 0 0; font-size: 11px; color: #94a3b8; text-transform: uppercase; letter-spacing: 1px;">
MailOTP Guard — made with ❤️ by TechBitForge
</p>
</td>
</tr>
</table>
</center>
</body>
</html>
"""
)
# ================= IP BLOCK SYSTEM =================
def is_ip_blocked(ip):
record = ip_store.get(ip)
if not record:
return False
if time.time() > record["blocked_until"]:
ip_store.pop(ip)
return False
return True
def register_ip_failure(ip):
now = time.time()
record = ip_store.setdefault(ip, {
"attempts": 0,
"blocked_until": 0
})
record["attempts"] += 1
if record["attempts"] >= IP_MAX_ATTEMPTS:
record["blocked_until"] = now + IP_BLOCK_TIME
# ================= SEND EMAIL =================
def send_email(email, otp):
if not GMAIL_EMAIL or not APP_PASSWORD:
print("Error: SMTP Credentials missing in Environment Variables")
raise Exception("SMTP Config Missing")
html = HTML_TEMPLATE.replace("{{OTP_CODE}}", otp)
msg = MIMEMultipart()
msg["From"] = FROM_EMAIL
msg["To"] = email
msg["Subject"] = f"{YOUR_WEB_APP_NAME} OTP Verification"
msg.attach(MIMEText(html, "html"))
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
server.starttls()
server.login(GMAIL_EMAIL, APP_PASSWORD)
server.send_message(msg)
# ================= ROUTE: HOME =================
@app.route("/")
def home():
return jsonify({"status": "running", "msg": f"Welcome to {YOUR_WEB_APP_NAME} API"})
# ================= ROUTE: SEND OTP =================
@app.route("/send-otp", methods=["POST"])
@limiter.limit("5 per minute")
def send_otp():
# Behind ProxyFix, remote_addr is now safe
ip = request.remote_addr
if is_ip_blocked(ip):
return jsonify({"error": "IP blocked for 1 minute"}), 429
data = request.get_json(silent=True) or {}
email = data.get("email")
if not email:
register_ip_failure(ip)
return jsonify({"error": "Email required"}), 400
now = time.time()
otp = str(random.randint(100000, 999999))
otp_store[email] = {
"otp": otp,
"expires": now + OTP_EXPIRY_SECONDS,
"attempts": 0,
"locked_until": 0,
"last_sent": now
}
try:
send_email(email, otp)
return jsonify({"message": "OTP sent successfully"})
except Exception as e:
print(f"Mail Error: {e}") # Print error to HF Space logs
register_ip_failure(ip)
return jsonify({"error": "Failed to send email"}), 500
# ================= ROUTE: RESEND OTP =================
@app.route("/resend-otp", methods=["POST"])
@limiter.limit("3 per minute")
def resend_otp():
ip = request.remote_addr
if is_ip_blocked(ip):
return jsonify({"error": "IP blocked for 1 minute"}), 429
data = request.get_json(silent=True) or {}
email = data.get("email")
if not email:
register_ip_failure(ip)
return jsonify({"error": "Email required"}), 400
record = otp_store.get(email)
if not record:
return jsonify({"error": "OTP not requested"}), 400
now = time.time()
if record["locked_until"] > now:
return jsonify({"error": "Account locked"}), 429
if now - record["last_sent"] < RESEND_COOLDOWN:
return jsonify({
"error": "Please wait before resending OTP",
"retry_after": int(RESEND_COOLDOWN - (now - record["last_sent"]))
}), 429
otp = str(random.randint(100000, 999999))
record.update({
"otp": otp,
"expires": now + OTP_EXPIRY_SECONDS,
"attempts": 0,
"last_sent": now
})
try:
send_email(email, otp)
return jsonify({"message": "OTP resent successfully"})
except Exception:
register_ip_failure(ip)
return jsonify({"error": "Failed to resend OTP"}), 500
# ================= ROUTE: VERIFY OTP =================
@app.route("/verify-otp", methods=["POST"])
@limiter.limit("10 per minute")
def verify_otp():
ip = request.remote_addr
if is_ip_blocked(ip):
return jsonify({"error": "IP blocked for 1 minute"}), 429
data = request.get_json(silent=True) or {}
email = data.get("email")
user_otp = data.get("otp")
if not email or not user_otp:
register_ip_failure(ip)
return jsonify({"error": "Missing fields"}), 400
record = otp_store.get(email)
if not record:
register_ip_failure(ip)
return jsonify({"error": "OTP not found"}), 400
now = time.time()
if record["locked_until"] > now:
return jsonify({"error": "Account locked"}), 429
if now > record["expires"]:
otp_store.pop(email)
return jsonify({"error": "OTP expired"}), 400
if record["otp"] != user_otp:
record["attempts"] += 1
register_ip_failure(ip)
if record["attempts"] >= MAX_ATTEMPTS:
record["locked_until"] = now + LOCK_TIME
return jsonify({"error": "Account locked for 10 minutes"}), 429
return jsonify({
"error": "Invalid OTP",
"remaining_attempts": MAX_ATTEMPTS - record["attempts"]
}), 400
otp_store.pop(email)
return jsonify({"message": "OTP verified successfully"})
# ================= RUN =================
if __name__ == "__main__":
# Hugging Face Spaces default port is 7860
app.run(host="0.0.0.0", port=7860, debug=False) |