feat: add authentication and user management with Authentik integration
Build and Push / build (release) Successful in 1m16s

- Add PostgreSQL database with async SQLAlchemy
- Add Alembic migrations for schema management
- Add User, Role, UserPreferences, ApiKey models
- Add auth endpoints: /auth/me, /auth/users, /auth/users/sync-from-authentik
- Add token validation via Authentik userinfo endpoint
- Add bulk user sync from Authentik admin API
- Add database health check to diagnostics

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Jeroen Schweitzer
2026-01-01 20:25:03 +01:00
co-authored by Claude Opus 4.5
parent cdb6344013
commit 4f45f9bf37
22 changed files with 1753 additions and 23 deletions
+21
View File
@@ -0,0 +1,21 @@
Alembic Migrations for Core-API
This directory contains database migrations managed by Alembic.
Commands:
# Generate a new migration (after changing models)
alembic revision --autogenerate -m "description"
# Apply all pending migrations
alembic upgrade head
# Rollback last migration
alembic downgrade -1
# View migration history
alembic history
# View current revision
alembic current
See https://alembic.sqlalchemy.org for more documentation.
+98
View File
@@ -0,0 +1,98 @@
"""
Alembic Environment Configuration
Async migration environment for SQLAlchemy 2.0 with asyncpg.
"""
import asyncio
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
# Import our models and config
from src.config import get_settings
from src.db.database import Base
# Import all models to ensure they're registered with Base.metadata
from src.db.models import User, Role, UserRole, UserPreferences, ApiKey # noqa: F401
# Alembic Config object
config = context.config
# Interpret the config file for Python logging
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# Model metadata for autogenerate support
target_metadata = Base.metadata
# Get database URL from our settings
settings = get_settings()
db_url = settings.database_url
if db_url.startswith("postgresql://"):
db_url = db_url.replace("postgresql://", "postgresql+asyncpg://", 1)
def run_migrations_offline() -> None:
"""
Run migrations in 'offline' mode.
Generates SQL script without connecting to the database.
"""
context.configure(
url=db_url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection: Connection) -> None:
"""
Run migrations with the given connection.
"""
context.configure(
connection=connection,
target_metadata=target_metadata,
)
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations() -> None:
"""
Run migrations in 'online' mode with async engine.
"""
configuration = config.get_section(config.config_ini_section) or {}
configuration["sqlalchemy.url"] = db_url
connectable = async_engine_from_config(
configuration,
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
def run_migrations_online() -> None:
"""
Run migrations in 'online' mode.
"""
asyncio.run(run_async_migrations())
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+25
View File
@@ -0,0 +1,25 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}
@@ -0,0 +1,138 @@
"""Create auth tables
Revision ID: 001
Revises:
Create Date: 2026-01-01
Creates the initial authentication and authorization tables:
- users: User accounts synced from Authentik
- roles: Domain-scoped permission roles
- user_roles: User-Role association table
- user_preferences: User settings and preferences
- api_keys: API key authentication
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision: str = "001"
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# Users table
op.create_table(
"users",
sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
sa.Column("authentik_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("email", sa.String(255), nullable=False),
sa.Column("name", sa.String(255), nullable=False),
sa.Column("avatar_url", sa.String(500), nullable=True),
sa.Column("api_keys_enabled", sa.Boolean(), nullable=False, server_default="true"),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
sa.Column("last_login", sa.DateTime(timezone=True), nullable=True),
)
op.create_index("ix_users_authentik_id", "users", ["authentik_id"], unique=True)
op.create_index("ix_users_email", "users", ["email"], unique=True)
# Roles table
op.create_table(
"roles",
sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
sa.Column("name", sa.String(100), nullable=False, comment="Role name in format domain:action"),
sa.Column("domain", sa.String(50), nullable=False, comment="Permission domain"),
sa.Column("action", sa.String(20), nullable=False, comment="Permission action"),
sa.Column("authentik_group", sa.String(255), nullable=True, comment="Corresponding Authentik group name"),
)
op.create_index("ix_roles_name", "roles", ["name"], unique=True)
op.create_index("ix_roles_domain", "roles", ["domain"])
op.create_index("ix_roles_authentik_group", "roles", ["authentik_group"], unique=True)
# User-Role association table
op.create_table(
"user_roles",
sa.Column("user_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), primary_key=True),
sa.Column("role_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("roles.id", ondelete="CASCADE"), primary_key=True),
)
# User preferences table
op.create_table(
"user_preferences",
sa.Column("user_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), primary_key=True),
sa.Column("theme", sa.String(20), nullable=False, server_default="system", comment="Theme preference"),
sa.Column("default_room", sa.String(50), nullable=False, server_default="front-hall", comment="Default room"),
sa.Column("preferences_json", postgresql.JSONB(), nullable=False, server_default="{}"),
)
# API keys table
op.create_table(
"api_keys",
sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
sa.Column("user_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
sa.Column("name", sa.String(100), nullable=False, comment="Human-readable key name"),
sa.Column("key_hash", sa.String(255), nullable=False, comment="SHA-256 hash of the API key"),
sa.Column("key_prefix", sa.String(8), nullable=False, comment="First 8 chars for identification"),
sa.Column("scopes", postgresql.ARRAY(sa.String()), nullable=True, comment="Optional scope restriction"),
sa.Column("expires_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("last_used_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
)
op.create_index("ix_api_keys_user_id", "api_keys", ["user_id"])
# Seed initial roles (domain:action combinations)
roles_table = sa.table(
"roles",
sa.column("id", postgresql.UUID),
sa.column("name", sa.String),
sa.column("domain", sa.String),
sa.column("action", sa.String),
sa.column("authentik_group", sa.String),
)
domains = [
"control-room",
"library",
"media",
"ai",
"housekeeper",
"developer",
"documents",
"gaming",
"admin",
]
actions = ["viewer", "user", "editor", "admin"]
roles_data = []
for domain in domains:
for action in actions:
role_name = f"{domain}:{action}"
authentik_group = f"tatlock-{domain}-{action}"
roles_data.append({
"id": sa.text("gen_random_uuid()"),
"name": role_name,
"domain": domain,
"action": action,
"authentik_group": authentik_group,
})
# Insert roles using raw SQL for UUID generation
for role in roles_data:
op.execute(
f"""
INSERT INTO roles (id, name, domain, action, authentik_group)
VALUES (gen_random_uuid(), '{role["name"]}', '{role["domain"]}', '{role["action"]}', '{role["authentik_group"]}')
"""
)
def downgrade() -> None:
op.drop_table("api_keys")
op.drop_table("user_preferences")
op.drop_table("user_roles")
op.drop_table("roles")
op.drop_table("users")