feat(auth): owner-bound bot tokens and self-service bot management

This commit is contained in:
2026-04-14 00:34:44 +09:00
parent 9787cf3159
commit 2dab17cbb1
16 changed files with 576 additions and 35 deletions
@@ -0,0 +1,97 @@
"""restore bot principal owner user id
Revision ID: 20260414_0011
Revises: 20260413_0010
Create Date: 2026-04-14 10:30:00
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
revision = "20260414_0011"
down_revision = "20260413_0010"
branch_labels = None
depends_on = None
def _column_exists(inspector, table_name: str, column_name: str) -> bool:
return any(column["name"] == column_name for column in inspector.get_columns(table_name))
def _index_exists(inspector, table_name: str, index_name: str) -> bool:
return any(index["name"] == index_name for index in inspector.get_indexes(table_name))
def _fk_exists(inspector, table_name: str, fk_name: str) -> bool:
return any(fk.get("name") == fk_name for fk in inspector.get_foreign_keys(table_name))
def upgrade() -> None:
bind = op.get_bind()
inspector = inspect(bind)
if not _column_exists(inspector, "bot_principals", "owner_user_id"):
op.add_column("bot_principals", sa.Column("owner_user_id", sa.Text(), nullable=True))
bind.execute(
sa.text(
"""
WITH fallback_owner AS (
SELECT id
FROM users
ORDER BY created_at ASC, id ASC
LIMIT 1
)
UPDATE bot_principals b
SET owner_user_id = f.id
FROM fallback_owner f
WHERE b.owner_user_id IS NULL
"""
)
)
unresolved = bind.execute(sa.text("SELECT COUNT(*) FROM bot_principals WHERE owner_user_id IS NULL")).scalar()
if unresolved and int(unresolved) > 0:
raise RuntimeError("bot_principals.owner_user_id backfill failed: users 테이블에 fallback 소유주가 필요합니다")
op.alter_column("bot_principals", "owner_user_id", existing_type=sa.Text(), nullable=False)
inspector = inspect(bind)
if not _index_exists(inspector, "bot_principals", "idx_bot_principals_owner_active_created"):
op.create_index(
"idx_bot_principals_owner_active_created",
"bot_principals",
["owner_user_id", "is_active", sa.text("created_at DESC")],
unique=False,
)
inspector = inspect(bind)
if not _fk_exists(inspector, "bot_principals", "fk_bot_principals_owner_user"):
op.create_foreign_key(
"fk_bot_principals_owner_user",
"bot_principals",
"users",
["owner_user_id"],
["id"],
ondelete="RESTRICT",
)
def downgrade() -> None:
bind = op.get_bind()
inspector = inspect(bind)
if _fk_exists(inspector, "bot_principals", "fk_bot_principals_owner_user"):
op.drop_constraint("fk_bot_principals_owner_user", "bot_principals", type_="foreignkey")
inspector = inspect(bind)
if _index_exists(inspector, "bot_principals", "idx_bot_principals_owner_active_created"):
op.drop_index("idx_bot_principals_owner_active_created", table_name="bot_principals")
inspector = inspect(bind)
if _column_exists(inspector, "bot_principals", "owner_user_id"):
op.drop_column("bot_principals", "owner_user_id")