phase-8: polish, global search, audit log, packaging, and demo docs
This commit is contained in:
@@ -1,7 +1,11 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from collections import defaultdict, deque
|
||||
import threading
|
||||
import time
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user
|
||||
from ..core.exceptions import CodedHTTPException
|
||||
from ..core.security import create_access_token, verify_password
|
||||
from ..models.masters import User
|
||||
from ..schemas.auth import LoginRequest, TokenResponse, UserOut
|
||||
@@ -9,6 +13,34 @@ from ..services.settings_service import get_demo_as_of_date
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
MAX_LOGIN_ATTEMPTS = 15
|
||||
LOGIN_WINDOW_SECONDS = 60.0
|
||||
_login_attempts: dict[str, deque[float]] = defaultdict(deque)
|
||||
_rate_limit_lock = threading.Lock()
|
||||
|
||||
|
||||
def reset_login_rate_limiter() -> None:
|
||||
"""Clear sliding-window login attempt counters (used in tests)."""
|
||||
with _rate_limit_lock:
|
||||
_login_attempts.clear()
|
||||
|
||||
|
||||
def _enforce_login_rate_limit(client_ip: str, email_norm: str) -> None:
|
||||
now = time.monotonic()
|
||||
cutoff = now - LOGIN_WINDOW_SECONDS
|
||||
key = f"{client_ip}:{email_norm}"
|
||||
with _rate_limit_lock:
|
||||
attempts = _login_attempts[key]
|
||||
while attempts and attempts[0] <= cutoff:
|
||||
attempts.popleft()
|
||||
if len(attempts) >= MAX_LOGIN_ATTEMPTS:
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="Too many login attempts. Please wait a minute.",
|
||||
code="RATE_LIMITED",
|
||||
)
|
||||
attempts.append(now)
|
||||
|
||||
|
||||
def _build_user_out(user: User, db: Session) -> UserOut:
|
||||
return UserOut(
|
||||
@@ -24,8 +56,10 @@ def _build_user_out(user: User, db: Session) -> UserOut:
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenResponse)
|
||||
def login(payload: LoginRequest, db: Session = Depends(get_db)):
|
||||
def login(payload: LoginRequest, request: Request, db: Session = Depends(get_db)):
|
||||
email_norm = payload.email.strip().lower()
|
||||
client_ip = request.client.host if request.client else "unknown"
|
||||
_enforce_login_rate_limit(client_ip, email_norm)
|
||||
user = (
|
||||
db.query(User)
|
||||
.options(joinedload(User.department))
|
||||
|
||||
Reference in New Issue
Block a user