Skip to main content

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

Metadata

Release files for vexen-auth 0.1.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for vexen-auth 0.1.3
File Size Uploaded Provenance
vexen_auth-0.1.3.tar.gz 72.1 kB With provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for vexen-auth 0.1.3
File Interpreter ABI Platform
vexen_auth-0.1.3-py3-none-any.whl Python 3 none any Details

Total release size: 107.8 kB

Release files / vexen_auth-0.1.3.tar.gz

Download URL vexen_auth-0.1.3.tar.gz
Size 72.1 kB
Tags Source
SHA-256 checksum
How to use checksums
e225e9c6b47bddd78b209731a6f5dcb538b5d93b27709d928c7d8915f080674d
BLAKE2b-256 checksum
How to use checksums
277e0461c432bcad5392c1ddbfa8d6d0e0b48630e5c9f45c56783f820b84b301
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 3, 2025.

Transparency log

Release files / vexen_auth-0.1.3-py3-none-any.whl

Download URL vexen_auth-0.1.3-py3-none-any.whl
Size 35.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1bbb1a2d704ce85c240e30d51bb153cf2ca164c23607b2214fec76c15c4da4c1
BLAKE2b-256 checksum
How to use checksums
d0a6f6c2f07ebaf6a3c0d524fbba8c7bb74cc83ade0d6d73b958735c8447cebd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 3, 2025.

Transparency log

Security for vexen-auth 0.1.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for vexen_auth-0.1.3.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 3, 2025.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page