Source types, connection test, server folders, uploads and OAuth sign-in for the Conectar dialog; sign-in for the web app with fastapi-users, the API left open
This commit is contained in:
+158
@@ -0,0 +1,158 @@
|
||||
"""Sign-in for the web app (fastapi-users): users, the domains each may see, and a session
|
||||
cookie. It decides only what the web app shows; no API route requires a session, so
|
||||
pipelines, the FHIR door and scripts answer as before.
|
||||
|
||||
Users live in the platform database (`config.users`). The first administrator comes from
|
||||
AUTH_ADMIN_EMAIL and AUTH_ADMIN_PASSWORD at startup; AUTH_SECRET signs the sessions (without
|
||||
it, one is made and kept in the data folder).
|
||||
"""
|
||||
|
||||
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="")
|
||||
# the domains the web app shows this user (an administrator sees every one)
|
||||
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():
|
||||
"""The platform database, opened asynchronously (SQLite: its `config` file attached)."""
|
||||
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(0o600)
|
||||
return path.read_text().strip()
|
||||
|
||||
|
||||
class Manager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
|
||||
@property
|
||||
def reset_password_token_secret(self) -> str: # type: ignore[override]
|
||||
return _secret()
|
||||
|
||||
@property
|
||||
def verification_token_secret(self) -> str: # type: ignore[override]
|
||||
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", # behind HTTPS
|
||||
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( # an administrator adds users
|
||||
users.get_register_router(UserRead, UserCreate),
|
||||
prefix="/users",
|
||||
tags=["users"],
|
||||
dependencies=admins_only,
|
||||
)
|
||||
|
||||
|
||||
async def first_admin() -> None:
|
||||
"""The users table, and the administrator AUTH_ADMIN_EMAIL names (once)."""
|
||||
async with _engine().begin() as connection:
|
||||
if connection.dialect.name != "sqlite": # SQLite: the attached file is the schema
|
||||
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)) # fmt: skip
|
||||
await manager.create(admin)
|
||||
except UserAlreadyExists:
|
||||
pass
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
||||
await first_admin()
|
||||
yield
|
||||
Reference in New Issue
Block a user