fix(web): mypy fixes, Starlette exception handler, disable CTA without PAT
- Fix return type annotations to use Response for TemplateResponse returns - Fix db.scalar nullability with `or 0` for mypy - Catch StarletteHTTPException for 404/405 error page rendering - Disable "Create share link" button when PAT not registered - Formatter/linter cleanup Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
18897362df
commit
442261f403
9 changed files with 94 additions and 86 deletions
|
|
@ -62,7 +62,7 @@ uv run python -c 'from cryptography.fernet import Fernet; print(Fernet.generate_
|
||||||
|
|
||||||
Add the output to your `.env` file (or your deployment platform's environment variables):
|
Add the output to your `.env` file (or your deployment platform's environment variables):
|
||||||
|
|
||||||
```
|
```bash
|
||||||
TOKEN_ENCRYPTION_KEY=your-generated-key-here
|
TOKEN_ENCRYPTION_KEY=your-generated-key-here
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -103,7 +103,9 @@ async def get_optional_session(
|
||||||
return await lookup_session(db, firebreak_session)
|
return await lookup_session(db, firebreak_session)
|
||||||
|
|
||||||
|
|
||||||
async def revoke_session(db: AsyncSession, response: Response, firebreak_session: str | None) -> None:
|
async def revoke_session(
|
||||||
|
db: AsyncSession, response: Response, firebreak_session: str | None
|
||||||
|
) -> None:
|
||||||
"""Delete the browser cookie and mark the matching session as revoked."""
|
"""Delete the browser cookie and mark the matching session as revoked."""
|
||||||
|
|
||||||
response.delete_cookie(
|
response.delete_cookie(
|
||||||
|
|
|
||||||
|
|
@ -4,9 +4,11 @@ from contextlib import asynccontextmanager
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from fastapi import Depends, FastAPI, HTTPException, Request
|
from fastapi import Depends, FastAPI, Request
|
||||||
from fastapi.responses import HTMLResponse, JSONResponse
|
from fastapi.responses import HTMLResponse, JSONResponse
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||||
|
from starlette.responses import Response
|
||||||
from sqlalchemy import func as sql_func, select
|
from sqlalchemy import func as sql_func, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||||
|
|
||||||
|
|
@ -86,8 +88,10 @@ ERROR_TITLES = {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@app.exception_handler(HTTPException)
|
@app.exception_handler(StarletteHTTPException)
|
||||||
async def http_exception_handler(request: Request, exc: HTTPException) -> HTMLResponse | JSONResponse:
|
async def http_exception_handler(
|
||||||
|
request: Request, exc: StarletteHTTPException
|
||||||
|
) -> Response:
|
||||||
"""Render a styled error page for browser requests, JSON for API clients."""
|
"""Render a styled error page for browser requests, JSON for API clients."""
|
||||||
accept = request.headers.get("accept", "")
|
accept = request.headers.get("accept", "")
|
||||||
if "text/html" in accept:
|
if "text/html" in accept:
|
||||||
|
|
@ -107,7 +111,7 @@ async def http_exception_handler(request: Request, exc: HTTPException) -> HTMLRe
|
||||||
@app.get("/", response_class=HTMLResponse)
|
@app.get("/", response_class=HTMLResponse)
|
||||||
async def root(
|
async def root(
|
||||||
request: Request, sess: Annotated[UserBrowserSession | None, Depends(get_optional_session)]
|
request: Request, sess: Annotated[UserBrowserSession | None, Depends(get_optional_session)]
|
||||||
) -> HTMLResponse:
|
) -> Response:
|
||||||
return templates.TemplateResponse(
|
return templates.TemplateResponse(
|
||||||
request,
|
request,
|
||||||
"index.html",
|
"index.html",
|
||||||
|
|
@ -118,7 +122,7 @@ async def root(
|
||||||
@app.get("/dashboard", response_class=HTMLResponse)
|
@app.get("/dashboard", response_class=HTMLResponse)
|
||||||
async def dashboard(
|
async def dashboard(
|
||||||
request: Request, sess: Annotated[UserBrowserSession, Depends(get_current_session)]
|
request: Request, sess: Annotated[UserBrowserSession, Depends(get_current_session)]
|
||||||
) -> HTMLResponse:
|
) -> Response:
|
||||||
return templates.TemplateResponse(
|
return templates.TemplateResponse(
|
||||||
request,
|
request,
|
||||||
"dashboard.html",
|
"dashboard.html",
|
||||||
|
|
|
||||||
|
|
@ -8,11 +8,7 @@ class SetupRequiredMiddleware(BaseHTTPMiddleware):
|
||||||
|
|
||||||
async def dispatch(self, request: Request, call_next) -> Response:
|
async def dispatch(self, request: Request, call_next) -> Response:
|
||||||
path = request.url.path
|
path = request.url.path
|
||||||
if (
|
if path.startswith("/setup") or path.startswith("/static") or path == "/favicon.ico":
|
||||||
path.startswith("/setup")
|
|
||||||
or path.startswith("/static")
|
|
||||||
or path == "/favicon.ico"
|
|
||||||
):
|
|
||||||
return await call_next(request)
|
return await call_next(request)
|
||||||
|
|
||||||
if request.app.state.app_settings is None:
|
if request.app.state.app_settings is None:
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ from typing import Annotated
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, Form, HTTPException, Request, status
|
from fastapi import APIRouter, Depends, Form, HTTPException, Request, status
|
||||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||||
|
from starlette.responses import Response
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.auth.crypto import encrypt_optional
|
from app.auth.crypto import encrypt_optional
|
||||||
|
|
@ -21,7 +22,7 @@ router = APIRouter(prefix="/settings", tags=["settings"])
|
||||||
async def settings_page(
|
async def settings_page(
|
||||||
request: Request,
|
request: Request,
|
||||||
sess: Annotated[UserBrowserSession, Depends(get_current_session)],
|
sess: Annotated[UserBrowserSession, Depends(get_current_session)],
|
||||||
) -> HTMLResponse:
|
) -> Response:
|
||||||
return templates.TemplateResponse(
|
return templates.TemplateResponse(
|
||||||
request,
|
request,
|
||||||
"settings.html",
|
"settings.html",
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,8 @@ from __future__ import annotations
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from fastapi import APIRouter, Cookie, Depends, Form, HTTPException, Request, status
|
from fastapi import APIRouter, Cookie, Depends, Form, HTTPException, Request, status
|
||||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
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, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
|
@ -32,7 +33,7 @@ async def _require_auth_if_configured(
|
||||||
return
|
return
|
||||||
|
|
||||||
# If no users exist, allow access — the setup token still protects POST
|
# If no users exist, allow access — the setup token still protects POST
|
||||||
user_count = await db.scalar(select(sql_func.count()).select_from(User))
|
user_count = await db.scalar(select(sql_func.count()).select_from(User)) or 0
|
||||||
if user_count == 0:
|
if user_count == 0:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
@ -44,16 +45,17 @@ async def _require_auth_if_configured(
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.get("", dependencies=[Depends(_require_auth_if_configured)], response_class=HTMLResponse)
|
@router.get("", dependencies=[Depends(_require_auth_if_configured)])
|
||||||
async def setup_page(request: Request, db: Annotated[AsyncSession, Depends(get_db)]) -> HTMLResponse:
|
async def setup_page(
|
||||||
|
request: Request, db: Annotated[AsyncSession, Depends(get_db)]
|
||||||
|
) -> Response:
|
||||||
"""Render the setup wizard. Pre-fills fields when reconfiguring."""
|
"""Render the setup wizard. Pre-fills fields when reconfiguring."""
|
||||||
existing = request.app.state.app_settings
|
existing = request.app.state.app_settings
|
||||||
user_count = await db.scalar(select(sql_func.count()).select_from(User))
|
user_count = await db.scalar(select(sql_func.count()).select_from(User)) or 0
|
||||||
has_users = user_count > 0
|
has_users = user_count > 0
|
||||||
public_base = (
|
public_base = (existing.firebreak_public_base_url if existing else "") or str(
|
||||||
(existing.firebreak_public_base_url if existing else "")
|
request.base_url
|
||||||
or str(request.base_url).rstrip("/")
|
).rstrip("/")
|
||||||
)
|
|
||||||
ctx = {
|
ctx = {
|
||||||
"reconfiguring": existing is not None and has_users,
|
"reconfiguring": existing is not None and has_users,
|
||||||
"forgejo_base_url": existing.forgejo_base_url if existing else "",
|
"forgejo_base_url": existing.forgejo_base_url if existing else "",
|
||||||
|
|
@ -75,7 +77,7 @@ async def setup_submit(
|
||||||
setup_token: Annotated[str, Form()] = "",
|
setup_token: Annotated[str, Form()] = "",
|
||||||
) -> RedirectResponse:
|
) -> RedirectResponse:
|
||||||
"""Process the setup wizard — creates or updates Forgejo settings."""
|
"""Process the setup wizard — creates or updates Forgejo settings."""
|
||||||
user_count = await db.scalar(select(sql_func.count()).select_from(User))
|
user_count = await db.scalar(select(sql_func.count()).select_from(User)) or 0
|
||||||
has_users = user_count > 0
|
has_users = user_count > 0
|
||||||
is_reconfiguring = request.app.state.app_settings is not None and has_users
|
is_reconfiguring = request.app.state.app_settings is not None and has_users
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,18 @@
|
||||||
{% extends "base.html" %}
|
{% extends "base.html" %}
|
||||||
{% block title %}Dashboard — Firebreak{% endblock %}
|
{% block title %}Dashboard — Firebreak{% endblock %}
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<div class="flex flex-col gap-6">
|
<div class="flex flex-col gap-6">
|
||||||
<section class="flex flex-col justify-between gap-4 pb-6 border-b border-border sm:flex-row sm:items-end">
|
<section class="flex flex-col justify-between gap-4 pb-6 border-b border-border sm:flex-row sm:items-end">
|
||||||
<div>
|
<div>
|
||||||
<h1 class="mt-2 text-3xl font-semibold leading-10 tracking-normal">Welcome,</h1>
|
<h1 class="mt-2 text-3xl font-semibold leading-10 tracking-normal">Welcome,</h1>
|
||||||
<p class=" text-2xl text-muted-foreground">{{ user.display_name or user.email }}.</p>
|
<p class=" text-2xl text-muted-foreground">{{ user.display_name or user.email }}.</p>
|
||||||
</div>
|
</div>
|
||||||
|
{% if pat_registered %}
|
||||||
<a href="/links/create" class="btn btn-primary w-fit">Create share link</a>
|
<a href="/links/create" class="btn btn-primary w-fit">Create share link</a>
|
||||||
|
{% else %}
|
||||||
|
<span class="btn btn-primary w-fit opacity-50 pointer-events-none"
|
||||||
|
aria-disabled="true">Create share link</span>
|
||||||
|
{% endif %}
|
||||||
</section>
|
</section>
|
||||||
<section class="grid gap-4 md:grid-cols-3">
|
<section class="grid gap-4 md:grid-cols-3">
|
||||||
<div class="p-4 card">
|
<div class="p-4 card">
|
||||||
|
|
@ -61,5 +66,5 @@
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
@ -111,7 +111,7 @@
|
||||||
"He doesn't bite. He just harvests.",
|
"He doesn't bite. He just harvests.",
|
||||||
"Move along. Nothing to scrape here.",
|
"Move along. Nothing to scrape here.",
|
||||||
"Unauthorized. The Zuck abides.",
|
"Unauthorized. The Zuck abides.",
|
||||||
"ACCESS DENIED. Deploying Cuckerberg.",
|
"ACCESS DENIED. Deploying Cuckerberg."
|
||||||
] %}
|
] %}
|
||||||
<p class="mt-2 text-xs italic text-[#f7f2e8]/30">{{ quips | random }}</p>
|
<p class="mt-2 text-xs italic text-[#f7f2e8]/30">{{ quips | random }}</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
|
||||||
|
|
@ -64,9 +64,7 @@
|
||||||
class="block w-full rounded-md border border-[#f7f2e8]/14 bg-[#1f2226] px-3 py-2.5 font-mono text-sm text-[#f7f2e8] placeholder:text-[#f7f2e8]/30 focus:border-[#f7f2e8]/30 focus:outline-none focus:ring-2 focus:ring-[#f7f2e8]/10"
|
class="block w-full rounded-md border border-[#f7f2e8]/14 bg-[#1f2226] px-3 py-2.5 font-mono text-sm text-[#f7f2e8] placeholder:text-[#f7f2e8]/30 focus:border-[#f7f2e8]/30 focus:outline-none focus:ring-2 focus:ring-[#f7f2e8]/10"
|
||||||
placeholder="Paste the token from your server logs"
|
placeholder="Paste the token from your server logs"
|
||||||
required />
|
required />
|
||||||
<p class="mt-1.5 text-xs text-[#f7f2e8]/30">
|
<p class="mt-1.5 text-xs text-[#f7f2e8]/30">Printed to the server console on first boot.</p>
|
||||||
Printed to the server console on first boot.
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<div>
|
<div>
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue