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.2.tar.gz (72.1 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.2-py3-none-any.whl (35.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: vexen_auth-0.1.2.tar.gz
  • Upload date:
  • Size: 72.1 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.2.tar.gz
Algorithm Hash digest
SHA256 25e93d29b819e483d095fe191efdc41c8ada46f057533967231252feba6e60ae
MD5 5042f4a689cb9fc8687389df94efbf4f
BLAKE2b-256 fd3a1eb0dfcf63fdd9cc8cdd11276c7b6ff3bc3f5fc235ca7740c3d260be9658

See more details on using hashes here.

Provenance

The following attestation bundles were made for vexen_auth-0.1.2.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.2-py3-none-any.whl.

File metadata

  • Download URL: vexen_auth-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 35.6 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.2-py3-none-any.whl
Algorithm Hash digest
SHA256 92963b3fa224daf7b48dedb8c938537aef8d5df3e04c355c36811c3530ff63f0
MD5 f3d6174f14ff2b2a3eb54e0a8db233d6
BLAKE2b-256 b423ed6189b8764d4a2b4dc9b0a64bc8f9ab38c7d51a6274d3ccae38782a9ae8

See more details on using hashes here.

Provenance

The following attestation bundles were made for vexen_auth-0.1.2-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