feat: Funcion de sistema tenants

This commit is contained in:
2026-02-23 13:01:24 -07:00
parent ceea67eb2b
commit 1ccc39732b
58 changed files with 1889 additions and 315 deletions

View File

@@ -4,7 +4,7 @@ Authentication Endpoints - ServiceManagerWeb
Endpoints para autenticación y autorización
"""
from fastapi import APIRouter, HTTPException, status, Depends
from fastapi import APIRouter, HTTPException, status, Depends, Request
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
@@ -18,7 +18,9 @@ from app.core.config import get_settings
from app.models.user import User
from app.models.tenant import Tenant
from app.services.audit_service import AuditService
from app.services.token_service import TokenService
from app.api.deps import oauth2_scheme, get_current_user
from app.core.cache import cache, cache_key
from app.api.schemas.auth import (
LoginRequest, LoginResponse, RefreshTokenRequest, TokenResponse,
TwoFactorStatusResponse, TwoFactorSetupResponse,
@@ -38,6 +40,7 @@ settings = get_settings()
@router.post("/login", response_model=LoginResponse)
async def login(
login_data: LoginRequest,
request: Request,
db: AsyncSession = Depends(get_db)
):
"""
@@ -58,13 +61,85 @@ async def login(
email=login_data.email,
tenant_slug=login_data.tenant_slug
)
# Rate limiting (best-effort): by IP before any tenant/user lookup.
if settings.RATE_LIMIT_ENABLED and not settings.TESTING:
client_ip = request.client.host if request.client else "unknown"
ip_key = cache_key("rl", "login", "ip", client_ip)
ip_count = await cache.incr(ip_key, 1)
if ip_count == 1:
await cache.expire(ip_key, settings.LOGIN_RATE_LIMIT_WINDOW_SECONDS)
if ip_count is not None and ip_count > settings.LOGIN_RATE_LIMIT_IP_MAX_ATTEMPTS:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="Too many login attempts. Try again later.",
headers={"Retry-After": str(settings.LOGIN_RATE_LIMIT_WINDOW_SECONDS)},
)
# 1. Buscar usuario en base de datos
query = select(User).where(User.email == login_data.email)
# 1. Validar tenant
tenant_result = await db.execute(
select(Tenant).where(Tenant.slug == login_data.tenant_slug)
)
tenant = tenant_result.scalar_one_or_none()
if tenant is None:
logger.warning(
"Login failed - tenant not found",
email=login_data.email,
tenant_slug=login_data.tenant_slug,
)
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Tenant not found",
)
# Rate limiting (best-effort): by (tenant,email) to slow brute force.
ident_key = None
if settings.RATE_LIMIT_ENABLED and not settings.TESTING:
email_norm = login_data.email.strip().lower()
ident_key = cache_key("rl", "login", "id", str(tenant.id), email_norm)
ident_count = await cache.incr(ident_key, 1)
if ident_count == 1:
await cache.expire(ident_key, settings.LOGIN_RATE_LIMIT_WINDOW_SECONDS)
if ident_count is not None and ident_count > settings.LOGIN_RATE_LIMIT_ID_MAX_ATTEMPTS:
try:
await AuditService.log(
db=db,
tenant_id=tenant.id,
user_id=None,
action="user.login_rate_limited",
resource_type="user",
resource_id=None,
metadata={
"email": email_norm,
"tenant_slug": login_data.tenant_slug,
"ip": request.client.host if request.client else None,
"scope": "tenant_email",
"window_seconds": settings.LOGIN_RATE_LIMIT_WINDOW_SECONDS,
"max_attempts": settings.LOGIN_RATE_LIMIT_ID_MAX_ATTEMPTS,
},
request=request,
)
await db.commit()
except Exception as e:
logger.warning("Failed to log rate limit audit entry", error=str(e))
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="Too many login attempts. Try again later.",
headers={"Retry-After": str(settings.LOGIN_RATE_LIMIT_WINDOW_SECONDS)},
)
# 2. Buscar usuario en base de datos (aislado por tenant)
query = select(User).where(
User.email == login_data.email,
User.tenant_id == tenant.id,
)
result = await db.execute(query)
user = result.scalar_one_or_none()
# 2. Verificar usuario y contraseña
# 3. Verificar usuario y contraseña
if not user or not security.verify_password(login_data.password, user.password_hash):
logger.warning(
"Login failed - invalid credentials",
@@ -89,21 +164,21 @@ async def login(
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Credenciales inválidas"
detail="Invalid credentials",
)
# 3. Verificar si está activo
# 4. Verificar si está activo
if not user.is_active:
logger.warning(
"Login failed - user inactive",
email=login_data.email
)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Usuario inactivo"
status_code=status.HTTP_403_FORBIDDEN,
detail="User inactive",
)
# 4. Verificar 2FA si está habilitado
# 5. Verificar 2FA si está habilitado
if user.totp_enabled:
if not login_data.totp_code:
# Indicar al frontend que debe pedir el código TOTP
@@ -128,6 +203,24 @@ async def login(
access_token = security.create_access_token(token_data)
refresh_token = security.create_refresh_token(token_data)
# Persist refresh token so it can be revoked/validated later
try:
await TokenService.create_refresh_token(
db=db,
user=user,
refresh_token=refresh_token,
user_agent=request.headers.get("user-agent"),
ip_address=request.client.host if request.client else None,
)
await db.commit()
except Exception as e:
# If persistence fails, do not leak tokens
logger.error("Failed to persist refresh token", error=str(e), user_id=str(user.id))
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Service temporarily unavailable",
)
# Registrar login exitoso en auditoría
try:
@@ -150,6 +243,10 @@ async def login(
tenant_slug=login_data.tenant_slug,
user_id=str(user.id)
)
# Best-effort: clear per-identity limiter on success.
if ident_key:
await cache.delete(ident_key)
return LoginResponse(
access_token=access_token,
@@ -198,7 +295,20 @@ async def refresh_token(
detail="Invalid refresh token"
)
# TODO: Check if refresh token exists in database and is not revoked
# Check token exists in database and is not revoked/expired
db_token = await TokenService.verify_refresh_token(db=db, refresh_token=refresh_data.refresh_token)
if db_token is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid refresh token",
)
# Defensive: ensure DB token belongs to same subject
if str(db_token.user_id) != str(payload.get("sub")):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid refresh token",
)
# Create new access token
token_data = {
@@ -243,7 +353,19 @@ async def logout(
detail="Invalid token"
)
# TODO: Revoke refresh token in database
# Revoke all active refresh tokens for this user (logout invalidates refresh)
try:
import uuid
user_id = uuid.UUID(payload["sub"])
await TokenService.revoke_all_user_tokens(
db=db,
user_id=user_id,
revoked_by_user_id=user_id,
)
await db.commit()
except Exception as e:
logger.warning("Failed to revoke refresh tokens on logout", error=str(e))
# Registrar logout en auditoría
try: