158 lines
4.9 KiB
Python
158 lines
4.9 KiB
Python
import os
|
|
import secrets
|
|
import uuid
|
|
from collections.abc import AsyncIterator
|
|
from contextlib import asynccontextmanager
|
|
from functools import cache
|
|
from fastapi import APIRouter, Depends, FastAPI
|
|
from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin, schemas
|
|
from fastapi_users.authentication import AuthenticationBackend, CookieTransport, JWTStrategy
|
|
from fastapi_users.exceptions import UserAlreadyExists
|
|
from fastapi_users_db_sqlalchemy import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
|
|
from sqlalchemy import JSON, String, event, make_url, text
|
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
|
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
|
from core.domains import Domain
|
|
from persistance.config import DATA_DIR, platform_url
|
|
|
|
SESSION_HOURS = 10
|
|
SCHEMA = "config"
|
|
|
|
|
|
class Base(DeclarativeBase):
|
|
pass
|
|
|
|
|
|
class User(SQLAlchemyBaseUserTableUUID, Base):
|
|
__tablename__ = "users"
|
|
__table_args__ = {"schema": SCHEMA}
|
|
name: Mapped[str] = mapped_column(String(120), default="")
|
|
domains: Mapped[list[str]] = mapped_column(JSON, default=list)
|
|
|
|
|
|
class UserRead(schemas.BaseUser[uuid.UUID]):
|
|
name: str = ""
|
|
domains: list[Domain] = []
|
|
|
|
|
|
class UserCreate(schemas.BaseUserCreate):
|
|
name: str = ""
|
|
domains: list[Domain] = []
|
|
|
|
|
|
class UserUpdate(schemas.BaseUserUpdate):
|
|
name: str | None = None
|
|
domains: list[Domain] | None = None
|
|
|
|
|
|
@cache
|
|
def _engine():
|
|
url = make_url(platform_url())
|
|
if url.drivername.startswith("sqlite"):
|
|
engine = create_async_engine(url.set(drivername="sqlite+aiosqlite"))
|
|
|
|
@event.listens_for(engine.sync_engine, "connect")
|
|
def _attach(connection, _record):
|
|
path = DATA_DIR / f"platform__{SCHEMA}.db"
|
|
connection.execute(f"ATTACH DATABASE '{path}' AS {SCHEMA}")
|
|
|
|
return engine
|
|
return create_async_engine(url.set(drivername="postgresql+asyncpg"))
|
|
|
|
|
|
async def _session() -> AsyncIterator[AsyncSession]:
|
|
async with async_sessionmaker(_engine(), expire_on_commit=False)() as session:
|
|
yield session
|
|
|
|
|
|
async def _users(session: AsyncSession = Depends(_session)):
|
|
yield SQLAlchemyUserDatabase(session, User)
|
|
|
|
|
|
@cache
|
|
def _secret() -> str:
|
|
if found := os.environ.get("AUTH_SECRET"):
|
|
return found
|
|
path = DATA_DIR / "auth_secret"
|
|
if not path.exists():
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(secrets.token_urlsafe(48))
|
|
path.chmod(384)
|
|
return path.read_text().strip()
|
|
|
|
|
|
class Manager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
|
|
@property
|
|
def reset_password_token_secret(self) -> str:
|
|
return _secret()
|
|
|
|
@property
|
|
def verification_token_secret(self) -> str:
|
|
return _secret()
|
|
|
|
|
|
async def _manager(users=Depends(_users)):
|
|
yield Manager(users)
|
|
|
|
|
|
backend = AuthenticationBackend(
|
|
name="cookie",
|
|
transport=CookieTransport(
|
|
cookie_name="isssteleon_session",
|
|
cookie_max_age=SESSION_HOURS * 3600,
|
|
cookie_secure=os.environ.get("AUTH_COOKIE_SECURE", "") == "1",
|
|
cookie_samesite="lax",
|
|
),
|
|
get_strategy=lambda: JWTStrategy(secret=_secret(), lifetime_seconds=SESSION_HOURS * 3600),
|
|
)
|
|
users = FastAPIUsers[User, uuid.UUID](_manager, [backend])
|
|
current_user = users.current_user(active=True)
|
|
router = APIRouter()
|
|
router.include_router(users.get_auth_router(backend), prefix="/auth", tags=["auth"])
|
|
router.include_router(users.get_users_router(UserRead, UserUpdate), prefix="/users", tags=["users"])
|
|
admins_only = [Depends(users.current_user(active=True, superuser=True))]
|
|
router.include_router(
|
|
users.get_register_router(UserRead, UserCreate),
|
|
prefix="/users",
|
|
tags=["users"],
|
|
dependencies=admins_only,
|
|
)
|
|
|
|
|
|
async def first_admin() -> None:
|
|
async with _engine().begin() as connection:
|
|
if connection.dialect.name != "sqlite":
|
|
await connection.execute(text(f"create schema if not exists {SCHEMA}"))
|
|
await connection.run_sync(Base.metadata.create_all)
|
|
email, password = (os.environ.get("AUTH_ADMIN_EMAIL"), os.environ.get("AUTH_ADMIN_PASSWORD"))
|
|
if not (email and password):
|
|
return
|
|
async with async_sessionmaker(_engine(), expire_on_commit=False)() as session:
|
|
manager = Manager(SQLAlchemyUserDatabase(session, User))
|
|
try:
|
|
admin = UserCreate(
|
|
email=email,
|
|
password=password,
|
|
is_superuser=True,
|
|
name="Administrador",
|
|
domains=list(Domain),
|
|
)
|
|
await manager.create(admin)
|
|
except UserAlreadyExists:
|
|
pass
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
|
import fcntl
|
|
|
|
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
|
with open(DATA_DIR / "startup.lock", "w") as lock:
|
|
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
try:
|
|
_secret()
|
|
await first_admin()
|
|
finally:
|
|
fcntl.flock(lock, fcntl.LOCK_UN)
|
|
yield
|