Spaces:
Running
Running
File size: 16,356 Bytes
3533fb9 b7698ad 3533fb9 af296c7 3533fb9 af296c7 3533fb9 af296c7 3533fb9 af296c7 3533fb9 af296c7 3533fb9 af296c7 3533fb9 af296c7 3533fb9 af296c7 3533fb9 af296c7 3533fb9 af296c7 3533fb9 af296c7 3533fb9 | 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 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 | from datetime import timedelta
from fastapi import APIRouter, Depends, HTTPException, status, Request
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from google.oauth2 import id_token
from google.auth.transport import requests
from app.db.session import get_db
from app.core import security, config
from app.crud import user as crud_user
from app.schemas import schemas
from app.models.models import User, UserSession
from app.services.email_service import send_verification_email
import hashlib
import logging
logger = logging.getLogger(__name__)
router = APIRouter()
@router.post("/token", response_model=schemas.Token)
async def login_for_access_token(
request: Request,
db: Session = Depends(get_db),
form_data: OAuth2PasswordRequestForm = Depends()
):
# Rate Limit: 10 attempts per minute per IP
if not security.check_rate_limit(f"ratelimit:login:{request.client.host}", 10, 60):
raise HTTPException(status_code=429, detail="Too many login attempts. Please wait.")
# Support login by username OR email
user = crud_user.get_user_by_username(db, username=form_data.username)
if not user:
user = crud_user.get_user_by_email(db, email=form_data.username)
if not user or not security.verify_password(form_data.password, user.hashed_password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
if getattr(user, 'two_factor_enabled', False) is True:
methods = ["totp"]
if user.recovery_codes:
methods.append("recovery_code")
return {"two_factor_required": True, "username": user.username, "methods": methods}
access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = security.create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
# Create Session
token_hash = hashlib.sha256(access_token.encode()).hexdigest()
new_session = UserSession(
user_id=user.id,
token_hash=token_hash,
device_info="Mock Device (Browser)",
ip_address="127.0.0.1"
)
db.add(new_session)
db.commit()
return {"access_token": access_token, "token_type": "bearer", "username": user.username}
@router.post("/register", response_model=schemas.VerificationResponse)
def register_user(request: Request, user_in: schemas.UserCreate, db: Session = Depends(get_db)):
# Rate Limit: 3 registrations per hour per IP (very strict)
if not security.check_rate_limit(f"ratelimit:register:{request.client.host}", 3, 3600):
raise HTTPException(status_code=429, detail="Too many registration attempts. Please wait.")
db_user = crud_user.get_user_by_email(db, email=user_in.email)
if db_user:
raise HTTPException(status_code=400, detail="Email already registered")
db_user = crud_user.get_user_by_username(db, username=user_in.username)
if db_user:
raise HTTPException(status_code=400, detail="Username already taken")
user = crud_user.create_user(db, user=user_in, is_onboarded=False, ip_address=request.client.host)
user.is_verified = False # Mandatory verification
db.commit()
# Generate and send verification code
code = crud_user.create_verification_code(db, email=user.email)
try:
send_verification_email(user.email, code)
except Exception as e:
logger.error(f"[auth] Verification email failed for {user.email}: {e}")
# We don't fail registration if email sending fails in dev, but in prod we might
db.refresh(user)
return {
"message": "Registration successful. Welcome to Monteeq!",
"email": user.email,
"username": user.username
}
@router.post("/verify-email", response_model=schemas.VerificationResponse)
def verify_email(data: schemas.EmailVerification, db: Session = Depends(get_db)):
if crud_user.verify_code(db, email=data.email, code=data.code):
user = crud_user.get_user_by_email(db, email=data.email)
if user:
# Update is_verified
user.is_verified = True
db.commit()
db.refresh(user)
return {"message": "Email verified successfully", "username": user.username}
raise HTTPException(status_code=400, detail="Invalid or expired verification code")
@router.post("/resend-verification", response_model=schemas.VerificationResponse)
def resend_verification(request: Request, data: schemas.ResendVerification, db: Session = Depends(get_db)):
"""Resend the email verification code. Cooldown + hourly caps per email/IP."""
email_key = (data.email or "").strip().lower()
client_ip = request.client.host if request.client else "unknown"
user = crud_user.get_user_by_email(db, email=data.email)
if not user:
raise HTTPException(status_code=404, detail="Email not registered")
if user.is_verified:
raise HTTPException(status_code=400, detail="Email is already verified.")
# DB-backed cooldown (works even if Redis is down)
age = crud_user.seconds_since_verification_code(db, data.email)
if age is not None and age < 60:
wait = max(1, 60 - int(age))
raise HTTPException(
status_code=429,
detail=f"Please wait {wait} seconds before requesting another verification code.",
)
# 60s cooldown per email (Redis / memory)
if not security.check_rate_limit(f"ratelimit:resend-verify:cool:{email_key}", 1, 60):
raise HTTPException(
status_code=429,
detail="Please wait 60 seconds before requesting another verification code.",
)
# 5 resends per hour per email
if not security.check_rate_limit(f"ratelimit:resend-verify:hour:{email_key}", 5, 3600):
raise HTTPException(
status_code=429,
detail="Too many verification emails. Try again in an hour.",
)
# 10 resends per hour per IP
if not security.check_rate_limit(f"ratelimit:resend-verify:ip:{client_ip}", 10, 3600):
raise HTTPException(
status_code=429,
detail="Too many verification requests from this network. Try again later.",
)
code = crud_user.create_verification_code(db, email=data.email)
try:
send_verification_email(data.email, code)
except Exception as e:
logger.error(f"[auth] Resend verification email failed for {data.email}: {e}")
return {
"message": "A new verification code has been sent to your email.",
"email": data.email,
"username": user.username,
}
@router.post("/google", response_model=schemas.Token)
async def google_auth(request: Request, auth_data: schemas.UserGoogleAuth, db: Session = Depends(get_db)):
try:
idinfo = id_token.verify_oauth2_token(
auth_data.credential, requests.Request(), config.GOOGLE_CLIENT_ID
)
email = idinfo['email']
google_id = idinfo['sub']
name = idinfo.get('name', email.split('@')[0])
picture = idinfo.get('picture')
user = crud_user.get_user_by_email(db, email=email)
if not user:
# Generate a temporary unique username
base_username = name.lower().replace(" ", "")
if not base_username:
base_username = "user"
username = base_username
suffix = 1
while crud_user.get_user_by_username(db, username=username):
username = f"{base_username}{suffix}"
suffix += 1
user_create = schemas.UserCreate(
username=username,
email=email,
full_name=name,
profile_pic=picture,
password=None # Google auth users don't have passwords
)
# Google users are auto-verified
user = crud_user.create_user(db, user=user_create, google_id=google_id, is_onboarded=False, ip_address=request.client.host)
user.is_verified = True
db.commit()
db.refresh(user)
else:
# If user exists but is trying to 'sign up' with Google, we might want to distinguish.
# But the requirement is: "if the email was registered, tell him to login"
# If they are using the Google auth flow, they ARE logging in.
# However, if they don't have a google_id, they originally signed up with a password.
if not user.google_id:
# This matches "tell him to login" (using his password)
raise HTTPException(
status_code=400,
detail="Email already registered with password. Please log in with your credentials."
)
if picture and not user.profile_pic:
user.profile_pic = picture
user.is_verified = True
db.commit()
db.refresh(user)
if getattr(user, 'two_factor_enabled', False) is True:
methods = ["totp"]
if user.recovery_codes:
methods.append("recovery_code")
return {"two_factor_required": True, "username": user.username, "methods": methods}
access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = security.create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
# Create Session
token_hash = hashlib.sha256(access_token.encode()).hexdigest()
new_session = UserSession(
user_id=user.id,
token_hash=token_hash,
device_info="Google Auth Device",
ip_address="127.0.0.1"
)
db.add(new_session)
db.commit()
return {"access_token": access_token, "token_type": "bearer", "username": user.username}
except ValueError as e:
print(f"Google Auth Error: {str(e)}")
raise HTTPException(status_code=400, detail=f"Invalid Google token: {str(e)}")
@router.post("/verify-2fa", response_model=schemas.Token)
def verify_login_2fa(
data: schemas.TokenData, # Reusing schemas to avoid new ones
db: Session = Depends(get_db)
):
"""Verify TOTP code for login."""
if not data.username or not data.code:
raise HTTPException(status_code=400, detail="Missing username or code")
user = crud_user.get_user_by_username(db, username=data.username)
if not user or not user.totp_secret:
raise HTTPException(status_code=401, detail="Could not validate credentials")
import pyotp
import json
is_valid = False
# Try TOTP
totp = pyotp.TOTP(user.totp_secret)
if totp.verify(data.code):
is_valid = True
# Try Recovery Codes
if not is_valid and user.recovery_codes:
codes = json.loads(user.recovery_codes)
hashed_input = hashlib.sha256(data.code.replace("-", "").upper().encode()).hexdigest()
if hashed_input in codes:
is_valid = True
# Consume the code
codes.remove(hashed_input)
user.recovery_codes = json.dumps(codes)
db.commit()
if not is_valid:
raise HTTPException(status_code=401, detail="Invalid verification code")
access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = security.create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
# Create Session
token_hash = hashlib.sha256(access_token.encode()).hexdigest()
new_session = UserSession(
user_id=user.id,
token_hash=token_hash,
device_info="2FA Verified Device",
ip_address="127.0.0.1"
)
db.add(new_session)
db.commit()
return {"access_token": access_token, "token_type": "bearer", "username": user.username}
@router.post("/forgot-password")
def forgot_password(request: Request, data: schemas.ResendVerification, db: Session = Depends(get_db)):
"""Send a secure reset link (rate-limited)."""
email_key = (data.email or "").strip().lower()
client_ip = request.client.host if request.client else "unknown"
if not security.check_rate_limit(f"ratelimit:forgot-password:cool:{email_key}", 1, 60):
raise HTTPException(
status_code=429,
detail="Please wait 60 seconds before requesting another reset email.",
)
if not security.check_rate_limit(f"ratelimit:forgot-password:hour:{email_key}", 5, 3600):
raise HTTPException(
status_code=429,
detail="Too many password reset emails. Try again in an hour.",
)
if not security.check_rate_limit(f"ratelimit:forgot-password:ip:{client_ip}", 10, 3600):
raise HTTPException(
status_code=429,
detail="Too many password reset requests from this network. Try again later.",
)
user = crud_user.get_user_by_email(db, email=data.email)
if not user:
# Avoid email enumeration — same message as success
return {"message": "If that email is registered, a reset link has been sent."}
import secrets
from datetime import datetime, timedelta
from sqlalchemy.exc import IntegrityError
from app.models.models import VerificationCode
token = secrets.token_urlsafe(32)
expires_at = datetime.utcnow() + timedelta(hours=1)
now = datetime.utcnow()
existing = crud_user.get_latest_verification_code(db, user.email)
if existing:
existing.code = token
existing.expires_at = expires_at
existing.created_at = now
db.commit()
else:
db_code = VerificationCode(
email=user.email, code=token, expires_at=expires_at, created_at=now
)
db.add(db_code)
try:
db.commit()
except IntegrityError:
db.rollback()
crud_user._sync_verification_codes_sequence(db)
existing = crud_user.get_latest_verification_code(db, user.email)
if existing:
existing.code = token
existing.expires_at = expires_at
existing.created_at = now
db.commit()
else:
db.add(
VerificationCode(
email=user.email, code=token, expires_at=expires_at, created_at=now
)
)
db.commit()
try:
from app.services.email_service import send_password_reset_email
send_password_reset_email(user.email, token)
except Exception as e:
logger.error(f"[auth] Password reset email failed for {user.email}: {e}")
return {"message": "A secure reset link has been sent to your email."}
@router.post("/reset-password")
def reset_password(data: schemas.PasswordReset, db: Session = Depends(get_db)):
"""Verify link token and update password."""
# We reuse verify_code logic which checks code (token) and expiry
if crud_user.verify_code(db, email=data.email, code=data.code):
user = crud_user.get_user_by_email(db, email=data.email)
if user:
user.hashed_password = security.get_password_hash(data.new_password)
db.commit()
return {"message": "Password updated successfully. You can now log in."}
raise HTTPException(status_code=400, detail="Invalid or expired reset link")
@router.get("/check-username")
def check_username(username: str, db: Session = Depends(get_db)):
user = crud_user.get_user_by_username(db, username=username)
return {"available": user is None}
@router.get("/check-email")
def check_email(email: str, db: Session = Depends(get_db)):
user = crud_user.get_user_by_email(db, email=email)
return {"available": user is None}
@router.get("/check-email-exists")
def check_email_exists(email: str, db: Session = Depends(get_db)):
"""Check if an email is registered."""
user = crud_user.get_user_by_email(db, email=email)
return {"exists": user is not None}
|