Skip to main content

Authentication system with hexagonal architecture

Project description

vexen-auth

Sistema de autenticación para aplicaciones Vexen con arquitectura hexagonal.

Características

  • JWT Authentication: Tokens de acceso y refresh
  • Provider Local: Autenticación email/password
  • Sistema Extensible: Listo para OAuth, SAML, etc.
  • Password Hashing: Bcrypt con salt automático
  • Token Management: Manejo y revocación de tokens
  • SQLAlchemy Async: Integración con SQLAlchemy 2.0+
  • Arquitectura Hexagonal: Separación clara de capas
  • Type Safe: Totalmente tipado
  • Integración: Compatible con vexen-user y vexen-rbac

Instalación

pip install vexen-auth

Uso Rápido

import asyncio
from vexen_auth import VexenAuth, AuthConfig, LoginRequest

async def main():
    # Configurar VexenAuth
    config = AuthConfig(
        database_url="postgresql+asyncpg://user:pass@localhost/db",
        secret_key="your-secret-key",
        access_token_expires_minutes=15,
        refresh_token_expires_days=30,
    )

    # Usar VexenAuth
    async with VexenAuth(config) as auth:
        # Login
        login_req = LoginRequest(
            email="user@example.com",
            password="SecurePassword123"
        )
        response = await auth.service.login(login_req)

        if response:
            print(f"Access token: {response.access_token}")
            print(f"User ID: {response.user_id}")

if __name__ == "__main__":
    asyncio.run(main())

Arquitectura

VexenAuth sigue arquitectura hexagonal con clara separación de responsabilidades:

vexen_auth/
├── domain/              # Lógica de negocio y entidades
│   ├── entity/         # Entidades de dominio (AuthToken, UserCredential)
│   ├── repository/     # Puertos de repositorio (interfaces)
│   └── provider/       # Puerto de proveedor de auth (interface)
│
├── application/        # Casos de uso y DTOs
│   ├── dto/           # Data Transfer Objects
│   ├── usecase/       # Casos de uso (Login, Refresh, Logout, Verify)
│   └── service/       # Servicio de aplicación
│
└── infraestructure/   # Implementaciones externas
    ├── provider/      # Implementaciones de proveedores (Local, OAuth, etc.)
    ├── security/      # Utilidades JWT y password
    └── output/
        └── persistence/
            └── sqlalchemy/  # Adaptador SQLAlchemy

Configuración

Opciones de AuthConfig

@dataclass
class AuthConfig:
    # Base de datos
    database_url: str                      # URL de conexión PostgreSQL
    adapter: str = "sqlalchemy"            # Adaptador de persistencia

    # Configuración JWT
    secret_key: str                        # Clave de firma JWT
    algorithm: str = "HS256"               # Algoritmo JWT
    access_token_expires_minutes: int = 15 # TTL del access token
    refresh_token_expires_days: int = 30   # TTL del refresh token

    # Integración externa (opcional)
    user_service = None                    # Instancia VexenUser
    user_repository = None                 # Repositorio de usuarios directo

API Reference

Servicio de Autenticación

Login

from vexen_auth import LoginRequest

request = LoginRequest(
    email="user@example.com",
    password="password123"
)

response = await auth.service.login(request)
# Retorna: LoginResponse | None
# Response contiene: access_token, refresh_token, user_id

Refresh Token

from vexen_auth import RefreshTokenRequest

request = RefreshTokenRequest(
    refresh_token="..."
)

response = await auth.service.refresh(request)
# Retorna: RefreshTokenResponse | None
# Response contiene: access_token

Logout

from vexen_auth import LogoutRequest

request = LogoutRequest(
    refresh_token="..."
)

success = await auth.service.logout(request)
# Retorna: bool

Verificar Token

from vexen_auth import VerifyTokenRequest

request = VerifyTokenRequest(
    access_token="..."
)

response = await auth.service.verify(request)
# Retorna: VerifyTokenResponse | None
# Response contiene: valid, user_id

