devadmin 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.
- devadmin/__init__.py +19 -0
- devadmin/__main__.py +5 -0
- devadmin/adapters/__init__.py +0 -0
- devadmin/adapters/base.py +175 -0
- devadmin/adapters/tortoise/__init__.py +81 -0
- devadmin/adapters/tortoise/introspect.py +209 -0
- devadmin/adapters/tortoise/models.py +34 -0
- devadmin/adapters/tortoise/queries.py +330 -0
- devadmin/adapters/tortoise/related.py +215 -0
- devadmin/adapters/tortoise/store.py +156 -0
- devadmin/auth/__init__.py +16 -0
- devadmin/auth/csrf.py +18 -0
- devadmin/auth/ip.py +28 -0
- devadmin/auth/login.py +149 -0
- devadmin/auth/session.py +94 -0
- devadmin/cli.py +314 -0
- devadmin/config.py +34 -0
- devadmin/core/__init__.py +0 -0
- devadmin/core/binding.py +609 -0
- devadmin/core/forms.py +475 -0
- devadmin/core/listing.py +400 -0
- devadmin/core/options.py +99 -0
- devadmin/core/paths.py +39 -0
- devadmin/core/site.py +288 -0
- devadmin/core/values.py +122 -0
- devadmin/history/__init__.py +38 -0
- devadmin/history/diff.py +109 -0
- devadmin/history/encoding.py +120 -0
- devadmin/history/records.py +40 -0
- devadmin/history/render.py +129 -0
- devadmin/history/service.py +256 -0
- devadmin/web/__init__.py +0 -0
- devadmin/web/app.py +106 -0
- devadmin/web/deps.py +275 -0
- devadmin/web/guard.py +178 -0
- devadmin/web/static/autocomplete.js +231 -0
- devadmin/web/static/devadmin.css +1645 -0
- devadmin/web/static/devadmin.js +129 -0
- devadmin/web/static/htmx.min.js +1 -0
- devadmin/web/static/icons/check.svg +1 -0
- devadmin/web/static/icons/clock.svg +1 -0
- devadmin/web/static/icons/cross.svg +1 -0
- devadmin/web/static/icons/down.svg +1 -0
- devadmin/web/static/icons/eye.svg +1 -0
- devadmin/web/static/icons/lock.svg +1 -0
- devadmin/web/static/icons/pencil.svg +1 -0
- devadmin/web/static/icons/plus.svg +1 -0
- devadmin/web/static/icons/right.svg +1 -0
- devadmin/web/static/icons/trash.svg +1 -0
- devadmin/web/static/icons/up.svg +1 -0
- devadmin/web/templates/_field.html +35 -0
- devadmin/web/templates/_history.html +19 -0
- devadmin/web/templates/_pagination.html +8 -0
- devadmin/web/templates/action_confirm.html +26 -0
- devadmin/web/templates/base.html +63 -0
- devadmin/web/templates/delete.html +62 -0
- devadmin/web/templates/error.html +9 -0
- devadmin/web/templates/form.html +34 -0
- devadmin/web/templates/history.html +59 -0
- devadmin/web/templates/index.html +49 -0
- devadmin/web/templates/list.html +88 -0
- devadmin/web/templates/login.html +15 -0
- devadmin/web/templates/recent.html +25 -0
- devadmin/web/views_auth.py +146 -0
- devadmin/web/views_delete.py +774 -0
- devadmin/web/views_form.py +551 -0
- devadmin/web/views_history.py +261 -0
- devadmin/web/views_list.py +246 -0
- devadmin-0.1.0.dist-info/METADATA +702 -0
- devadmin-0.1.0.dist-info/RECORD +73 -0
- devadmin-0.1.0.dist-info/WHEEL +4 -0
- devadmin-0.1.0.dist-info/entry_points.txt +3 -0
- devadmin-0.1.0.dist-info/licenses/LICENSE +21 -0
devadmin/web/deps.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import logging
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from http import HTTPStatus
|
|
5
|
+
from typing import Any
|
|
6
|
+
from urllib.parse import quote, urlencode
|
|
7
|
+
|
|
8
|
+
from itsdangerous import BadData, URLSafeTimedSerializer
|
|
9
|
+
from jinja2 import Environment, PackageLoader, StrictUndefined, pass_context
|
|
10
|
+
from starlette.datastructures import FormData
|
|
11
|
+
from starlette.exceptions import HTTPException
|
|
12
|
+
from starlette.requests import Request
|
|
13
|
+
from starlette.responses import HTMLResponse, RedirectResponse, Response
|
|
14
|
+
|
|
15
|
+
from devadmin.adapters.base import FieldType
|
|
16
|
+
from devadmin.auth import SESSION_COOKIE, Session, load_actor
|
|
17
|
+
from devadmin.config import AdminConfig
|
|
18
|
+
from devadmin.core.listing import scoped_rows
|
|
19
|
+
from devadmin.core.site import BoundAdmin, Site
|
|
20
|
+
from devadmin.core.values import parse_scalar
|
|
21
|
+
from devadmin.history.service import History
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger("devadmin")
|
|
24
|
+
|
|
25
|
+
SERVER_ERROR = "Something went wrong. The error has been logged."
|
|
26
|
+
FLASH_COOKIE = "devadmin_flash"
|
|
27
|
+
FLASH_SECONDS = 120
|
|
28
|
+
FLASH_LIMIT = 500
|
|
29
|
+
REPR_LIMIT = 100
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
SEARCH_HINT_FIELDS = 3
|
|
33
|
+
NAV_FLATTEN_FROM = 4
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def short_repr(text: str) -> str:
|
|
37
|
+
return text if len(text) <= REPR_LIMIT else text[: REPR_LIMIT - 1] + "…"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def search_hint(admin: BoundAdmin) -> str:
|
|
41
|
+
labels: list[str] = []
|
|
42
|
+
for entry in admin.search_entries:
|
|
43
|
+
hops = [hop.replace("_", " ") for hop in entry.path.split("__")[:-1]]
|
|
44
|
+
label = " ".join([*hops, entry.field.label]).lower()
|
|
45
|
+
if label not in labels:
|
|
46
|
+
labels.append(label)
|
|
47
|
+
hint = ", ".join(labels[:SEARCH_HINT_FIELDS])
|
|
48
|
+
return hint + ", …" if len(labels) > SEARCH_HINT_FIELDS else hint
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class Ctx:
|
|
53
|
+
config: AdminConfig
|
|
54
|
+
site: Site
|
|
55
|
+
adapter: Any
|
|
56
|
+
history: History
|
|
57
|
+
actor: Any | None
|
|
58
|
+
session: Session | None
|
|
59
|
+
form: FormData = field(default_factory=FormData)
|
|
60
|
+
sidebar: list[tuple[str, list[BoundAdmin]]] | None = None
|
|
61
|
+
|
|
62
|
+
def groups(self, request: Request) -> list[tuple[str, list[BoundAdmin]]]:
|
|
63
|
+
if self.sidebar is None:
|
|
64
|
+
self.sidebar = self.site.groups(request)
|
|
65
|
+
return self.sidebar
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def nav_groups(groups: list[tuple[str, list[BoundAdmin]]]) -> list[tuple[str, list[BoundAdmin]]]:
|
|
69
|
+
singles = sum(1 for _, admins in groups if len(admins) == 1)
|
|
70
|
+
if len(groups) < NAV_FLATTEN_FROM or singles * 2 <= len(groups):
|
|
71
|
+
return groups
|
|
72
|
+
merged = [admin for _, admins in groups for admin in admins]
|
|
73
|
+
return [("", sorted(merged, key=lambda admin: admin.label_plural.lower()))]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class LoginRequired(Exception):
|
|
77
|
+
def __init__(self, response: Response) -> None:
|
|
78
|
+
super().__init__("login required")
|
|
79
|
+
self.response = response
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def panel_of(request: Request) -> Any:
|
|
83
|
+
return request.app.state.devadmin
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def ctx_of(request: Request) -> Ctx | None:
|
|
87
|
+
return getattr(request.state, "devadmin", None)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def mount_path(request: Request) -> str:
|
|
91
|
+
return quote(request.scope.get("root_path", ""), safe="/").rstrip("/")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
_DOT_SEGMENTS = {".": "%2E", "..": "%2E%2E"}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _segment(part: Any) -> str:
|
|
98
|
+
quoted = quote(str(part), safe="")
|
|
99
|
+
return _DOT_SEGMENTS.get(quoted, quoted)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def url(request: Request, /, *parts: Any, **query: Any) -> str:
|
|
103
|
+
path = mount_path(request) + "/" + "/".join(_segment(part) for part in parts)
|
|
104
|
+
pairs = [(name, str(value)) for name, value in query.items() if value is not None]
|
|
105
|
+
return path + ("?" + urlencode(pairs) if pairs else "")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def requested_path(request: Request) -> str:
|
|
109
|
+
raw = request.scope.get("raw_path")
|
|
110
|
+
path = raw.decode("latin-1") if raw else quote(request.scope["path"])
|
|
111
|
+
query = request.scope.get("query_string", b"").decode("latin-1")
|
|
112
|
+
return path + ("?" + query if query else "")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def client_address(request: Request) -> str | None:
|
|
116
|
+
config = panel_of(request).config
|
|
117
|
+
if config.client_ip is not None:
|
|
118
|
+
try:
|
|
119
|
+
address = config.client_ip(request)
|
|
120
|
+
except Exception:
|
|
121
|
+
logger.exception("client_ip raised")
|
|
122
|
+
return None
|
|
123
|
+
return address if isinstance(address, str) else None
|
|
124
|
+
return request.client.host if request.client is not None else None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def cookie_path(request: Request) -> str:
|
|
128
|
+
return mount_path(request) or "/"
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def set_cookie(response: Response, request: Request, name: str, value: str, max_age: int) -> None:
|
|
132
|
+
response.set_cookie(
|
|
133
|
+
name,
|
|
134
|
+
value,
|
|
135
|
+
max_age=max_age,
|
|
136
|
+
path=cookie_path(request),
|
|
137
|
+
secure=panel_of(request).config.secure_cookies,
|
|
138
|
+
httponly=True,
|
|
139
|
+
samesite="strict",
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def delete_cookie(response: Response, request: Request, name: str) -> None:
|
|
144
|
+
response.delete_cookie(
|
|
145
|
+
name,
|
|
146
|
+
path=cookie_path(request),
|
|
147
|
+
secure=panel_of(request).config.secure_cookies,
|
|
148
|
+
httponly=True,
|
|
149
|
+
samesite="strict",
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
async def current_session(request: Request) -> tuple[Session | None, Any | None]:
|
|
154
|
+
panel = panel_of(request)
|
|
155
|
+
session = panel.signer.loads(request.cookies.get(SESSION_COOKIE, ""))
|
|
156
|
+
if session is None:
|
|
157
|
+
return None, None
|
|
158
|
+
actor = await load_actor(panel.config, session)
|
|
159
|
+
if actor is None:
|
|
160
|
+
return None, None
|
|
161
|
+
return session, actor
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
async def require_actor(request: Request) -> Any:
|
|
165
|
+
session, actor = await current_session(request)
|
|
166
|
+
if actor is None:
|
|
167
|
+
if request.method in ("GET", "HEAD"):
|
|
168
|
+
response = RedirectResponse(url(request, "login", next=requested_path(request)), status_code=303)
|
|
169
|
+
else:
|
|
170
|
+
response = error_page(request, 403, "You are not signed in.")
|
|
171
|
+
if SESSION_COOKIE in request.cookies:
|
|
172
|
+
delete_cookie(response, request, SESSION_COOKIE)
|
|
173
|
+
raise LoginRequired(response)
|
|
174
|
+
ctx = ctx_of(request)
|
|
175
|
+
ctx.actor, ctx.session = actor, session
|
|
176
|
+
return actor
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def get_admin(request: Request, key: str) -> BoundAdmin:
|
|
180
|
+
try:
|
|
181
|
+
admin = ctx_of(request).site.get(key)
|
|
182
|
+
except KeyError:
|
|
183
|
+
raise HTTPException(404) from None
|
|
184
|
+
if not admin.options.has_view_permission(request):
|
|
185
|
+
raise HTTPException(404)
|
|
186
|
+
return admin
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def parse_key(request: Request, admin: BoundAdmin, raw_pk: str) -> Any:
|
|
190
|
+
pk = ctx_of(request).adapter.parse_pk(admin.info.model, raw_pk)
|
|
191
|
+
if isinstance(pk, str) and admin.pk.type in (FieldType.STR, FieldType.TEXT):
|
|
192
|
+
parse_scalar(admin.pk, pk)
|
|
193
|
+
return pk
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
async def scoped_object(request: Request, admin: BoundAdmin, pk: Any) -> Any:
|
|
197
|
+
rows = await scoped_rows(admin, ctx_of(request).adapter, [pk], request)
|
|
198
|
+
if not rows:
|
|
199
|
+
raise HTTPException(404)
|
|
200
|
+
return rows[0]
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
async def get_object(request: Request, admin: BoundAdmin, raw_pk: str) -> Any:
|
|
204
|
+
try:
|
|
205
|
+
pk = parse_key(request, admin, raw_pk)
|
|
206
|
+
except ValueError:
|
|
207
|
+
raise HTTPException(404) from None
|
|
208
|
+
return await scoped_object(request, admin, pk)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _flash_serializer(request: Request) -> URLSafeTimedSerializer:
|
|
212
|
+
return URLSafeTimedSerializer(
|
|
213
|
+
panel_of(request).config.secret_key,
|
|
214
|
+
salt="devadmin.flash",
|
|
215
|
+
signer_kwargs={"digest_method": hashlib.sha256},
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def set_flash(response: Response, request: Request, message: str) -> None:
|
|
220
|
+
set_cookie(response, request, FLASH_COOKIE, _flash_serializer(request).dumps(message[:FLASH_LIMIT]), FLASH_SECONDS)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _read_flash(request: Request) -> str:
|
|
224
|
+
value = request.cookies.get(FLASH_COOKIE)
|
|
225
|
+
if not value:
|
|
226
|
+
return ""
|
|
227
|
+
try:
|
|
228
|
+
message = _flash_serializer(request).loads(value, max_age=FLASH_SECONDS)
|
|
229
|
+
except (BadData, UnicodeError):
|
|
230
|
+
return ""
|
|
231
|
+
return message[:FLASH_LIMIT] if isinstance(message, str) else ""
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
@pass_context
|
|
235
|
+
def _url_global(context: Any, *parts: Any, **query: Any) -> str:
|
|
236
|
+
return url(context["request"], *parts, **query)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def make_templates() -> Environment:
|
|
240
|
+
environment = Environment(
|
|
241
|
+
loader=PackageLoader("devadmin.web", "templates"), autoescape=True, undefined=StrictUndefined
|
|
242
|
+
)
|
|
243
|
+
environment.globals["url"] = _url_global
|
|
244
|
+
return environment
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _page(request: Request, template: str, status_code: int, ctx: Ctx | None, context: dict) -> HTMLResponse:
|
|
248
|
+
panel = panel_of(request)
|
|
249
|
+
actor = ctx.actor if ctx is not None else None
|
|
250
|
+
signed_in = actor is not None and ctx.session is not None
|
|
251
|
+
values = {
|
|
252
|
+
"request": request,
|
|
253
|
+
"config": panel.config,
|
|
254
|
+
"signed_in": signed_in,
|
|
255
|
+
"actor_repr": panel.config.adapter.repr_of(actor) if signed_in else "",
|
|
256
|
+
"csrf": ctx.session.csrf if signed_in else "",
|
|
257
|
+
"groups": nav_groups(ctx.groups(request)) if signed_in else [],
|
|
258
|
+
"current_key": context.get("key", ""),
|
|
259
|
+
"flash": _read_flash(request) if signed_in else "",
|
|
260
|
+
**context,
|
|
261
|
+
}
|
|
262
|
+
response = HTMLResponse(panel.templates.get_template(template).render(values), status_code=status_code)
|
|
263
|
+
if signed_in and FLASH_COOKIE in request.cookies:
|
|
264
|
+
delete_cookie(response, request, FLASH_COOKIE)
|
|
265
|
+
return response
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def render(request: Request, template: str, status_code: int = 200, **context: Any) -> HTMLResponse:
|
|
269
|
+
return _page(request, template, status_code, ctx_of(request), context)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def error_page(request: Request, status_code: int, message: str, bare: bool = False) -> HTMLResponse:
|
|
273
|
+
title = HTTPStatus(status_code).phrase
|
|
274
|
+
ctx = None if bare else ctx_of(request)
|
|
275
|
+
return _page(request, "error.html", status_code, ctx, {"title": title, "message": message})
|
devadmin/web/guard.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from starlette.exceptions import HTTPException
|
|
5
|
+
from starlette.requests import ClientDisconnect, Request
|
|
6
|
+
from starlette.responses import PlainTextResponse
|
|
7
|
+
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
|
8
|
+
|
|
9
|
+
from devadmin.auth import check_csrf, ip_allowed
|
|
10
|
+
from devadmin.web.deps import SERVER_ERROR, Ctx, LoginRequired, client_address, error_page, require_actor
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger("devadmin")
|
|
13
|
+
|
|
14
|
+
SECURITY_HEADERS = [
|
|
15
|
+
(b"cache-control", b"no-store"),
|
|
16
|
+
(b"x-frame-options", b"DENY"),
|
|
17
|
+
(b"x-content-type-options", b"nosniff"),
|
|
18
|
+
(b"referrer-policy", b"same-origin"),
|
|
19
|
+
(
|
|
20
|
+
b"content-security-policy",
|
|
21
|
+
b"default-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'none'",
|
|
22
|
+
),
|
|
23
|
+
]
|
|
24
|
+
_SECURITY_NAMES = frozenset(name for name, _ in SECURITY_HEADERS)
|
|
25
|
+
_SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
|
|
26
|
+
_PUBLIC_PATHS = frozenset({"/login"})
|
|
27
|
+
_STATIC_PREFIX = "/static/"
|
|
28
|
+
_PUBLIC_FORM_TYPE = "application/x-www-form-urlencoded"
|
|
29
|
+
WEBSOCKET_POLICY_VIOLATION = 1008
|
|
30
|
+
MAX_BODY_BYTES = 10 * 1024 * 1024
|
|
31
|
+
MAX_PUBLIC_BODY_BYTES = 64 * 1024
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def route_path(scope: Scope) -> str:
|
|
35
|
+
path = scope["path"]
|
|
36
|
+
root = scope.get("root_path", "")
|
|
37
|
+
if root and path.startswith(root):
|
|
38
|
+
return path[len(root):] or "/"
|
|
39
|
+
return path
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _plain_static_path(path: str) -> bool:
|
|
43
|
+
return all(segment not in ("", ".", "..") for segment in path[len(_STATIC_PREFIX):].split("/"))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _replay(body: bytes, receive: Receive) -> Receive:
|
|
47
|
+
sent = False
|
|
48
|
+
|
|
49
|
+
async def replayed() -> Message:
|
|
50
|
+
nonlocal sent
|
|
51
|
+
if sent:
|
|
52
|
+
return await receive()
|
|
53
|
+
sent = True
|
|
54
|
+
return {"type": "http.request", "body": body, "more_body": False}
|
|
55
|
+
|
|
56
|
+
return replayed
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class _TooLarge(Exception):
|
|
60
|
+
pass
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
async def _read_body(request: Request, limit: int) -> bytes:
|
|
64
|
+
chunks = []
|
|
65
|
+
size = 0
|
|
66
|
+
async for chunk in request.stream():
|
|
67
|
+
size += len(chunk)
|
|
68
|
+
if size > limit:
|
|
69
|
+
raise _TooLarge
|
|
70
|
+
chunks.append(chunk)
|
|
71
|
+
return b"".join(chunks)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _text(value: Any) -> str | None:
|
|
75
|
+
return value if isinstance(value, str) else None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _media_type(request: Request) -> str:
|
|
79
|
+
return request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class Guard:
|
|
83
|
+
def __init__(self, app: ASGIApp, panel: Any) -> None:
|
|
84
|
+
self.app = app
|
|
85
|
+
self.panel = panel
|
|
86
|
+
|
|
87
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
88
|
+
if scope["type"] == "lifespan":
|
|
89
|
+
await self.app(scope, receive, send)
|
|
90
|
+
return
|
|
91
|
+
if scope["type"] == "websocket":
|
|
92
|
+
await send({"type": "websocket.close", "code": WEBSOCKET_POLICY_VIOLATION, "reason": ""})
|
|
93
|
+
return
|
|
94
|
+
if scope["type"] != "http":
|
|
95
|
+
return
|
|
96
|
+
started = False
|
|
97
|
+
|
|
98
|
+
async def secured(message: Message) -> None:
|
|
99
|
+
nonlocal started
|
|
100
|
+
if message["type"] == "http.response.start":
|
|
101
|
+
started = True
|
|
102
|
+
headers = [
|
|
103
|
+
(name, value)
|
|
104
|
+
for name, value in message.get("headers", [])
|
|
105
|
+
if name.lower() not in _SECURITY_NAMES
|
|
106
|
+
]
|
|
107
|
+
message = {**message, "headers": [*headers, *SECURITY_HEADERS]}
|
|
108
|
+
await send(message)
|
|
109
|
+
|
|
110
|
+
try:
|
|
111
|
+
await self._guard(scope, receive, secured)
|
|
112
|
+
except ClientDisconnect:
|
|
113
|
+
return
|
|
114
|
+
except Exception:
|
|
115
|
+
if started:
|
|
116
|
+
raise
|
|
117
|
+
logger.exception("devadmin request failed")
|
|
118
|
+
await self._server_error(scope)(scope, receive, secured)
|
|
119
|
+
|
|
120
|
+
def _server_error(self, scope: Scope) -> Any:
|
|
121
|
+
try:
|
|
122
|
+
return error_page(Request(scope), 500, SERVER_ERROR, bare=True)
|
|
123
|
+
except Exception:
|
|
124
|
+
logger.exception("devadmin error page failed")
|
|
125
|
+
return PlainTextResponse(SERVER_ERROR, status_code=500)
|
|
126
|
+
|
|
127
|
+
async def _guard(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
128
|
+
panel = self.panel
|
|
129
|
+
config = panel.config
|
|
130
|
+
request = Request(scope, receive)
|
|
131
|
+
if config.allowed_ips and not ip_allowed(config.allowed_ips, client_address(request)):
|
|
132
|
+
await error_page(request, 403, "Access from your address is not allowed.", bare=True)(scope, receive, send)
|
|
133
|
+
return
|
|
134
|
+
path = route_path(scope)
|
|
135
|
+
if path.startswith(_STATIC_PREFIX):
|
|
136
|
+
if not _plain_static_path(path):
|
|
137
|
+
await error_page(request, 404, "This page does not exist.", bare=True)(scope, receive, send)
|
|
138
|
+
return
|
|
139
|
+
await self.app(scope, receive, send)
|
|
140
|
+
return
|
|
141
|
+
await panel.ready()
|
|
142
|
+
ctx = Ctx(config, panel.site, config.adapter, panel.history, None, None)
|
|
143
|
+
scope.setdefault("state", {})["devadmin"] = ctx
|
|
144
|
+
public = path in _PUBLIC_PATHS
|
|
145
|
+
if not public:
|
|
146
|
+
try:
|
|
147
|
+
await require_actor(request)
|
|
148
|
+
except LoginRequired as refused:
|
|
149
|
+
await refused.response(scope, receive, send)
|
|
150
|
+
return
|
|
151
|
+
if scope["method"] in _SAFE_METHODS:
|
|
152
|
+
await self.app(scope, receive, send)
|
|
153
|
+
return
|
|
154
|
+
if public and _media_type(request) != _PUBLIC_FORM_TYPE:
|
|
155
|
+
await error_page(request, 415, "Send the form as application/x-www-form-urlencoded.")(
|
|
156
|
+
scope, receive, send
|
|
157
|
+
)
|
|
158
|
+
return
|
|
159
|
+
try:
|
|
160
|
+
body = await _read_body(request, MAX_PUBLIC_BODY_BYTES if public else MAX_BODY_BYTES)
|
|
161
|
+
ctx.form = await Request(scope, _replay(body, receive)).form()
|
|
162
|
+
except _TooLarge:
|
|
163
|
+
await error_page(request, 413, "The request is too large.")(scope, receive, send)
|
|
164
|
+
return
|
|
165
|
+
except HTTPException as exc:
|
|
166
|
+
await error_page(request, exc.status_code, "The form could not be read.")(scope, receive, send)
|
|
167
|
+
return
|
|
168
|
+
try:
|
|
169
|
+
if not public and not check_csrf(
|
|
170
|
+
ctx.session, _text(ctx.form.get("_csrf")), request.headers.get("x-csrf-token")
|
|
171
|
+
):
|
|
172
|
+
await error_page(request, 403, "The form has expired. Reload the page and try again.")(
|
|
173
|
+
scope, receive, send
|
|
174
|
+
)
|
|
175
|
+
return
|
|
176
|
+
await self.app(scope, _replay(body, receive), send)
|
|
177
|
+
finally:
|
|
178
|
+
await ctx.form.close()
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
(function () {
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
var DELAY = 200;
|
|
5
|
+
var counter = 0;
|
|
6
|
+
|
|
7
|
+
function enhance(wrapper) {
|
|
8
|
+
if (wrapper.getAttribute("data-enhanced") === "true") {
|
|
9
|
+
return;
|
|
10
|
+
}
|
|
11
|
+
wrapper.setAttribute("data-enhanced", "true");
|
|
12
|
+
counter += 1;
|
|
13
|
+
var visible = wrapper.querySelector("input[type=text]");
|
|
14
|
+
var current = wrapper.querySelector(".fk-current");
|
|
15
|
+
var hidden = document.createElement("input");
|
|
16
|
+
hidden.type = "hidden";
|
|
17
|
+
hidden.name = visible.name;
|
|
18
|
+
hidden.value = visible.value;
|
|
19
|
+
visible.removeAttribute("name");
|
|
20
|
+
wrapper.appendChild(hidden);
|
|
21
|
+
if (current) {
|
|
22
|
+
current.hidden = true;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
var chosenText = wrapper.getAttribute("data-repr") || hidden.value;
|
|
26
|
+
visible.value = chosenText;
|
|
27
|
+
|
|
28
|
+
var listId = "autocomplete-list-" + counter;
|
|
29
|
+
var list = document.createElement("ul");
|
|
30
|
+
list.id = listId;
|
|
31
|
+
list.className = "autocomplete-results";
|
|
32
|
+
list.setAttribute("role", "listbox");
|
|
33
|
+
list.hidden = true;
|
|
34
|
+
wrapper.appendChild(list);
|
|
35
|
+
|
|
36
|
+
visible.setAttribute("role", "combobox");
|
|
37
|
+
visible.setAttribute("aria-autocomplete", "list");
|
|
38
|
+
visible.setAttribute("aria-expanded", "false");
|
|
39
|
+
visible.setAttribute("aria-controls", listId);
|
|
40
|
+
|
|
41
|
+
if (wrapper.hasAttribute("data-nullable")) {
|
|
42
|
+
var clear = document.createElement("button");
|
|
43
|
+
clear.type = "button";
|
|
44
|
+
clear.className = "link-button autocomplete-clear";
|
|
45
|
+
clear.textContent = "Clear";
|
|
46
|
+
clear.addEventListener("click", function () {
|
|
47
|
+
choose("", "");
|
|
48
|
+
visible.focus();
|
|
49
|
+
});
|
|
50
|
+
wrapper.appendChild(clear);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
var results = [];
|
|
54
|
+
var active = -1;
|
|
55
|
+
var timer = null;
|
|
56
|
+
var sent = 0;
|
|
57
|
+
var shown = 0;
|
|
58
|
+
|
|
59
|
+
function close() {
|
|
60
|
+
list.hidden = true;
|
|
61
|
+
list.textContent = "";
|
|
62
|
+
results = [];
|
|
63
|
+
active = -1;
|
|
64
|
+
visible.setAttribute("aria-expanded", "false");
|
|
65
|
+
visible.removeAttribute("aria-activedescendant");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function clearError() {
|
|
69
|
+
var describedBy = visible.getAttribute("aria-describedby");
|
|
70
|
+
if (describedBy) {
|
|
71
|
+
var message = document.getElementById(describedBy);
|
|
72
|
+
if (message && message.classList.contains("field-error")) {
|
|
73
|
+
message.remove();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
visible.removeAttribute("aria-describedby");
|
|
77
|
+
visible.removeAttribute("aria-invalid");
|
|
78
|
+
var field = wrapper.closest(".field");
|
|
79
|
+
if (field) {
|
|
80
|
+
field.classList.remove("has-error");
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function choose(id, text) {
|
|
85
|
+
hidden.value = id;
|
|
86
|
+
chosenText = text;
|
|
87
|
+
visible.value = text;
|
|
88
|
+
if (id !== "") {
|
|
89
|
+
clearError();
|
|
90
|
+
}
|
|
91
|
+
close();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function highlight(index) {
|
|
95
|
+
var options = list.querySelectorAll("[role=option]");
|
|
96
|
+
options.forEach(function (option, position) {
|
|
97
|
+
option.setAttribute("aria-selected", position === index ? "true" : "false");
|
|
98
|
+
});
|
|
99
|
+
active = index;
|
|
100
|
+
if (index >= 0 && options[index]) {
|
|
101
|
+
visible.setAttribute("aria-activedescendant", options[index].id);
|
|
102
|
+
options[index].scrollIntoView({ block: "nearest" });
|
|
103
|
+
} else {
|
|
104
|
+
visible.removeAttribute("aria-activedescendant");
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function show(items) {
|
|
109
|
+
list.textContent = "";
|
|
110
|
+
results = items;
|
|
111
|
+
active = -1;
|
|
112
|
+
if (!items.length) {
|
|
113
|
+
var empty = document.createElement("li");
|
|
114
|
+
empty.className = "autocomplete-empty";
|
|
115
|
+
var searches = wrapper.getAttribute("data-searches");
|
|
116
|
+
empty.textContent = searches ? "No matches (searches by " + searches + ")" : "No matches";
|
|
117
|
+
list.appendChild(empty);
|
|
118
|
+
}
|
|
119
|
+
items.forEach(function (item, index) {
|
|
120
|
+
var option = document.createElement("li");
|
|
121
|
+
option.id = listId + "-" + index;
|
|
122
|
+
option.setAttribute("role", "option");
|
|
123
|
+
option.setAttribute("aria-selected", "false");
|
|
124
|
+
option.textContent = item.text;
|
|
125
|
+
var key = document.createElement("span");
|
|
126
|
+
key.className = "autocomplete-key";
|
|
127
|
+
key.textContent = item.id;
|
|
128
|
+
option.appendChild(key);
|
|
129
|
+
option.addEventListener("mousedown", function (event) {
|
|
130
|
+
event.preventDefault();
|
|
131
|
+
choose(item.id, item.text);
|
|
132
|
+
});
|
|
133
|
+
list.appendChild(option);
|
|
134
|
+
});
|
|
135
|
+
list.hidden = false;
|
|
136
|
+
visible.setAttribute("aria-expanded", "true");
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function search() {
|
|
140
|
+
sent += 1;
|
|
141
|
+
var ticket = sent;
|
|
142
|
+
var address = new URL(wrapper.getAttribute("data-url"), window.location.href);
|
|
143
|
+
address.searchParams.set("q", visible.value.trim());
|
|
144
|
+
fetch(address.toString(), {
|
|
145
|
+
credentials: "same-origin",
|
|
146
|
+
headers: { Accept: "application/json" },
|
|
147
|
+
})
|
|
148
|
+
.then(function (response) {
|
|
149
|
+
return response.ok ? response.json() : { results: [] };
|
|
150
|
+
})
|
|
151
|
+
.then(function (body) {
|
|
152
|
+
if (ticket < shown || document.activeElement !== visible) {
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
shown = ticket;
|
|
156
|
+
show(Array.isArray(body.results) ? body.results : []);
|
|
157
|
+
})
|
|
158
|
+
.catch(function () {
|
|
159
|
+
if (ticket >= shown) {
|
|
160
|
+
close();
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function schedule() {
|
|
166
|
+
window.clearTimeout(timer);
|
|
167
|
+
timer = window.setTimeout(search, DELAY);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
visible.addEventListener("input", schedule);
|
|
171
|
+
visible.addEventListener("focus", function () {
|
|
172
|
+
if (visible.value === chosenText) {
|
|
173
|
+
visible.select();
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
visible.addEventListener("blur", function () {
|
|
177
|
+
window.clearTimeout(timer);
|
|
178
|
+
sent += 1;
|
|
179
|
+
shown = sent;
|
|
180
|
+
close();
|
|
181
|
+
visible.value = chosenText;
|
|
182
|
+
});
|
|
183
|
+
visible.addEventListener("keydown", function (event) {
|
|
184
|
+
if (event.key === "ArrowDown") {
|
|
185
|
+
event.preventDefault();
|
|
186
|
+
if (list.hidden) {
|
|
187
|
+
search();
|
|
188
|
+
} else if (results.length) {
|
|
189
|
+
highlight(Math.min(active + 1, results.length - 1));
|
|
190
|
+
}
|
|
191
|
+
} else if (event.key === "ArrowUp") {
|
|
192
|
+
event.preventDefault();
|
|
193
|
+
if (results.length) {
|
|
194
|
+
highlight(Math.max(active - 1, 0));
|
|
195
|
+
}
|
|
196
|
+
} else if (event.key === "Enter") {
|
|
197
|
+
if (!list.hidden) {
|
|
198
|
+
event.preventDefault();
|
|
199
|
+
if (active >= 0 && results[active]) {
|
|
200
|
+
choose(results[active].id, results[active].text);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
} else if (event.key === "Escape") {
|
|
204
|
+
if (!list.hidden) {
|
|
205
|
+
event.preventDefault();
|
|
206
|
+
close();
|
|
207
|
+
visible.value = chosenText;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function enhanceAll(root) {
|
|
214
|
+
var scope = root && root.querySelectorAll ? root : document;
|
|
215
|
+
if (scope.matches && scope.matches("[data-autocomplete]")) {
|
|
216
|
+
enhance(scope);
|
|
217
|
+
}
|
|
218
|
+
scope.querySelectorAll("[data-autocomplete]").forEach(enhance);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
if (document.readyState === "loading") {
|
|
222
|
+
document.addEventListener("DOMContentLoaded", function () {
|
|
223
|
+
enhanceAll(document);
|
|
224
|
+
});
|
|
225
|
+
} else {
|
|
226
|
+
enhanceAll(document);
|
|
227
|
+
}
|
|
228
|
+
document.addEventListener("htmx:load", function (event) {
|
|
229
|
+
enhanceAll(event.detail && event.detail.elt);
|
|
230
|
+
});
|
|
231
|
+
})();
|