d3a337992c
Path traversal fix in SPA fallback, admin-only host delete, login rate limit with 3 attempts and Telegram alert, JWT validated against active users in DB, and DOMPurify for agent report HTML. Co-authored-by: Cursor <cursoragent@cursor.com>
79 lines
2.4 KiB
Python
79 lines
2.4 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, Request
|
|
|
|
from pydantic import BaseModel, Field
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
|
|
|
|
from app.auth.jwt_auth import CurrentUser, create_access_token, get_current_user
|
|
|
|
from app.config import get_settings
|
|
|
|
from app.database import get_db
|
|
|
|
from app.services.login_rate_limit import (
|
|
|
|
ensure_login_allowed,
|
|
|
|
record_login_failure,
|
|
|
|
record_login_success,
|
|
|
|
)
|
|
|
|
from app.services.user_auth import authenticate_user
|
|
|
|
|
|
|
|
router = APIRouter(prefix="/auth", tags=["auth"])
|
|
|
|
|
|
|
|
|
|
|
|
class LoginRequest(BaseModel):
|
|
|
|
username: str
|
|
|
|
password: str
|
|
|
|
|
|
|
|
|
|
|
|
class TokenResponse(BaseModel):
|
|
|
|
access_token: str
|
|
|
|
token_type: str = "bearer"
|
|
|
|
username: str
|
|
|
|
role: str
|
|
|
|
|
|
|
|
|
|
|
|
class MeResponse(BaseModel):
|
|
|
|
username: str
|
|
|
|
role: str
|
|
|
|
|
|
|
|
|
|
|
|
@router.post("/login", response_model=TokenResponse)
|
|
|
|
def login(body: LoginRequest, request: Request, db: Session = Depends(get_db)) -> TokenResponse:
|
|
|
|
settings = get_settings()
|
|
|
|
if not settings.sac_admin_password and not _has_any_user(db):
|
|
|
|
raise HTTPException(
|
|
|
|
status_code=503,
|
|
|
|
detail="SAC UI users are not configured (run alembic upgrade and set SAC_ADMIN_PASSWORD for bootstrap)",
|
|
|
|
)
|
|
|
|
|
|
|
|
ip_address = ensure_login_allowed(db, request)
|
|
|
|
|
|
|
|
user = authenticate_user(db, body.username, body.password)
|
|
|
|
if user is None:
|
|
|
|
record_login_failure(db, ip_address=ip_address, username=body.username)
|
|
|
|
db.commit()
|
|
|
|
raise HTTPException(status_code=401, detail="Invalid username or password")
|
|
|
|
|
|
|
|
record_login_success(db, ip_address=ip_address, username=user.username)
|
|
|
|
db.commit()
|
|
|
|
|
|
|
|
token = create_access_token(user.username, user.role)
|
|
|
|
return TokenResponse(
|
|
|
|
access_token=token,
|
|
|
|
username=user.username,
|
|
|
|
role=user.role,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
@router.get("/me", response_model=MeResponse)
|
|
|
|
def me(current_user: CurrentUser = Depends(get_current_user)) -> MeResponse:
|
|
|
|
return MeResponse(username=current_user.username, role=current_user.role)
|
|
|
|
|
|
|
|
|
|
|
|
def _has_any_user(db: Session) -> bool:
|
|
|
|
from sqlalchemy import func, select
|
|
|
|
|
|
|
|
from app.models.user import User
|
|
|
|
|
|
|
|
try:
|
|
|
|
count = db.scalar(select(func.count()).select_from(User)) or 0
|
|
|
|
return count > 0
|
|
|
|
except Exception:
|
|
|
|
db.rollback()
|
|
|
|
return False
|
|
|