70 lines
2.5 KiB
Python
70 lines
2.5 KiB
Python
# ==============================================================================
|
|
# Servicio de Autenticación y Control de Sesión
|
|
# ==============================================================================
|
|
from datetime import timedelta
|
|
from typing import Optional, Tuple
|
|
from fastapi import HTTPException, status
|
|
from app.repositories.auth_repository import AuthRepository
|
|
from app.core.security import verificar_password, crear_access_token
|
|
from app.schemas.auth_schema import LoginResponse, UserSessionDTO
|
|
|
|
|
|
class AuthService:
|
|
@staticmethod
|
|
def autenticar_usuario(
|
|
username: str,
|
|
password_raw: str,
|
|
workstation_name: Optional[str] = None,
|
|
expires_delta: Optional[timedelta] = None,
|
|
) -> Tuple[LoginResponse, str]:
|
|
"""Valida credenciales, genera token JWT y registra auditoría."""
|
|
user_row = AuthRepository.obtener_usuario_por_nombre(username)
|
|
if not user_row:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Credenciales inválidas: usuario o contraseña incorrectos",
|
|
)
|
|
|
|
stored_password = user_row.get("Password", "")
|
|
if not verificar_password(password_raw, stored_password):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Credenciales inválidas: usuario o contraseña incorrectos",
|
|
)
|
|
|
|
user_id = user_row["UsuarioID"]
|
|
nombre = user_row["Nombre"].strip()
|
|
system_param = user_row.get("SystemParameter")
|
|
role = "SUPERVISOR" if system_param == 1 else "OPERADOR"
|
|
|
|
# Generar Token JWT con soporte de rol y parámetros de sesión
|
|
token_data = {
|
|
"sub": str(user_id),
|
|
"username": nombre,
|
|
"workstation": workstation_name or "",
|
|
"role": role,
|
|
"system_parameter": system_param,
|
|
}
|
|
token = crear_access_token(token_data, expires_delta=expires_delta)
|
|
|
|
# Registrar auditoría en usrlogin
|
|
AuthRepository.registrar_evento_login(user_id)
|
|
|
|
user_dto = UserSessionDTO(
|
|
user_id=user_id,
|
|
username=nombre,
|
|
role=role,
|
|
system_parameter=system_param,
|
|
)
|
|
|
|
response = LoginResponse(
|
|
status="ok",
|
|
message="Autenticación exitosa",
|
|
user=user_dto,
|
|
workstation=workstation_name,
|
|
token=token,
|
|
token_type="bearer",
|
|
)
|
|
|
|
return response, token
|