Integración con vexen-user

VexenAuth necesita información de usuarios de vexen-user. Puedes integrarlo de dos formas:

Opción 1: Acceso Directo a Repositorio

from vexen_user import VexenUser

# Inicializar vexen-user
user_system = VexenUser(database_url="postgresql+asyncpg://...")
await user_system.init()

# Configurar VexenAuth con repositorio de usuarios
config = AuthConfig(
    database_url="postgresql+asyncpg://...",
    secret_key="...",
    user_repository=user_system.repository,
)

auth = VexenAuth(config)
await auth.init()

Opción 2: Usando vexen-core

from vexen_core import VexenContainer, VexenConfig

config = VexenConfig(
    database_url="postgresql+asyncpg://...",
    secret_key="...",
)

async with VexenContainer(config) as vexen:
    # Auth ya está integrado con user
    response = await vexen.auth.service.login(request)

Schema de Base de Datos

VexenAuth crea dos tablas:

user_credentials

  • id (int, PK)
  • user_id (str, unique, FK a tabla users)
  • password_hash (str)
  • created_at (datetime)
  • updated_at (datetime, nullable)

auth_tokens

  • id (int, PK)
  • user_id (str, FK a tabla users)
  • token (str, unique, refresh token hasheado)
  • expires_at (datetime)
  • created_at (datetime)
  • revoked (bool)

Consideraciones de Seguridad

  1. Password Hashing: Usa bcrypt con salting automático
  2. Token Storage: Refresh tokens se hashean (SHA-256) antes de almacenar
  3. Token Expiration: Expiración configurable para access y refresh tokens
  4. Token Revocation: Logout explícito revoca refresh tokens
  5. JWT Algorithm: Por defecto HS256, configurable

Extender Proveedores de Autenticación

VexenAuth soporta múltiples proveedores de autenticación. Para agregar un nuevo proveedor:

from vexen_auth.domain.provider import IAuthProviderPort

class OAuthProvider(IAuthProviderPort):
    async def authenticate(self, email: str, password: str):
        # Implementar autenticación OAuth
        pass

    async def refresh_token(self, refresh_token: str):
        # Implementar refresh de token
        pass

    # Implementar otros métodos requeridos...

Desarrollo

# Instalar dependencias
pip install -e ".[dev]"

# Ejecutar ejemplo
python example_usage.py

# Formatear código
ruff format .

# Linting
ruff check . --fix

Licencia

MIT

Proyectos Relacionados

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

vexen_auth-0.1.1.tar.gz (55.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

vexen_auth-0.1.1-py3-none-any.whl (31.3 kB view details)

Uploaded Python 3

File details

Details for the file vexen_auth-0.1.1.tar.gz.

File metadata

  • Download URL: vexen_auth-0.1.1.tar.gz
  • Upload date:
  • Size: 55.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for vexen_auth-0.1.1.tar.gz
Algorithm Hash digest
SHA256 ff5e8c525e61aeeccb209a491e8786b136440c8443cba817adf2cdba898f8a7a
MD5 b86acf5fd9713489a7b85c4af3a87600
BLAKE2b-256 55d3cfae8fa0a35621161456b928ec2643529d5a8028e8a6d440eefd0e234376

See more details on using hashes here.

Provenance

The following attestation bundles were made for vexen_auth-0.1.1.tar.gz:

Publisher: python-publish.yml on vexen-labs/vexen-auth

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file vexen_auth-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: vexen_auth-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 31.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for vexen_auth-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 7f89b2b30f523f0804902a9433a8d2772797397110d3de793c216576671754fa
MD5 8f4159b1b4e91afca17a9a2f3ee62917
BLAKE2b-256 548a5f7d96c47944fa8594ed8d71f6a17ad9926d1911a442dbf03ade8a8df1ac

See more details on using hashes here.

Provenance

The following attestation bundles were made for vexen_auth-0.1.1-py3-none-any.whl:

Publisher: python-publish.yml on vexen-labs/vexen-auth

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page