244 lines
9.9 KiB
Python
244 lines
9.9 KiB
Python
"""
|
|
FastAPI Authentication Router (/api/v1/auth)
|
|
Implements Hybrid Authentication:
|
|
- Local Authentication with Admin fallback
|
|
- Google OAuth 2.0 institutional login
|
|
- Moodle Delegated Authentication
|
|
- Impersonation mode for Administrators
|
|
- Dual Token JWT management with HttpOnly cookies
|
|
"""
|
|
from typing import Optional
|
|
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
|
|
from pydantic import ValidationError
|
|
|
|
from app.models.user import User
|
|
from app.models.setting import SystemSetting
|
|
from app.services.user_service import UserService
|
|
from app.services.jwt_service import JWTService
|
|
from app.services.moodle_client import moodle_client
|
|
from app.services.audit_service import AuditService
|
|
from dependencies import get_current_user, require_roles, get_token_from_request
|
|
from database import get_flask_app
|
|
from schemas.auth import (
|
|
LoginRequest,
|
|
GoogleAuthRequest,
|
|
MoodleAuthRequest,
|
|
ImpersonateRequest,
|
|
RefreshTokenRequest
|
|
)
|
|
|
|
auth_router = APIRouter(prefix="/api/v1/auth", tags=["Authentication"])
|
|
user_service = UserService()
|
|
flask_app = get_flask_app()
|
|
|
|
|
|
@auth_router.get("/providers")
|
|
def get_auth_providers():
|
|
"""Retorna los métodos de autenticación habilitados y configuración de cliente Google."""
|
|
with flask_app.app_context():
|
|
local_val = str(SystemSetting.get_value('auth_local_enabled', 'true') or 'true').lower() in ('true', '1')
|
|
google_val = str(SystemSetting.get_value('auth_google_enabled', 'false') or 'false').lower() in ('true', '1')
|
|
moodle_val = str(SystemSetting.get_value('auth_moodle_enabled', 'false') or 'false').lower() in ('true', '1')
|
|
google_client_id = str(SystemSetting.get_value('google_client_id', '') or '')
|
|
demo_access_enabled = str(SystemSetting.get_value('demo_access_enabled', 'true') or 'true').lower() in ('true', '1')
|
|
|
|
return {
|
|
'status': 'success',
|
|
'providers': {
|
|
'local': local_val,
|
|
'google': google_val,
|
|
'moodle': moodle_val
|
|
},
|
|
'google_client_id': google_client_id,
|
|
'demo_access_enabled': demo_access_enabled
|
|
}
|
|
|
|
|
|
@auth_router.post("/login")
|
|
def login(payload: LoginRequest, response: Response):
|
|
"""Inicio de sesión local nativo (Access + Refresh tokens)."""
|
|
with flask_app.app_context():
|
|
local_enabled = str(SystemSetting.get_value('auth_local_enabled', 'true') or 'true').lower() in ('true', '1')
|
|
|
|
user = user_service.authenticate(payload.email, payload.password)
|
|
if not user:
|
|
AuditService.log(
|
|
action='LOGIN_FAILED',
|
|
module='auth',
|
|
user_email=payload.email,
|
|
details=f"Intento de inicio de sesión fallido para {payload.email}. Credenciales incorrectas o cuenta inactiva."
|
|
)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Credenciales de acceso incorrectas o cuenta inactiva."
|
|
)
|
|
|
|
is_admin = user.is_admin() or getattr(user, 'role', '').upper() == 'ADMIN'
|
|
if not local_enabled and not is_admin:
|
|
AuditService.log(
|
|
action='LOGIN_BLOCKED',
|
|
module='auth',
|
|
user=user,
|
|
entity_id=user.id,
|
|
details=f"Acceso local con contraseña bloqueado para {user.email}. Método deshabilitado por administración."
|
|
)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="El acceso local con contraseña está deshabilitado por el administrador. Inicie sesión mediante Google OAuth o Moodle."
|
|
)
|
|
|
|
AuditService.log(
|
|
action='LOGIN',
|
|
module='auth',
|
|
user=user,
|
|
entity_id=user.id,
|
|
details=f"Inicio de sesión exitoso (Autenticación Local) - Rol: {user.role}"
|
|
)
|
|
|
|
tokens = JWTService.generate_tokens(user)
|
|
profile = user_service.get_profile_data(user)
|
|
|
|
response.set_cookie(
|
|
key="access_token",
|
|
value=tokens["access_token"],
|
|
httponly=True,
|
|
samesite="lax",
|
|
path="/"
|
|
)
|
|
response.set_cookie(
|
|
key="refresh_token",
|
|
value=tokens["refresh_token"],
|
|
httponly=True,
|
|
samesite="lax",
|
|
max_age=7 * 24 * 3600,
|
|
path="/api/v1/auth/refresh"
|
|
)
|
|
|
|
return {
|
|
'status': 'success',
|
|
'access_token': tokens['access_token'],
|
|
'refresh_token': tokens['refresh_token'],
|
|
'token_type': tokens['token_type'],
|
|
'expires_in': tokens['expires_in'],
|
|
'user': profile
|
|
}
|
|
|
|
|
|
@auth_router.post("/google")
|
|
def google_auth(payload: GoogleAuthRequest, response: Response):
|
|
"""Inicio de sesión delegado institucional Google OAuth 2.0."""
|
|
with flask_app.app_context():
|
|
google_enabled = str(SystemSetting.get_value('auth_google_enabled', 'false') or 'false').lower() in ('true', '1')
|
|
if not google_enabled:
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="El inicio de sesión con Google no está habilitado.")
|
|
|
|
email = payload.email.strip().lower()
|
|
allowed_domains_str = str(SystemSetting.get_value('google_allowed_domains', 'unicaba.edu.ar') or 'unicaba.edu.ar')
|
|
allowed_domains = [d.strip().lower() for d in allowed_domains_str.split(',') if d.strip()]
|
|
|
|
email_domain = email.split('@')[1] if '@' in email else ''
|
|
if allowed_domains and email_domain not in allowed_domains:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail=f"Dominio @{email_domain} no autorizado. Sólo se permiten cuentas institucionales: {allowed_domains_str}."
|
|
)
|
|
|
|
user = user_service.get_or_create_google_user(
|
|
email=email,
|
|
name=payload.name or email.split('@')[0],
|
|
photo=payload.photo
|
|
)
|
|
|
|
tokens = JWTService.generate_tokens(user)
|
|
profile = user_service.get_profile_data(user)
|
|
|
|
response.set_cookie(key="access_token", value=tokens["access_token"], httponly=True, samesite="lax", path="/")
|
|
return {
|
|
'status': 'success',
|
|
'access_token': tokens['access_token'],
|
|
'refresh_token': tokens['refresh_token'],
|
|
'token_type': tokens['token_type'],
|
|
'expires_in': tokens['expires_in'],
|
|
'user': profile
|
|
}
|
|
|
|
|
|
@auth_router.post("/moodle")
|
|
def moodle_auth(payload: MoodleAuthRequest, response: Response):
|
|
"""Inicio de sesión delegado con Moodle (verificando DNI o credenciales de campus)."""
|
|
with flask_app.app_context():
|
|
moodle_enabled = str(SystemSetting.get_value('auth_moodle_enabled', 'false') or 'false').lower() in ('true', '1')
|
|
if not moodle_enabled:
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="El inicio de sesión con Moodle no está habilitado.")
|
|
|
|
user = user_service.authenticate_moodle(payload.username, payload.password)
|
|
if not user:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Credenciales de Moodle inválidas o usuario no sincronizado.")
|
|
|
|
tokens = JWTService.generate_tokens(user)
|
|
profile = user_service.get_profile_data(user)
|
|
|
|
response.set_cookie(key="access_token", value=tokens["access_token"], httponly=True, samesite="lax", path="/")
|
|
return {
|
|
'status': 'success',
|
|
'access_token': tokens['access_token'],
|
|
'refresh_token': tokens['refresh_token'],
|
|
'token_type': tokens['token_type'],
|
|
'expires_in': tokens['expires_in'],
|
|
'user': profile
|
|
}
|
|
|
|
|
|
@auth_router.get("/me")
|
|
def get_current_user_profile(user: User = Depends(get_current_user)):
|
|
"""Retorna la ficha del perfil del usuario actualmente autenticado."""
|
|
with flask_app.app_context():
|
|
profile = user_service.get_profile_data(user)
|
|
return {
|
|
'status': 'success',
|
|
'user': profile
|
|
}
|
|
|
|
|
|
@auth_router.post("/logout")
|
|
def logout(request: Request, response: Response):
|
|
"""Cierra la sesión y revoca los tokens activos."""
|
|
token = get_token_from_request(request)
|
|
if token:
|
|
try:
|
|
JWTService.revoke_token(token)
|
|
except Exception:
|
|
pass
|
|
|
|
response.delete_cookie(key="access_token", path="/")
|
|
response.delete_cookie(key="refresh_token", path="/api/v1/auth/refresh")
|
|
return {'status': 'success', 'message': 'Sesión cerrada exitosamente.'}
|
|
|
|
|
|
@auth_router.post("/refresh")
|
|
def refresh_token(request: Request, response: Response, payload: Optional[RefreshTokenRequest] = None):
|
|
"""Renueva el token de acceso a partir de un refresh token válido."""
|
|
token = (payload and payload.refresh_token) or request.cookies.get('refresh_token')
|
|
if not token:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="No se proporcionó refresh token.")
|
|
|
|
with flask_app.app_context():
|
|
try:
|
|
decoded = JWTService.decode_token(token, expected_type='refresh')
|
|
user_id = decoded.get('sub')
|
|
user = User.query.get(int(user_id))
|
|
if not user or not user.is_active:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Usuario no encontrado o inactivo.")
|
|
|
|
tokens = JWTService.generate_tokens(user)
|
|
response.set_cookie(key="access_token", value=tokens["access_token"], httponly=True, samesite="lax", path="/")
|
|
return {
|
|
'status': 'success',
|
|
'access_token': tokens['access_token'],
|
|
'refresh_token': tokens['refresh_token'],
|
|
'token_type': tokens['token_type'],
|
|
'expires_in': tokens['expires_in']
|
|
}
|
|
except Exception as e:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f"Refresh token inválido: {str(e)}")
|