fastapi-panel 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fastapi_panel/__init__.py +77 -0
- fastapi_panel/__main__.py +97 -0
- fastapi_panel/auth.py +189 -0
- fastapi_panel/db.py +41 -0
- fastapi_panel/filters.py +215 -0
- fastapi_panel/forms.py +733 -0
- fastapi_panel/imports.py +264 -0
- fastapi_panel/introspect.py +111 -0
- fastapi_panel/log.py +52 -0
- fastapi_panel/options.py +717 -0
- fastapi_panel/py.typed +0 -0
- fastapi_panel/security.py +139 -0
- fastapi_panel/site.py +602 -0
- fastapi_panel/static/panel.css +420 -0
- fastapi_panel/static/panel.js +404 -0
- fastapi_panel/static/theme.js +5 -0
- fastapi_panel/storage.py +38 -0
- fastapi_panel/templates/fastapi_panel/base.html +76 -0
- fastapi_panel/templates/fastapi_panel/delete.html +25 -0
- fastapi_panel/templates/fastapi_panel/error.html +10 -0
- fastapi_panel/templates/fastapi_panel/form.html +113 -0
- fastapi_panel/templates/fastapi_panel/history.html +23 -0
- fastapi_panel/templates/fastapi_panel/import.html +76 -0
- fastapi_panel/templates/fastapi_panel/index.html +43 -0
- fastapi_panel/templates/fastapi_panel/list.html +131 -0
- fastapi_panel/templates/fastapi_panel/login.html +15 -0
- fastapi_panel/templates/fastapi_panel/password.html +17 -0
- fastapi_panel/templates/fastapi_panel/popup_done.html +4 -0
- fastapi_panel/templates/fastapi_panel/widgets.html +74 -0
- fastapi_panel/views.py +710 -0
- fastapi_panel-0.1.0.dist-info/METADATA +151 -0
- fastapi_panel-0.1.0.dist-info/RECORD +34 -0
- fastapi_panel-0.1.0.dist-info/WHEEL +4 -0
- fastapi_panel-0.1.0.dist-info/licenses/LICENSE +21 -0
fastapi_panel/site.py
ADDED
|
@@ -0,0 +1,602 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import datetime as dt
|
|
4
|
+
import hmac
|
|
5
|
+
import importlib
|
|
6
|
+
import inspect as inspect_module
|
|
7
|
+
import mimetypes
|
|
8
|
+
import pkgutil
|
|
9
|
+
import re
|
|
10
|
+
import secrets
|
|
11
|
+
import time
|
|
12
|
+
from collections.abc import Callable, Iterable, Iterator
|
|
13
|
+
from pathlib import Path, PurePosixPath
|
|
14
|
+
from typing import Any
|
|
15
|
+
from urllib.parse import urlsplit
|
|
16
|
+
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
|
17
|
+
|
|
18
|
+
from fastapi import FastAPI
|
|
19
|
+
from jinja2 import ChoiceLoader, Environment, FileSystemLoader, PackageLoader, select_autoescape
|
|
20
|
+
from sqlalchemy import inspect, select
|
|
21
|
+
from sqlalchemy.exc import DBAPIError
|
|
22
|
+
from starlette.applications import Starlette
|
|
23
|
+
from starlette.concurrency import run_in_threadpool
|
|
24
|
+
from starlette.exceptions import HTTPException
|
|
25
|
+
from starlette.middleware import Middleware
|
|
26
|
+
from starlette.requests import Request
|
|
27
|
+
from starlette.responses import HTMLResponse, RedirectResponse, Response, StreamingResponse
|
|
28
|
+
from starlette.routing import Mount, Route
|
|
29
|
+
from starlette.staticfiles import StaticFiles
|
|
30
|
+
|
|
31
|
+
from . import __version__, imports, views
|
|
32
|
+
from .db import Database
|
|
33
|
+
from .log import AdminLog
|
|
34
|
+
from .options import ImproperlyConfigured, ModelAdmin
|
|
35
|
+
from .security import SECURITY_HEADERS, BodyTooLarge, LimitBody, LoginThrottle, Signer
|
|
36
|
+
from .storage import Storage
|
|
37
|
+
|
|
38
|
+
COOKIE_NAME = "fastapi_panel_session"
|
|
39
|
+
RESERVED_SLUGS = {"login", "logout", "password", "static", "files"}
|
|
40
|
+
INLINE_FILE_TYPES = {"png", "jpg", "jpeg", "gif", "webp"}
|
|
41
|
+
FILE_CSP = "default-src 'none'; sandbox"
|
|
42
|
+
MIN_SECRET_LENGTH = 32
|
|
43
|
+
MIN_PASSWORD_LENGTH = 8
|
|
44
|
+
MAX_PASSWORD_LENGTH = 4096
|
|
45
|
+
MAX_FORM_FIELDS = 20_000
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class AdminSite:
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
*,
|
|
52
|
+
title: str = "Admin",
|
|
53
|
+
header: str | None = None,
|
|
54
|
+
index_title: str = "Dashboard",
|
|
55
|
+
template_dirs: Iterable[str | Path] = (),
|
|
56
|
+
extra_css: Iterable[str] = (),
|
|
57
|
+
audit_log: bool = True,
|
|
58
|
+
timezone: str = "UTC",
|
|
59
|
+
naive_utc: bool = True,
|
|
60
|
+
storage: Storage | None = None,
|
|
61
|
+
) -> None:
|
|
62
|
+
self.title = title
|
|
63
|
+
self.header = header or title
|
|
64
|
+
self.index_title = index_title
|
|
65
|
+
self.extra_css = list(extra_css)
|
|
66
|
+
self.audit_log = audit_log
|
|
67
|
+
self.timezone = timezone
|
|
68
|
+
self.naive_utc = naive_utc
|
|
69
|
+
self.storage = storage
|
|
70
|
+
self._registry: dict[str, ModelAdmin] = {}
|
|
71
|
+
self._pages: list[dict[str, Any]] = []
|
|
72
|
+
self._log_table_ready = not audit_log
|
|
73
|
+
self.templates = Environment(
|
|
74
|
+
loader=ChoiceLoader(
|
|
75
|
+
[FileSystemLoader([str(d) for d in template_dirs]), PackageLoader("fastapi_panel", "templates")]
|
|
76
|
+
),
|
|
77
|
+
autoescape=select_autoescape(default=True, default_for_string=True),
|
|
78
|
+
)
|
|
79
|
+
self.templates.filters["log_time"] = self._log_time
|
|
80
|
+
|
|
81
|
+
# Times. The database keeps its values, people see and type them in this timezone.
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def timezone(self) -> str:
|
|
85
|
+
return self._timezone
|
|
86
|
+
|
|
87
|
+
@timezone.setter
|
|
88
|
+
def timezone(self, name: str) -> None:
|
|
89
|
+
try:
|
|
90
|
+
self._zone = ZoneInfo(name)
|
|
91
|
+
except (ZoneInfoNotFoundError, ValueError):
|
|
92
|
+
raise ImproperlyConfigured(f"Unknown timezone {name!r}. Use a name like 'Europe/Paris'.") from None
|
|
93
|
+
self._timezone = name
|
|
94
|
+
|
|
95
|
+
def to_local(self, value: dt.datetime) -> dt.datetime:
|
|
96
|
+
if value.tzinfo is None:
|
|
97
|
+
if not self.naive_utc:
|
|
98
|
+
return value
|
|
99
|
+
value = value.replace(tzinfo=dt.timezone.utc)
|
|
100
|
+
return value.astimezone(self._zone)
|
|
101
|
+
|
|
102
|
+
def from_local(self, value: dt.datetime, aware: bool) -> dt.datetime:
|
|
103
|
+
"""What to store for a time typed in the panel. `value` is naive, `aware` is the column's kind."""
|
|
104
|
+
if not aware and not self.naive_utc:
|
|
105
|
+
return value
|
|
106
|
+
stored = value.replace(tzinfo=self._zone).astimezone(dt.timezone.utc)
|
|
107
|
+
return stored if aware else stored.replace(tzinfo=None)
|
|
108
|
+
|
|
109
|
+
def now(self) -> dt.datetime:
|
|
110
|
+
return dt.datetime.now(self._zone)
|
|
111
|
+
|
|
112
|
+
def _log_time(self, value: dt.datetime, spec: str = "%Y-%m-%d %H:%M") -> str:
|
|
113
|
+
# The audit log always stores naive UTC, whatever naive_utc says about your own columns.
|
|
114
|
+
return value.replace(tzinfo=dt.timezone.utc).astimezone(self._zone).strftime(spec)
|
|
115
|
+
|
|
116
|
+
# Registration
|
|
117
|
+
|
|
118
|
+
def register(self, model: type, admin_class: type[ModelAdmin] = ModelAdmin) -> ModelAdmin:
|
|
119
|
+
admin = admin_class(model, self)
|
|
120
|
+
if admin.slug in self._registry or admin.slug in RESERVED_SLUGS:
|
|
121
|
+
raise ImproperlyConfigured(f"The URL name {admin.slug!r} is taken. Set `slug` on {admin_class.__name__}.")
|
|
122
|
+
self._registry[admin.slug] = admin
|
|
123
|
+
return admin
|
|
124
|
+
|
|
125
|
+
def unregister(self, model: type) -> None:
|
|
126
|
+
self._registry = {slug: a for slug, a in self._registry.items() if a.model is not model}
|
|
127
|
+
|
|
128
|
+
def page(
|
|
129
|
+
self,
|
|
130
|
+
path: str,
|
|
131
|
+
*,
|
|
132
|
+
title: str,
|
|
133
|
+
group: str = "Pages",
|
|
134
|
+
methods: Iterable[str] = ("GET",),
|
|
135
|
+
permission: str | None = None,
|
|
136
|
+
) -> Callable[[Callable], Callable]:
|
|
137
|
+
"""Add a custom page. The view is called as `fn(session, request)` and returns a Response."""
|
|
138
|
+
|
|
139
|
+
def decorate(fn: Callable) -> Callable:
|
|
140
|
+
self._pages.append(
|
|
141
|
+
{
|
|
142
|
+
"path": path,
|
|
143
|
+
"title": title,
|
|
144
|
+
"group": group,
|
|
145
|
+
"methods": list(methods),
|
|
146
|
+
"permission": permission,
|
|
147
|
+
"view": fn,
|
|
148
|
+
}
|
|
149
|
+
)
|
|
150
|
+
return fn
|
|
151
|
+
|
|
152
|
+
return decorate
|
|
153
|
+
|
|
154
|
+
def admin_for_model(self, model: type) -> ModelAdmin | None:
|
|
155
|
+
return next((admin for admin in self._registry.values() if admin.model is model), None)
|
|
156
|
+
|
|
157
|
+
def queryset_for(self, model: type, request: Request) -> Any:
|
|
158
|
+
admin = self.admin_for_model(model)
|
|
159
|
+
stmt = admin.get_queryset(request) if admin else select(model)
|
|
160
|
+
keys = inspect(model).primary_key
|
|
161
|
+
return stmt.order_by(*keys)
|
|
162
|
+
|
|
163
|
+
def _admin(self, request: Request) -> ModelAdmin:
|
|
164
|
+
admin = self._registry.get(request.path_params["slug"])
|
|
165
|
+
if admin is None:
|
|
166
|
+
raise HTTPException(404, "Not found.")
|
|
167
|
+
return admin
|
|
168
|
+
|
|
169
|
+
# Mounting
|
|
170
|
+
|
|
171
|
+
def mount(
|
|
172
|
+
self,
|
|
173
|
+
app: FastAPI | Starlette,
|
|
174
|
+
*,
|
|
175
|
+
engine: Any,
|
|
176
|
+
auth: Any,
|
|
177
|
+
secret_key: str,
|
|
178
|
+
path: str = "/admin",
|
|
179
|
+
session_age: int = 12 * 3600,
|
|
180
|
+
secure_cookies: bool | None = None,
|
|
181
|
+
trusted_origins: Iterable[str] = (),
|
|
182
|
+
max_body_size: int = 10 * 1024 * 1024,
|
|
183
|
+
) -> None:
|
|
184
|
+
if len(secret_key) < MIN_SECRET_LENGTH:
|
|
185
|
+
raise ValueError(
|
|
186
|
+
f"secret_key must be at least {MIN_SECRET_LENGTH} characters. "
|
|
187
|
+
'Generate one: python -c "import secrets; print(secrets.token_urlsafe(48))"'
|
|
188
|
+
)
|
|
189
|
+
self.db = Database(engine)
|
|
190
|
+
self.auth = auth
|
|
191
|
+
self.signer = Signer(secret_key)
|
|
192
|
+
self.file_signer = Signer(secret_key, salt="files")
|
|
193
|
+
self.session_age = session_age
|
|
194
|
+
self.secure_cookies = secure_cookies
|
|
195
|
+
self.trusted_origins = set(trusted_origins)
|
|
196
|
+
self.max_body_size = max_body_size
|
|
197
|
+
self.throttle = LoginThrottle()
|
|
198
|
+
for admin in self._registry.values():
|
|
199
|
+
admin.check()
|
|
200
|
+
panel = Starlette(
|
|
201
|
+
routes=self._routes(),
|
|
202
|
+
exception_handlers={404: self._not_found},
|
|
203
|
+
middleware=[Middleware(LimitBody, limit=max_body_size)],
|
|
204
|
+
)
|
|
205
|
+
app.mount(path, panel)
|
|
206
|
+
|
|
207
|
+
def _routes(self) -> list[Any]:
|
|
208
|
+
routes: list[Any] = [
|
|
209
|
+
self._route("/", self._index),
|
|
210
|
+
self._route("/login", self._login, methods=["GET", "POST"], public=True),
|
|
211
|
+
self._route("/logout", self._logout, methods=["POST"]),
|
|
212
|
+
self._route("/password", self._change_password, methods=["GET", "POST"]),
|
|
213
|
+
self._route("/files/{token}", self._serve_file),
|
|
214
|
+
Mount("/static", StaticFiles(directory=Path(__file__).parent / "static"), name="static"),
|
|
215
|
+
]
|
|
216
|
+
for page in self._pages:
|
|
217
|
+
routes.append(self._route(page["path"], self._page_view(page), methods=page["methods"]))
|
|
218
|
+
for slug, admin in self._registry.items():
|
|
219
|
+
for path, view, methods in admin.get_routes():
|
|
220
|
+
routes.append(self._route(f"/{slug}{path}", view, methods=methods))
|
|
221
|
+
routes += [
|
|
222
|
+
self._route("/{slug}", self._model_view(views.changelist), methods=["GET", "POST"]),
|
|
223
|
+
self._route("/{slug}/add", self._model_view(views.change_form), methods=["GET", "POST"]),
|
|
224
|
+
self._route("/{slug}/autocomplete", self._model_view(views.autocomplete)),
|
|
225
|
+
self._route("/{slug}/deleted", self._model_view(views.trash), methods=["GET", "POST"]),
|
|
226
|
+
self._route("/{slug}/import", self._model_view(imports.import_view), methods=["GET", "POST"]),
|
|
227
|
+
self._route("/{slug}/{pk}/change", self._object_view(views.change_form), methods=["GET", "POST"]),
|
|
228
|
+
self._route("/{slug}/{pk}/delete", self._object_view(views.delete_view), methods=["GET", "POST"]),
|
|
229
|
+
self._route("/{slug}/{pk}/history", self._object_view(views.history_view)),
|
|
230
|
+
]
|
|
231
|
+
return routes
|
|
232
|
+
|
|
233
|
+
def _route(self, path: str, view: Callable, *, methods: Iterable[str] = ("GET",), public: bool = False) -> Route:
|
|
234
|
+
async def endpoint(request: Request) -> Response:
|
|
235
|
+
return await self._handle(request, view, public)
|
|
236
|
+
|
|
237
|
+
return Route(path, endpoint, methods=list(methods))
|
|
238
|
+
|
|
239
|
+
def _model_view(self, view: Callable) -> Callable:
|
|
240
|
+
return lambda session, request: view(session, request, self._admin(request))
|
|
241
|
+
|
|
242
|
+
def _object_view(self, view: Callable) -> Callable:
|
|
243
|
+
return lambda session, request: view(session, request, self._admin(request), request.path_params["pk"])
|
|
244
|
+
|
|
245
|
+
def _page_view(self, page: dict[str, Any]) -> Callable:
|
|
246
|
+
def view(session: Any, request: Request) -> Response:
|
|
247
|
+
if page["permission"] and not self.auth.has_perm(request.state.user, page["permission"]):
|
|
248
|
+
raise HTTPException(403, "You don't have permission to do that.")
|
|
249
|
+
return page["view"](session, request)
|
|
250
|
+
|
|
251
|
+
return view
|
|
252
|
+
|
|
253
|
+
# The one path every request takes: session, CSRF, auth, the view, then headers and the cookie.
|
|
254
|
+
|
|
255
|
+
async def _handle(self, request: Request, view: Callable, public: bool) -> Response:
|
|
256
|
+
session_data = self._read_session(request)
|
|
257
|
+
request.state.session = session_data
|
|
258
|
+
before = dict(session_data)
|
|
259
|
+
request.state.user = None
|
|
260
|
+
request.state.form = None
|
|
261
|
+
request.state.trash = False
|
|
262
|
+
request.state.relation_options = {}
|
|
263
|
+
try:
|
|
264
|
+
if request.method == "POST":
|
|
265
|
+
await self._guard_post(request)
|
|
266
|
+
await self._ensure_log_table()
|
|
267
|
+
await self._load_user(request)
|
|
268
|
+
if request.state.user is None and not public:
|
|
269
|
+
response: Response = self._redirect_to_login(request)
|
|
270
|
+
elif inspect_module.iscoroutinefunction(view):
|
|
271
|
+
response = await view(request)
|
|
272
|
+
else:
|
|
273
|
+
response = await self.db.run(view, request)
|
|
274
|
+
except HTTPException as exc:
|
|
275
|
+
response = self._error_page(request, exc.status_code, exc.detail)
|
|
276
|
+
finally:
|
|
277
|
+
await request.close()
|
|
278
|
+
if _is_popup(request) and request.url.path.endswith("/add"):
|
|
279
|
+
# Only the add form opens in the panel's own dialog. Everything else still refuses to be framed.
|
|
280
|
+
policy = SECURITY_HEADERS["Content-Security-Policy"]
|
|
281
|
+
response.headers["Content-Security-Policy"] = policy.replace(
|
|
282
|
+
"frame-ancestors 'none'", "frame-ancestors 'self'"
|
|
283
|
+
)
|
|
284
|
+
response.headers["X-Frame-Options"] = "SAMEORIGIN"
|
|
285
|
+
for name, value in SECURITY_HEADERS.items():
|
|
286
|
+
response.headers.setdefault(name, value)
|
|
287
|
+
if request.state.session != before or not request.cookies.get(COOKIE_NAME):
|
|
288
|
+
self._write_session(request, response)
|
|
289
|
+
return response
|
|
290
|
+
|
|
291
|
+
def _read_session(self, request: Request) -> dict[str, Any]:
|
|
292
|
+
raw = request.cookies.get(COOKIE_NAME)
|
|
293
|
+
data = self.signer.loads(raw) if raw else None
|
|
294
|
+
if not isinstance(data, dict):
|
|
295
|
+
data = {}
|
|
296
|
+
if data.get("uid") and data.get("exp", 0) < time.time():
|
|
297
|
+
data = {}
|
|
298
|
+
data.setdefault("csrf", secrets.token_urlsafe(32))
|
|
299
|
+
return data
|
|
300
|
+
|
|
301
|
+
def _write_session(self, request: Request, response: Response) -> None:
|
|
302
|
+
secure = self.secure_cookies if self.secure_cookies is not None else request.url.scheme == "https"
|
|
303
|
+
response.set_cookie(
|
|
304
|
+
COOKIE_NAME,
|
|
305
|
+
self.signer.dumps(request.state.session),
|
|
306
|
+
max_age=self.session_age,
|
|
307
|
+
path=request.scope["root_path"] or "/",
|
|
308
|
+
httponly=True,
|
|
309
|
+
samesite="lax",
|
|
310
|
+
secure=secure,
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
async def _guard_post(self, request: Request) -> None:
|
|
314
|
+
length = request.headers.get("content-length", "0")
|
|
315
|
+
if length.isdigit() and int(length) > self.max_body_size:
|
|
316
|
+
raise HTTPException(413, "That request is too large.")
|
|
317
|
+
|
|
318
|
+
origin = request.headers.get("origin")
|
|
319
|
+
if origin and origin != "null":
|
|
320
|
+
parts = urlsplit(origin)
|
|
321
|
+
if parts.netloc != request.url.netloc and origin not in self.trusted_origins:
|
|
322
|
+
raise HTTPException(403, "This request came from another site and was blocked.")
|
|
323
|
+
elif origin == "null" or request.headers.get("sec-fetch-site") == "cross-site":
|
|
324
|
+
raise HTTPException(403, "This request came from another site and was blocked.")
|
|
325
|
+
|
|
326
|
+
try:
|
|
327
|
+
form = await request.form(max_fields=MAX_FORM_FIELDS, max_part_size=self.max_body_size)
|
|
328
|
+
except BodyTooLarge:
|
|
329
|
+
raise HTTPException(413, "That request is too large.") from None
|
|
330
|
+
request.state.form = form
|
|
331
|
+
token = form.get("csrf_token", "")
|
|
332
|
+
if not isinstance(token, str) or not hmac.compare_digest(token, request.state.session["csrf"]):
|
|
333
|
+
raise HTTPException(403, "Your session expired or this form is stale. Reload the page and try again.")
|
|
334
|
+
|
|
335
|
+
async def _load_user(self, request: Request) -> None:
|
|
336
|
+
session_data = request.state.session
|
|
337
|
+
uid = session_data.get("uid")
|
|
338
|
+
if not uid:
|
|
339
|
+
return
|
|
340
|
+
user = await self.db.run(self.auth.get_user, uid)
|
|
341
|
+
expected = session_data.get("hash", "")
|
|
342
|
+
if (
|
|
343
|
+
user is None
|
|
344
|
+
or not self.auth.is_allowed(user)
|
|
345
|
+
or not hmac.compare_digest(self.auth.session_hash(user), expected)
|
|
346
|
+
):
|
|
347
|
+
for key in ("uid", "hash", "exp"):
|
|
348
|
+
session_data.pop(key, None)
|
|
349
|
+
return
|
|
350
|
+
request.state.user = user
|
|
351
|
+
|
|
352
|
+
async def _ensure_log_table(self) -> None:
|
|
353
|
+
if self._log_table_ready:
|
|
354
|
+
return
|
|
355
|
+
|
|
356
|
+
def create(session: Any) -> None:
|
|
357
|
+
AdminLog.__table__.create(session.connection(), checkfirst=True)
|
|
358
|
+
session.commit()
|
|
359
|
+
|
|
360
|
+
try:
|
|
361
|
+
await self.db.run(create)
|
|
362
|
+
except DBAPIError:
|
|
363
|
+
pass # Another worker won the race, or the table is managed by migrations.
|
|
364
|
+
self._log_table_ready = True
|
|
365
|
+
|
|
366
|
+
def _redirect_to_login(self, request: Request) -> Response:
|
|
367
|
+
root = request.scope["root_path"]
|
|
368
|
+
target = request.url.path if request.method == "GET" else f"{root}/"
|
|
369
|
+
return RedirectResponse(f"{root}/login?next={views.quote(target, safe='')}", status_code=303)
|
|
370
|
+
|
|
371
|
+
def _error_page(self, request: Request, status: int, detail: str) -> Response:
|
|
372
|
+
response = self.render(
|
|
373
|
+
request, "fastapi_panel/error.html", {"title": f"Error {status}", "status": status, "detail": detail}
|
|
374
|
+
)
|
|
375
|
+
response.status_code = status
|
|
376
|
+
return response
|
|
377
|
+
|
|
378
|
+
async def _not_found(self, request: Request, exc: Exception) -> Response:
|
|
379
|
+
return await self._handle(request, _raise_not_found, public=True)
|
|
380
|
+
|
|
381
|
+
# Rendering
|
|
382
|
+
|
|
383
|
+
def render(
|
|
384
|
+
self, request: Request, template: str, context: dict[str, Any] | None = None, status_code: int = 200
|
|
385
|
+
) -> HTMLResponse:
|
|
386
|
+
session_data = request.state.session
|
|
387
|
+
messages = session_data.pop("messages", [])
|
|
388
|
+
user = request.state.user
|
|
389
|
+
root = request.scope["root_path"]
|
|
390
|
+
html = self.templates.get_template(template).render(
|
|
391
|
+
{
|
|
392
|
+
"request": request,
|
|
393
|
+
"site": self,
|
|
394
|
+
"root": root,
|
|
395
|
+
"static": f"{root}/static",
|
|
396
|
+
"version": __version__,
|
|
397
|
+
"csrf_token": session_data["csrf"],
|
|
398
|
+
"messages": messages,
|
|
399
|
+
"user": user,
|
|
400
|
+
"popup": _is_popup(request),
|
|
401
|
+
"user_label": self.auth.user_label(user) if user is not None else "",
|
|
402
|
+
"can_change_password": self.auth.can_change_password,
|
|
403
|
+
"nav": self._navigation(request) if user is not None else [],
|
|
404
|
+
**(context or {}),
|
|
405
|
+
}
|
|
406
|
+
)
|
|
407
|
+
return HTMLResponse(html, status_code=status_code)
|
|
408
|
+
|
|
409
|
+
def _navigation(self, request: Request) -> list[dict[str, Any]]:
|
|
410
|
+
groups: dict[str, list[dict[str, Any]]] = {}
|
|
411
|
+
current = request.url.path
|
|
412
|
+
root = request.scope["root_path"]
|
|
413
|
+
for admin in self._registry.values():
|
|
414
|
+
if admin.has_module_permission(request):
|
|
415
|
+
url = f"{root}/{admin.slug}"
|
|
416
|
+
can_add = admin.has_add_permission(request)
|
|
417
|
+
groups.setdefault(admin.group_name, []).append(
|
|
418
|
+
{
|
|
419
|
+
"label": admin.name_plural,
|
|
420
|
+
"url": url,
|
|
421
|
+
"add_url": f"{url}/add" if can_add else None,
|
|
422
|
+
"active": current == url or current.startswith(f"{url}/"),
|
|
423
|
+
}
|
|
424
|
+
)
|
|
425
|
+
for page in self._pages:
|
|
426
|
+
if not page["permission"] or self.auth.has_perm(request.state.user, page["permission"]):
|
|
427
|
+
url = f"{root}{page['path']}"
|
|
428
|
+
groups.setdefault(page["group"], []).append(
|
|
429
|
+
{"label": page["title"], "url": url, "add_url": None, "active": current == url}
|
|
430
|
+
)
|
|
431
|
+
return [
|
|
432
|
+
{"name": name, "items": sorted(items, key=lambda item: item["label"])}
|
|
433
|
+
for name, items in sorted(groups.items())
|
|
434
|
+
]
|
|
435
|
+
|
|
436
|
+
def message(self, request: Request, text: str, level: str = "success") -> None:
|
|
437
|
+
# Kept short: these travel in the cookie until the next page renders.
|
|
438
|
+
queue = request.state.session.setdefault("messages", [])
|
|
439
|
+
queue.append({"text": text[:300], "level": level})
|
|
440
|
+
del queue[:-5]
|
|
441
|
+
|
|
442
|
+
# Built-in pages
|
|
443
|
+
|
|
444
|
+
def _index(self, session: Any, request: Request) -> Response:
|
|
445
|
+
recent = []
|
|
446
|
+
if self.audit_log:
|
|
447
|
+
stmt = (
|
|
448
|
+
select(AdminLog)
|
|
449
|
+
.where(AdminLog.user_id == self.auth.user_id(request.state.user))
|
|
450
|
+
.order_by(AdminLog.created_at.desc(), AdminLog.id.desc())
|
|
451
|
+
.limit(10)
|
|
452
|
+
)
|
|
453
|
+
recent = list(session.scalars(stmt))
|
|
454
|
+
return self.render(
|
|
455
|
+
request,
|
|
456
|
+
"fastapi_panel/index.html",
|
|
457
|
+
{"title": self.index_title, "recent": recent, "registry": self._registry},
|
|
458
|
+
)
|
|
459
|
+
|
|
460
|
+
async def _login(self, request: Request) -> Response:
|
|
461
|
+
root = request.scope["root_path"]
|
|
462
|
+
raw_next = request.query_params.get("next", "")
|
|
463
|
+
target = raw_next if _is_safe_next(raw_next, root) else f"{root}/"
|
|
464
|
+
if request.state.user is not None:
|
|
465
|
+
return RedirectResponse(target, status_code=303)
|
|
466
|
+
error = ""
|
|
467
|
+
username = ""
|
|
468
|
+
status = 200
|
|
469
|
+
if request.method == "POST":
|
|
470
|
+
form = request.state.form
|
|
471
|
+
username = str(form.get("username", ""))[:255]
|
|
472
|
+
password = str(form.get("password", ""))[:MAX_PASSWORD_LENGTH]
|
|
473
|
+
client = request.client.host if request.client else "unknown"
|
|
474
|
+
key = f"{client}|{username.lower()}"
|
|
475
|
+
if self.throttle.blocked(key):
|
|
476
|
+
error = "Too many failed attempts. Try again in a few minutes."
|
|
477
|
+
status = 429
|
|
478
|
+
else:
|
|
479
|
+
user = await self.db.run(self.auth.find_user, username)
|
|
480
|
+
valid = await run_in_threadpool(self.auth.check_password, user, password)
|
|
481
|
+
if valid and user is not None and self.auth.is_allowed(user):
|
|
482
|
+
self.throttle.reset(key)
|
|
483
|
+
# A new session, including a new CSRF token, so nothing set before login carries over.
|
|
484
|
+
request.state.session = {
|
|
485
|
+
"csrf": secrets.token_urlsafe(32),
|
|
486
|
+
"uid": self.auth.user_id(user),
|
|
487
|
+
"hash": self.auth.session_hash(user),
|
|
488
|
+
"exp": time.time() + self.session_age,
|
|
489
|
+
}
|
|
490
|
+
return RedirectResponse(target, status_code=303)
|
|
491
|
+
self.throttle.fail(key)
|
|
492
|
+
error = "Please enter a correct username and password."
|
|
493
|
+
status = 400
|
|
494
|
+
return self.render(
|
|
495
|
+
request,
|
|
496
|
+
"fastapi_panel/login.html",
|
|
497
|
+
{"title": "Log in", "error": error, "username": username, "next": raw_next if target == raw_next else ""},
|
|
498
|
+
status_code=status,
|
|
499
|
+
)
|
|
500
|
+
|
|
501
|
+
def file_url(self, request: Request, name: str) -> str:
|
|
502
|
+
# Links are minted for someone who may see the record, and only work with a logged-in session.
|
|
503
|
+
token = self.file_signer.dumps({"name": name, "exp": time.time() + self.session_age})
|
|
504
|
+
return f"{request.scope['root_path']}/files/{token}"
|
|
505
|
+
|
|
506
|
+
def _serve_file(self, session: Any, request: Request) -> Response:
|
|
507
|
+
payload = self.file_signer.loads(request.path_params["token"])
|
|
508
|
+
if not isinstance(payload, dict) or payload.get("exp", 0) < time.time() or not self.storage:
|
|
509
|
+
raise HTTPException(404, "This file doesn't exist.")
|
|
510
|
+
name = str(payload.get("name", ""))
|
|
511
|
+
try:
|
|
512
|
+
stream = self.storage.open(name)
|
|
513
|
+
except (FileNotFoundError, IsADirectoryError, ValueError):
|
|
514
|
+
raise HTTPException(404, "This file doesn't exist.") from None
|
|
515
|
+
|
|
516
|
+
def chunks() -> Iterator[bytes]:
|
|
517
|
+
with stream:
|
|
518
|
+
yield from iter(lambda: stream.read(64 * 1024), b"")
|
|
519
|
+
|
|
520
|
+
filename = re.sub(r"[^\w.-]", "_", PurePosixPath(name).name)
|
|
521
|
+
extension = PurePosixPath(name).suffix.lstrip(".").lower()
|
|
522
|
+
# Anything but a plain image downloads, so an uploaded page can't run on the panel's origin.
|
|
523
|
+
disposition = "inline" if extension in INLINE_FILE_TYPES else "attachment"
|
|
524
|
+
return StreamingResponse(
|
|
525
|
+
chunks(),
|
|
526
|
+
media_type=mimetypes.guess_type(filename)[0] or "application/octet-stream",
|
|
527
|
+
headers={
|
|
528
|
+
"Content-Disposition": f'{disposition}; filename="{filename}"',
|
|
529
|
+
"Content-Security-Policy": FILE_CSP,
|
|
530
|
+
},
|
|
531
|
+
)
|
|
532
|
+
|
|
533
|
+
def _logout(self, session: Any, request: Request) -> Response:
|
|
534
|
+
request.state.session = {"csrf": secrets.token_urlsafe(32)}
|
|
535
|
+
return RedirectResponse(f"{request.scope['root_path']}/login", status_code=303)
|
|
536
|
+
|
|
537
|
+
async def _change_password(self, request: Request) -> Response:
|
|
538
|
+
if not self.auth.can_change_password:
|
|
539
|
+
raise HTTPException(404, "Not found.")
|
|
540
|
+
errors: dict[str, str] = {}
|
|
541
|
+
if request.method == "POST":
|
|
542
|
+
form = request.state.form
|
|
543
|
+
current = str(form.get("current", ""))[:MAX_PASSWORD_LENGTH]
|
|
544
|
+
new = str(form.get("new", ""))[:MAX_PASSWORD_LENGTH]
|
|
545
|
+
if not await run_in_threadpool(self.auth.check_password, request.state.user, current):
|
|
546
|
+
errors["current"] = "That's not your current password."
|
|
547
|
+
if len(new) < MIN_PASSWORD_LENGTH:
|
|
548
|
+
errors["new"] = f"Use at least {MIN_PASSWORD_LENGTH} characters."
|
|
549
|
+
elif new != form.get("confirm", ""):
|
|
550
|
+
errors["confirm"] = "The two passwords don't match."
|
|
551
|
+
if not errors:
|
|
552
|
+
hashed_user = await self.db.run(self._store_password, request, new)
|
|
553
|
+
request.state.session["hash"] = self.auth.session_hash(hashed_user)
|
|
554
|
+
self.message(request, "Your password was changed.")
|
|
555
|
+
return RedirectResponse(f"{request.scope['root_path']}/", status_code=303)
|
|
556
|
+
return self.render(request, "fastapi_panel/password.html", {"title": "Change password", "errors": errors})
|
|
557
|
+
|
|
558
|
+
def _store_password(self, session: Any, request: Request, password: str) -> Any:
|
|
559
|
+
user = self.auth.get_user(session, self.auth.user_id(request.state.user))
|
|
560
|
+
self.auth.set_password(session, user, password)
|
|
561
|
+
session.commit()
|
|
562
|
+
return user
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def _is_popup(request: Request) -> bool:
|
|
566
|
+
return bool(request.query_params.get("_popup"))
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def _raise_not_found(session: Any, request: Request) -> Response:
|
|
570
|
+
raise HTTPException(404, "This page doesn't exist.")
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def _is_safe_next(target: str, root: str) -> bool:
|
|
574
|
+
if not target.startswith(f"{root}/") or target.startswith("//") or "\\" in target:
|
|
575
|
+
return False
|
|
576
|
+
parts = urlsplit(target)
|
|
577
|
+
return not parts.scheme and not parts.netloc
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def autodiscover(*packages: str, module: str = "admin") -> None:
|
|
581
|
+
"""Import every `admin` module under the given packages, so their registrations run."""
|
|
582
|
+
for name in packages:
|
|
583
|
+
package = importlib.import_module(name)
|
|
584
|
+
if not hasattr(package, "__path__"):
|
|
585
|
+
continue
|
|
586
|
+
for info in pkgutil.walk_packages(package.__path__, f"{name}."):
|
|
587
|
+
if info.name.rsplit(".", 1)[-1] == module:
|
|
588
|
+
importlib.import_module(info.name)
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
site = AdminSite()
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
def register(*models: type, site: AdminSite = site) -> Callable[[type[ModelAdmin]], type[ModelAdmin]]:
|
|
595
|
+
"""`@register(Product)` above a ModelAdmin."""
|
|
596
|
+
|
|
597
|
+
def decorate(admin_class: type[ModelAdmin]) -> type[ModelAdmin]:
|
|
598
|
+
for model in models:
|
|
599
|
+
site.register(model, admin_class)
|
|
600
|
+
return admin_class
|
|
601
|
+
|
|
602
|
+
return decorate
|