mirror of
https://github.com/ZTatman/myst.git
synced 2026-11-20 20:07:59 +00:00
refactor(web): rename config module to settings, add shared Forgejo API client
This commit is contained in:
parent
de1b8c9bd8
commit
3c3f47d20e
7 changed files with 175 additions and 62 deletions
|
|
@ -7,9 +7,9 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from app.auth.crypto import encrypt_optional
|
||||
from app.config import get_fernet
|
||||
from app.models.app_settings import AppSettings
|
||||
from app.models.user import LinkedIdentity, User
|
||||
from app.settings import get_fernet
|
||||
|
||||
|
||||
async def find_or_create_user(
|
||||
|
|
@ -44,7 +44,9 @@ async def find_or_create_user(
|
|||
identity.access_token_encrypted = encrypt_optional(fernet, access_token_raw)
|
||||
identity.access_token_expires_at = access_token_expires_at
|
||||
if refresh_token_raw is not None:
|
||||
identity.refresh_token_encrypted = encrypt_optional(fernet, refresh_token_raw)
|
||||
identity.refresh_token_encrypted = encrypt_optional(
|
||||
fernet, refresh_token_raw
|
||||
)
|
||||
user = identity.user
|
||||
if email:
|
||||
user.email = email
|
||||
|
|
|
|||
68
web/app/clients/forgejo.py
Normal file
68
web/app/clients/forgejo.py
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
from app.models.app_settings import AppSettings
|
||||
|
||||
|
||||
async def post(app_settings: AppSettings, path: str, data: dict) -> dict:
|
||||
"""Send a POST request to the Forgejo API.
|
||||
|
||||
Args:
|
||||
app_settings: The application settings.
|
||||
path: The path to the Forgejo API endpoint.
|
||||
data: The data to send in the request.
|
||||
|
||||
Returns:
|
||||
The response from the Forgejo API.
|
||||
"""
|
||||
try:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=app_settings.forgejo_base_url, timeout=30.0
|
||||
) as client:
|
||||
resp = await client.post(
|
||||
path, data=data, headers={"Accept": "application/json"}
|
||||
)
|
||||
except httpx.RequestError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail="Cannot reach Forgejo. Check your connection settings.",
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Forgejo returned an error ({resp.status_code}). Verify your OAuth configuration.",
|
||||
)
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def get(app_settings: AppSettings, path: str, access_token: str) -> dict | list[dict]:
|
||||
"""Send a GET request to the Forgejo API.
|
||||
|
||||
Args:
|
||||
app_settings: The application settings.
|
||||
path: The path to the Forgejo API endpoint.
|
||||
access_token: The authentication token.
|
||||
|
||||
Returns:
|
||||
The response from the Forgejo API as a dictionary or list of dictionaries.
|
||||
"""
|
||||
try:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=app_settings.forgejo_base_url, timeout=30.0
|
||||
) as client:
|
||||
resp = await client.get(
|
||||
path, headers={"Authorization": f"token {access_token}"}
|
||||
)
|
||||
except httpx.RequestError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail="Cannot reach Forgejo. Check your connection settings.",
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Forgejo returned an error ({resp.status_code}). Verify your OAuth configuration.",
|
||||
)
|
||||
return resp.json()
|
||||
|
|
@ -7,25 +7,27 @@ from typing import Annotated
|
|||
from fastapi import Depends, FastAPI, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from sqlalchemy import func as sql_func
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from starlette.responses import Response
|
||||
from sqlalchemy import func as sql_func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
|
||||
from app import models as _models # noqa: F401 - register ORM tables on metadata
|
||||
from app.auth.session import get_current_session, get_optional_session
|
||||
from app.config import get_settings
|
||||
from app.database import Base
|
||||
from app.middleware import SetupRequiredMiddleware
|
||||
from app.models.app_settings import AppSettings
|
||||
from app.models.session import Session as UserBrowserSession
|
||||
from app.routers import auth, links, settings, setup
|
||||
from app.settings import get_settings
|
||||
from app.templating import templates
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Manage database engine lifecycle and load app settings."""
|
||||
|
||||
boot_settings = get_settings()
|
||||
engine = create_async_engine(
|
||||
url=boot_settings.database_url,
|
||||
|
|
@ -69,15 +71,27 @@ async def lifespan(app: FastAPI):
|
|||
await engine.dispose()
|
||||
|
||||
|
||||
# Initialize app
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
|
||||
|
||||
# Middleware
|
||||
app.add_middleware(SetupRequiredMiddleware)
|
||||
|
||||
app.mount("/static", StaticFiles(directory=Path(__file__).parent / "static"), name="static")
|
||||
|
||||
# Static files
|
||||
app.mount(
|
||||
"/static", StaticFiles(directory=Path(__file__).parent / "static"), name="static"
|
||||
)
|
||||
|
||||
|
||||
# Routers
|
||||
app.include_router(auth.router)
|
||||
app.include_router(links.router)
|
||||
app.include_router(settings.router)
|
||||
app.include_router(setup.router)
|
||||
|
||||
|
||||
ERROR_TITLES = {
|
||||
400: "Bad Request",
|
||||
401: "Unauthorized",
|
||||
|
|
@ -88,9 +102,13 @@ ERROR_TITLES = {
|
|||
}
|
||||
|
||||
|
||||
# Http exception handler
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException) -> Response:
|
||||
async def http_exception_handler(
|
||||
request: Request, exc: StarletteHTTPException
|
||||
) -> Response:
|
||||
"""Render a styled error page for browser requests, JSON for API clients."""
|
||||
|
||||
accept = request.headers.get("accept", "")
|
||||
if "text/html" in accept:
|
||||
return templates.TemplateResponse(
|
||||
|
|
@ -108,7 +126,8 @@ async def http_exception_handler(request: Request, exc: StarletteHTTPException)
|
|||
|
||||
@app.get("/", response_class=HTMLResponse)
|
||||
async def root(
|
||||
request: Request, sess: Annotated[UserBrowserSession | None, Depends(get_optional_session)]
|
||||
request: Request,
|
||||
sess: Annotated[UserBrowserSession | None, Depends(get_optional_session)],
|
||||
) -> Response:
|
||||
return templates.TemplateResponse(
|
||||
request,
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ from datetime import UTC, datetime, timedelta
|
|||
from typing import Annotated
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, Cookie, Depends, HTTPException, Request, status
|
||||
from fastapi.responses import RedirectResponse
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
|
@ -13,56 +12,24 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||
from app.auth.crypto import decrypt_token
|
||||
from app.auth.identity import find_or_create_user
|
||||
from app.auth.session import create_session, revoke_session
|
||||
from app.config import get_app_settings, get_fernet
|
||||
from app.clients import forgejo
|
||||
from app.deps import get_db
|
||||
from app.models.app_settings import AppSettings
|
||||
from app.settings import get_app_settings, get_fernet
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
# ── Forgejo API client ──
|
||||
|
||||
|
||||
async def _forgejo_post(app_settings: AppSettings, path: str, data: dict) -> dict:
|
||||
url = f"{app_settings.forgejo_base_url}{path}"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
resp = await client.post(url, data=data, headers={"Accept": "application/json"})
|
||||
except httpx.RequestError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail="Cannot reach Forgejo. Check your connection settings.",
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Forgejo returned an error ({resp.status_code}). Verify your OAuth configuration.",
|
||||
)
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def _forgejo_get(app_settings: AppSettings, path: str, token: str) -> dict:
|
||||
url = f"{app_settings.forgejo_base_url}{path}"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
resp = await client.get(url, headers={"Authorization": f"token {token}"})
|
||||
except httpx.RequestError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail="Cannot reach Forgejo. Check your connection settings.",
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Forgejo returned an error ({resp.status_code}). Verify your OAuth configuration.",
|
||||
)
|
||||
return resp.json()
|
||||
|
||||
|
||||
# ── OAuth CSRF helpers ──
|
||||
|
||||
|
||||
def _set_oauth_state_cookie(response: RedirectResponse, state: str) -> None:
|
||||
"""Set the OAuth state cookie in the response.
|
||||
|
||||
Args:
|
||||
response: The response to set the cookie in.
|
||||
state: The state to set in the cookie.
|
||||
"""
|
||||
response.set_cookie(
|
||||
key="oauth_state",
|
||||
value=state,
|
||||
|
|
@ -74,6 +41,12 @@ def _set_oauth_state_cookie(response: RedirectResponse, state: str) -> None:
|
|||
|
||||
|
||||
def _verify_oauth_state(state: str | None, oauth_state: str | None) -> None:
|
||||
"""Verify the OAuth state and raise an exception if it is invalid.
|
||||
|
||||
Args:
|
||||
state: The state parameter from the OAuth request.
|
||||
oauth_state: The state cookie from the client.
|
||||
"""
|
||||
if not state or not oauth_state or not secrets.compare_digest(state, oauth_state):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
|
|
@ -85,6 +58,16 @@ def _verify_oauth_state(state: str | None, oauth_state: str | None) -> None:
|
|||
|
||||
|
||||
def _parse_token_response(data: dict) -> tuple[str, str | None, datetime | None]:
|
||||
"""Parse the token response from Forgejo and return the access token, refresh token, and expiration time.
|
||||
|
||||
Args:
|
||||
data: The token response from Forgejo.
|
||||
|
||||
Returns:
|
||||
access_token: The access token.
|
||||
refresh_token: The refresh token.
|
||||
expires_at: The expiration time of the access token.
|
||||
"""
|
||||
access_token = data.get("access_token")
|
||||
if not access_token or not isinstance(access_token, str):
|
||||
raise HTTPException(
|
||||
|
|
@ -102,6 +85,16 @@ def _parse_token_response(data: dict) -> tuple[str, str | None, datetime | None]
|
|||
|
||||
|
||||
def _parse_user_response(data: dict) -> tuple[str, str, str | None]:
|
||||
"""Parse the user response from Forgejo and return the provider user id, provider username, and email.
|
||||
|
||||
Args:
|
||||
data: The user response from Forgejo.
|
||||
|
||||
Returns:
|
||||
provider_user_id: The provider user id.
|
||||
provider_username: The provider username.
|
||||
email: The email address of the user.
|
||||
"""
|
||||
provider_user_id = str(data.get("id", "")).strip()
|
||||
provider_username = str(data.get("username", "")).strip()
|
||||
if not provider_user_id or not provider_username:
|
||||
|
|
@ -118,6 +111,15 @@ def _parse_user_response(data: dict) -> tuple[str, str, str | None]:
|
|||
|
||||
|
||||
def _forgejo_oauth_redirect_uri(request: Request, app_settings: AppSettings) -> str:
|
||||
"""Generate the redirect URI for the Forgejo OAuth callback.
|
||||
|
||||
Args:
|
||||
request: The incoming request.
|
||||
app_settings: The application settings.
|
||||
|
||||
Returns:
|
||||
The redirect URI for the Forgejo OAuth callback.
|
||||
"""
|
||||
base_url = app_settings.firebreak_public_base_url.strip().rstrip("/")
|
||||
if base_url:
|
||||
return f"{base_url}/auth/callback/forgejo"
|
||||
|
|
@ -125,8 +127,18 @@ def _forgejo_oauth_redirect_uri(request: Request, app_settings: AppSettings) ->
|
|||
|
||||
|
||||
def _get_oauth_client_secret(app_settings: AppSettings) -> str:
|
||||
"""Get the OAuth client secret from the application settings.
|
||||
|
||||
Args:
|
||||
app_settings: The application settings.
|
||||
|
||||
Returns:
|
||||
The OAuth client secret.
|
||||
"""
|
||||
try:
|
||||
return decrypt_token(get_fernet(), app_settings.forgejo_oauth_client_secret_encrypted)
|
||||
return decrypt_token(
|
||||
get_fernet(), app_settings.forgejo_oauth_client_secret_encrypted
|
||||
)
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
|
|
@ -168,20 +180,20 @@ async def callback_forgejo(
|
|||
state: str | None = None,
|
||||
oauth_state: Annotated[str | None, Cookie()] = None,
|
||||
) -> RedirectResponse:
|
||||
"""Handle Forgejo's OAuth callback and create a local app session."""
|
||||
"""Handle Forgejo's OAuth callback and creates a new app session."""
|
||||
|
||||
_verify_oauth_state(state, oauth_state)
|
||||
|
||||
if not code:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Forgejo did not return an authorization code. The user may have denied consent.",
|
||||
detail="Forgejo did not return an authorization code. The user may have denied access.",
|
||||
)
|
||||
|
||||
client_secret = _get_oauth_client_secret(app_settings)
|
||||
redirect_uri = _forgejo_oauth_redirect_uri(request, app_settings)
|
||||
|
||||
token_data = await _forgejo_post(
|
||||
token_data = await forgejo.post(
|
||||
app_settings,
|
||||
"/login/oauth/access_token",
|
||||
{
|
||||
|
|
@ -194,9 +206,10 @@ async def callback_forgejo(
|
|||
)
|
||||
access_token, refresh_plain, expires_at = _parse_token_response(token_data)
|
||||
|
||||
user_data = await _forgejo_get(app_settings, "/api/v1/user", access_token)
|
||||
user_data = await forgejo.get(app_settings, "/api/v1/user", access_token)
|
||||
provider_user_id, provider_username, email = _parse_user_response(user_data)
|
||||
|
||||
# Find or create the user in the database
|
||||
user = await find_or_create_user(
|
||||
db,
|
||||
app_settings,
|
||||
|
|
@ -216,7 +229,10 @@ async def callback_forgejo(
|
|||
redirect = RedirectResponse("/dashboard", status_code=status.HTTP_302_FOUND)
|
||||
redirect.delete_cookie("oauth_state")
|
||||
|
||||
# Create a new session for the user
|
||||
await create_session(db, redirect, user.id, secure=request.url.scheme == "https")
|
||||
|
||||
# Redirect to the dashboard
|
||||
return redirect
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -5,14 +5,14 @@ from typing import Annotated
|
|||
|
||||
from fastapi import APIRouter, Depends, Form, HTTPException, Request, status
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from starlette.responses import Response
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from starlette.responses import Response
|
||||
|
||||
from app.auth.crypto import encrypt_optional
|
||||
from app.auth.session import get_current_session
|
||||
from app.config import get_fernet
|
||||
from app.deps import get_db
|
||||
from app.models.session import Session as UserBrowserSession
|
||||
from app.settings import get_fernet
|
||||
from app.templating import templates
|
||||
|
||||
router = APIRouter(prefix="/settings", tags=["settings"])
|
||||
|
|
|
|||
|
|
@ -4,16 +4,17 @@ from typing import Annotated
|
|||
|
||||
from fastapi import APIRouter, Cookie, Depends, Form, HTTPException, Request, status
|
||||
from fastapi.responses import RedirectResponse
|
||||
from starlette.responses import Response
|
||||
from sqlalchemy import func as sql_func, select
|
||||
from sqlalchemy import func as sql_func
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from starlette.responses import Response
|
||||
|
||||
from app.auth.crypto import encrypt_token
|
||||
from app.auth.session import lookup_session
|
||||
from app.config import get_fernet
|
||||
from app.deps import get_db
|
||||
from app.models.app_settings import AppSettings
|
||||
from app.models.user import User
|
||||
from app.settings import get_fernet
|
||||
from app.templating import templates
|
||||
|
||||
router = APIRouter(prefix="/setup", tags=["setup"])
|
||||
|
|
@ -46,7 +47,9 @@ async def _require_auth_if_configured(
|
|||
|
||||
|
||||
@router.get("", dependencies=[Depends(_require_auth_if_configured)])
|
||||
async def setup_page(request: Request, db: Annotated[AsyncSession, Depends(get_db)]) -> Response:
|
||||
async def setup_page(
|
||||
request: Request, db: Annotated[AsyncSession, Depends(get_db)]
|
||||
) -> Response:
|
||||
"""Render the setup wizard. Pre-fills fields when reconfiguring."""
|
||||
existing = request.app.state.app_settings
|
||||
user_count = await db.scalar(select(sql_func.count()).select_from(User)) or 0
|
||||
|
|
@ -58,7 +61,9 @@ async def setup_page(request: Request, db: Annotated[AsyncSession, Depends(get_d
|
|||
"reconfiguring": existing is not None and has_users,
|
||||
"forgejo_base_url": existing.forgejo_base_url if existing else "",
|
||||
"forgejo_oauth_client_id": existing.forgejo_oauth_client_id if existing else "",
|
||||
"firebreak_public_base_url": existing.firebreak_public_base_url if existing else "",
|
||||
"firebreak_public_base_url": existing.firebreak_public_base_url
|
||||
if existing
|
||||
else "",
|
||||
"oauth_callback_url": f"{public_base}/auth/callback/forgejo",
|
||||
}
|
||||
return templates.TemplateResponse(request, "setup.html", ctx)
|
||||
|
|
|
|||
|
|
@ -39,7 +39,10 @@ def get_settings() -> Settings:
|
|||
|
||||
@lru_cache
|
||||
def get_fernet() -> Fernet:
|
||||
"""Return a cached Fernet cipher from the TOKEN_ENCRYPTION_KEY env var."""
|
||||
"""
|
||||
Get a Fernet cipher from the TOKEN_ENCRYPTION_KEY env var.
|
||||
Return a cached Fernet cipher from the TOKEN_ENCRYPTION_KEY env var.
|
||||
"""
|
||||
key = get_settings().token_encryption_key
|
||||
if not key:
|
||||
raise ValueError(
|
||||
Loading…
Add table
Reference in a new issue