confsync-server 0.2.0__tar.gz → 0.4.0__tar.gz
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.
- {confsync_server-0.2.0 → confsync_server-0.4.0}/PKG-INFO +1 -1
- {confsync_server-0.2.0 → confsync_server-0.4.0}/confsync_server/__init__.py +1 -1
- {confsync_server-0.2.0 → confsync_server-0.4.0}/confsync_server/app.py +286 -48
- confsync_server-0.4.0/confsync_server/auth.py +198 -0
- {confsync_server-0.2.0 → confsync_server-0.4.0}/confsync_server/cli.py +12 -7
- {confsync_server-0.2.0 → confsync_server-0.4.0}/confsync_server/crypto.py +5 -0
- confsync_server-0.4.0/confsync_server/db.py +555 -0
- confsync_server-0.4.0/tests/test_accounts.py +369 -0
- {confsync_server-0.2.0 → confsync_server-0.4.0}/tests/test_api.py +70 -10
- confsync_server-0.4.0/tests/test_auth.py +118 -0
- {confsync_server-0.2.0 → confsync_server-0.4.0}/tests/test_backup.py +3 -3
- {confsync_server-0.2.0 → confsync_server-0.4.0}/tests/test_gitea.py +71 -60
- confsync_server-0.2.0/confsync_server/auth.py +0 -144
- confsync_server-0.2.0/confsync_server/db.py +0 -396
- confsync_server-0.2.0/tests/test_auth.py +0 -93
- {confsync_server-0.2.0 → confsync_server-0.4.0}/.gitignore +0 -0
- {confsync_server-0.2.0 → confsync_server-0.4.0}/README.md +0 -0
- {confsync_server-0.2.0 → confsync_server-0.4.0}/confsync_server/__main__.py +0 -0
- {confsync_server-0.2.0 → confsync_server-0.4.0}/confsync_server/config.py +0 -0
- {confsync_server-0.2.0 → confsync_server-0.4.0}/confsync_server/service.py +0 -0
- {confsync_server-0.2.0 → confsync_server-0.4.0}/pyproject.toml +0 -0
- {confsync_server-0.2.0 → confsync_server-0.4.0}/tests/test_crypto.py +0 -0
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
from __future__ import annotations
|
|
3
3
|
|
|
4
4
|
import html
|
|
5
|
+
import sqlite3
|
|
5
6
|
import time
|
|
6
7
|
from contextlib import asynccontextmanager
|
|
7
8
|
|
|
@@ -37,7 +38,8 @@ button, .btn { padding: .3rem .8rem; border: 1px solid #ccc; border-radius: 6px;
|
|
|
37
38
|
button.primary { background: #1f883d; color: #fff; border-color: #1f883d; }
|
|
38
39
|
button.danger { color: #cf222e; }
|
|
39
40
|
code.key { background: #fff8c5; padding: .4rem .6rem; border-radius: 6px;
|
|
40
|
-
display: inline-block; margin: .5rem 0;
|
|
41
|
+
display: inline-block; margin: .5rem .5rem .5rem 0; overflow-wrap: anywhere;
|
|
42
|
+
user-select: all; }
|
|
41
43
|
.flash { background: #dafbe1; border: 1px solid #1f883d; padding: .5rem .8rem;
|
|
42
44
|
border-radius: 6px; margin-bottom: 1rem; }
|
|
43
45
|
.error { background: #ffebe9; border: 1px solid #cf222e; padding: .5rem .8rem;
|
|
@@ -68,7 +70,7 @@ def _page(title: str, body: str, user=None, flash: str = "", error: str = "") ->
|
|
|
68
70
|
<a href="/keys">API Keys</a>
|
|
69
71
|
{admin_link}
|
|
70
72
|
<span class="spacer"></span>
|
|
71
|
-
<span class="muted">{_e(user['
|
|
73
|
+
<span class="muted">{_e(user['username'])}</span>
|
|
72
74
|
<a href="/logout">Logout</a>
|
|
73
75
|
</nav>"""
|
|
74
76
|
else:
|
|
@@ -85,14 +87,50 @@ def _page(title: str, body: str, user=None, flash: str = "", error: str = "") ->
|
|
|
85
87
|
{nav}
|
|
86
88
|
{flash_html}{error_html}
|
|
87
89
|
{body}
|
|
90
|
+
<script>
|
|
91
|
+
document.querySelectorAll("[data-copy-target]").forEach((button) => {{
|
|
92
|
+
button.addEventListener("click", async () => {{
|
|
93
|
+
const element = document.getElementById(button.dataset.copyTarget);
|
|
94
|
+
try {{
|
|
95
|
+
if (navigator.clipboard && window.isSecureContext) {{
|
|
96
|
+
await navigator.clipboard.writeText(element.textContent);
|
|
97
|
+
}} else {{
|
|
98
|
+
const input = document.createElement("textarea");
|
|
99
|
+
input.value = element.textContent;
|
|
100
|
+
input.style.position = "fixed";
|
|
101
|
+
input.style.opacity = "0";
|
|
102
|
+
document.body.appendChild(input);
|
|
103
|
+
input.select();
|
|
104
|
+
const copied = document.execCommand("copy");
|
|
105
|
+
input.remove();
|
|
106
|
+
if (!copied) throw new Error("copy failed");
|
|
107
|
+
}}
|
|
108
|
+
button.textContent = "Copied";
|
|
109
|
+
}} catch {{
|
|
110
|
+
const range = document.createRange();
|
|
111
|
+
range.selectNodeContents(element);
|
|
112
|
+
const selection = window.getSelection();
|
|
113
|
+
selection.removeAllRanges();
|
|
114
|
+
selection.addRange(range);
|
|
115
|
+
button.textContent = "Press Ctrl+C";
|
|
116
|
+
}}
|
|
117
|
+
setTimeout(() => {{ button.textContent = "Copy"; }}, 1500);
|
|
118
|
+
}});
|
|
119
|
+
}});
|
|
120
|
+
</script>
|
|
88
121
|
</body></html>"""
|
|
89
122
|
return Response(page, media_type="text/html")
|
|
90
123
|
|
|
91
124
|
|
|
92
|
-
def _redirect(url: str, flash: str = "") -> RedirectResponse:
|
|
125
|
+
def _redirect(url: str, flash: str = "", error: str = "") -> RedirectResponse:
|
|
126
|
+
params = []
|
|
93
127
|
if flash:
|
|
128
|
+
params.append(f"flash={flash}")
|
|
129
|
+
if error:
|
|
130
|
+
params.append(f"error={error}")
|
|
131
|
+
if params:
|
|
94
132
|
sep = "&" if "?" in url else "?"
|
|
95
|
-
url = f"{url}{sep}
|
|
133
|
+
url = f"{url}{sep}{'&'.join(params)}"
|
|
96
134
|
return RedirectResponse(url, status_code=303)
|
|
97
135
|
|
|
98
136
|
|
|
@@ -171,23 +209,22 @@ async def _gitea_token_user(request: Request, token: str):
|
|
|
171
209
|
return None, JSONResponse({"error": str(exc)}, status_code=401)
|
|
172
210
|
conn = _open_db(request)
|
|
173
211
|
try:
|
|
174
|
-
|
|
212
|
+
account = _resolve_account(conn, "gitea", profile)
|
|
213
|
+
if account is None:
|
|
175
214
|
return None, JSONResponse(
|
|
176
215
|
{"error": f"Gitea user '{profile['login']}' is not on the allowlist"},
|
|
177
216
|
status_code=403,
|
|
178
217
|
)
|
|
179
|
-
user = db.upsert_gitea_user(conn, profile["id"], profile["login"],
|
|
180
|
-
profile["name"], profile["avatar_url"])
|
|
181
218
|
finally:
|
|
182
219
|
conn.close()
|
|
183
|
-
user_id =
|
|
220
|
+
user_id = account["uid"]
|
|
184
221
|
if len(cache) > 1024:
|
|
185
222
|
cache.clear()
|
|
186
223
|
cache[token_hash] = (user_id, time.time() + GITEA_TOKEN_CACHE_TTL)
|
|
187
224
|
|
|
188
225
|
conn = _open_db(request)
|
|
189
226
|
try:
|
|
190
|
-
user = db.
|
|
227
|
+
user = db.get_account_by_uid(conn, user_id)
|
|
191
228
|
finally:
|
|
192
229
|
conn.close()
|
|
193
230
|
if user is None:
|
|
@@ -273,17 +310,75 @@ def _check_oauth_state(request: Request) -> str | None:
|
|
|
273
310
|
return None
|
|
274
311
|
|
|
275
312
|
|
|
276
|
-
def
|
|
277
|
-
|
|
313
|
+
def _bind_profile_email(conn, uid: int, email: str) -> None:
|
|
314
|
+
email = email.strip().lower()
|
|
315
|
+
if not email or db.get_account_by_email(conn, email) is not None:
|
|
316
|
+
return
|
|
317
|
+
try:
|
|
318
|
+
db.bind_email(conn, uid, email)
|
|
319
|
+
except ValueError:
|
|
320
|
+
# Provider profiles are external input; an invalid or concurrently
|
|
321
|
+
# claimed email must not prevent an already verified identity login.
|
|
322
|
+
pass
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _resolve_account(conn, provider: str, profile: dict):
|
|
326
|
+
"""Map a provider profile (OAuth login or verified token) to an account:
|
|
327
|
+
an existing identity row → its account; else a matching bound email →
|
|
328
|
+
that account (linking the new identity to it); else a brand-new account
|
|
329
|
+
whose candidate username must pass the allowlist. Returns None when the
|
|
330
|
+
login would create a new account that is not allowlisted."""
|
|
331
|
+
identity = db.get_identity(conn, provider, profile["id"])
|
|
332
|
+
if identity is not None:
|
|
333
|
+
db.touch_identity(conn, identity["id"], profile["login"], profile.get("email", ""))
|
|
334
|
+
db.update_account_profile(conn, identity["uid"], profile["name"],
|
|
335
|
+
profile["avatar_url"])
|
|
336
|
+
_bind_profile_email(conn, identity["uid"], profile.get("email", ""))
|
|
337
|
+
return db.get_account_by_uid(conn, identity["uid"])
|
|
338
|
+
email = profile.get("email") or ""
|
|
339
|
+
if email:
|
|
340
|
+
account = db.get_account_by_email(conn, email)
|
|
341
|
+
if account is not None:
|
|
342
|
+
db.link_identity(conn, account["uid"], provider, profile["id"],
|
|
343
|
+
profile["login"], email)
|
|
344
|
+
db.update_account_profile(conn, account["uid"], profile["name"],
|
|
345
|
+
profile["avatar_url"])
|
|
346
|
+
return db.get_account_by_uid(conn, account["uid"])
|
|
347
|
+
if not db.is_login_allowed(conn, profile["login"]):
|
|
348
|
+
return None
|
|
349
|
+
# A pre-created account with exactly this username (e.g. ``confsync-server
|
|
350
|
+
# bootstrap``) adopts the identity on its first login with this provider.
|
|
351
|
+
account = db.get_account_by_username(conn, profile["login"])
|
|
352
|
+
if account is not None:
|
|
353
|
+
linked = {i["provider"] for i in db.list_identities(conn, account["uid"])}
|
|
354
|
+
if provider not in linked:
|
|
355
|
+
db.link_identity(conn, account["uid"], provider, profile["id"],
|
|
356
|
+
profile["login"], email)
|
|
357
|
+
db.update_account_profile(conn, account["uid"], profile["name"],
|
|
358
|
+
profile["avatar_url"])
|
|
359
|
+
_bind_profile_email(conn, account["uid"], email)
|
|
360
|
+
return db.get_account_by_uid(conn, account["uid"])
|
|
361
|
+
account = db.create_account(conn, profile["login"], name=profile["name"],
|
|
362
|
+
avatar_url=profile["avatar_url"])
|
|
363
|
+
db.link_identity(conn, account["uid"], provider, profile["id"],
|
|
364
|
+
profile["login"], email)
|
|
365
|
+
_bind_profile_email(conn, account["uid"], email)
|
|
366
|
+
return account
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _login_profile(request: Request, provider: str, profile: dict) -> Response:
|
|
370
|
+
"""Resolve the OAuth profile to an account (allowlist gates new accounts)
|
|
371
|
+
and start a web session."""
|
|
278
372
|
conn = _open_db(request)
|
|
279
373
|
try:
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
374
|
+
account = _resolve_account(conn, provider, profile)
|
|
375
|
+
if account is None:
|
|
376
|
+
return _page(
|
|
377
|
+
"Access denied", "",
|
|
378
|
+
error=f"{provider.title()} login '{profile['login']}' would create a "
|
|
379
|
+
f"new account, but that username is not on the allowlist.")
|
|
285
380
|
session_token = auth.generate_session_token()
|
|
286
|
-
db.create_session(conn,
|
|
381
|
+
db.create_session(conn, account["uid"], session_token)
|
|
287
382
|
finally:
|
|
288
383
|
conn.close()
|
|
289
384
|
resp = RedirectResponse("/", status_code=303)
|
|
@@ -312,7 +407,7 @@ async def github_callback(request: Request) -> Response:
|
|
|
312
407
|
except ValueError as exc:
|
|
313
408
|
return _page("Error", "", error=str(exc))
|
|
314
409
|
|
|
315
|
-
return _login_profile(request, "
|
|
410
|
+
return _login_profile(request, "github", profile)
|
|
316
411
|
|
|
317
412
|
|
|
318
413
|
async def gitea_callback(request: Request) -> Response:
|
|
@@ -332,7 +427,7 @@ async def gitea_callback(request: Request) -> Response:
|
|
|
332
427
|
except ValueError as exc:
|
|
333
428
|
return _page("Error", "", error=str(exc))
|
|
334
429
|
|
|
335
|
-
return _login_profile(request, "
|
|
430
|
+
return _login_profile(request, "gitea", profile)
|
|
336
431
|
|
|
337
432
|
|
|
338
433
|
async def logout(request: Request) -> Response:
|
|
@@ -356,7 +451,7 @@ async def web_index(request: Request) -> Response:
|
|
|
356
451
|
return resp
|
|
357
452
|
conn = _open_db(request)
|
|
358
453
|
try:
|
|
359
|
-
docs = db.list_documents(conn, user["
|
|
454
|
+
docs = db.list_documents(conn, user["uid"])
|
|
360
455
|
finally:
|
|
361
456
|
conn.close()
|
|
362
457
|
rows = "".join(
|
|
@@ -382,12 +477,12 @@ async def web_doc_view(request: Request) -> Response:
|
|
|
382
477
|
version_q = request.query_params.get("version")
|
|
383
478
|
conn = _open_db(request)
|
|
384
479
|
try:
|
|
385
|
-
row = db.get_document(conn, user["
|
|
480
|
+
row = db.get_document(conn, user["uid"], app, name)
|
|
386
481
|
if row is None:
|
|
387
482
|
return _page("Not found", "", user, error=f"No document {app}/{name}.")
|
|
388
|
-
history = db.list_history(conn, user["
|
|
483
|
+
history = db.list_history(conn, user["uid"], app, name)
|
|
389
484
|
if version_q:
|
|
390
|
-
hrow = db.get_history_version(conn, user["
|
|
485
|
+
hrow = db.get_history_version(conn, user["uid"], app, name, int(version_q))
|
|
391
486
|
if hrow is None:
|
|
392
487
|
return _page("Not found", "", user, error=f"No version {version_q}.")
|
|
393
488
|
content, shown_version = _decrypt_doc(request, hrow), hrow["version"]
|
|
@@ -434,7 +529,7 @@ async def web_doc_save(request: Request) -> Response:
|
|
|
434
529
|
content = str(form.get("content", ""))
|
|
435
530
|
if len(content.encode()) > MAX_CONTENT_BYTES:
|
|
436
531
|
return _page("Too large", "", user, error="Content exceeds 4 MB limit.")
|
|
437
|
-
version = _store_doc(request, user["
|
|
532
|
+
version = _store_doc(request, user["uid"], app, name, content)
|
|
438
533
|
return _redirect(f"/docs/{app}/{name}", flash=f"Saved as v{version}.")
|
|
439
534
|
|
|
440
535
|
|
|
@@ -447,9 +542,9 @@ async def web_doc_raw(request: Request) -> Response:
|
|
|
447
542
|
conn = _open_db(request)
|
|
448
543
|
try:
|
|
449
544
|
if version_q:
|
|
450
|
-
row = db.get_history_version(conn, user["
|
|
545
|
+
row = db.get_history_version(conn, user["uid"], app, name, int(version_q))
|
|
451
546
|
else:
|
|
452
|
-
row = db.get_document(conn, user["
|
|
547
|
+
row = db.get_document(conn, user["uid"], app, name)
|
|
453
548
|
if row is None:
|
|
454
549
|
return PlainTextResponse("not found", status_code=404)
|
|
455
550
|
content = _decrypt_doc(request, row)
|
|
@@ -467,7 +562,7 @@ async def web_doc_delete(request: Request) -> Response:
|
|
|
467
562
|
app, name = request.path_params["app"], request.path_params["name"]
|
|
468
563
|
conn = _open_db(request)
|
|
469
564
|
try:
|
|
470
|
-
db.delete_document(conn, user["
|
|
565
|
+
db.delete_document(conn, user["uid"], app, name)
|
|
471
566
|
finally:
|
|
472
567
|
conn.close()
|
|
473
568
|
return _redirect("/", flash=f"Deleted {app}/{name}.")
|
|
@@ -482,13 +577,13 @@ async def web_doc_rollback(request: Request) -> Response:
|
|
|
482
577
|
version = int(form.get("version", "0"))
|
|
483
578
|
conn = _open_db(request)
|
|
484
579
|
try:
|
|
485
|
-
hrow = db.get_history_version(conn, user["
|
|
580
|
+
hrow = db.get_history_version(conn, user["uid"], app, name, version)
|
|
486
581
|
if hrow is None:
|
|
487
582
|
return _page("Not found", "", user, error=f"No history version {version}.")
|
|
488
583
|
content = _decrypt_doc(request, hrow)
|
|
489
584
|
finally:
|
|
490
585
|
conn.close()
|
|
491
|
-
new_version = _store_doc(request, user["
|
|
586
|
+
new_version = _store_doc(request, user["uid"], app, name, content)
|
|
492
587
|
return _redirect(f"/docs/{app}/{name}",
|
|
493
588
|
flash=f"Rolled back to v{version} content (saved as v{new_version}).")
|
|
494
589
|
|
|
@@ -501,11 +596,22 @@ async def web_keys(request: Request) -> Response:
|
|
|
501
596
|
return resp
|
|
502
597
|
conn = _open_db(request)
|
|
503
598
|
try:
|
|
504
|
-
keys = db.list_api_keys(conn, user["
|
|
599
|
+
keys = db.list_api_keys(conn, user["uid"])
|
|
505
600
|
finally:
|
|
506
601
|
conn.close()
|
|
507
602
|
rows = ""
|
|
508
603
|
for k in keys:
|
|
604
|
+
plaintext = db.decrypt_api_key(k, _master_key(request))
|
|
605
|
+
if plaintext is None:
|
|
606
|
+
key_html = (
|
|
607
|
+
f"<code>{_e(k['prefix'])}…</code> "
|
|
608
|
+
"<span class='muted'>hash-only; create a replacement to view/copy</span>"
|
|
609
|
+
)
|
|
610
|
+
else:
|
|
611
|
+
key_html = (
|
|
612
|
+
f"<code class='key' id='api-key-{k['id']}'>{_e(plaintext)}</code>"
|
|
613
|
+
f"<button type='button' data-copy-target='api-key-{k['id']}'>Copy</button>"
|
|
614
|
+
)
|
|
509
615
|
if k["revoked"]:
|
|
510
616
|
action = ""
|
|
511
617
|
status = "revoked"
|
|
@@ -516,15 +622,16 @@ async def web_keys(request: Request) -> Response:
|
|
|
516
622
|
)
|
|
517
623
|
status = ""
|
|
518
624
|
rows += (
|
|
519
|
-
f"<tr><td>{_e(k['name'])}</td><td
|
|
625
|
+
f"<tr><td>{_e(k['name'])}</td><td>{key_html}</td>"
|
|
520
626
|
f"<td>{_fmt_ts(k['created_at'])}</td><td>{_fmt_ts(k['last_used_at'])}</td>"
|
|
521
627
|
f"<td>{status}</td><td>{action}</td></tr>"
|
|
522
628
|
)
|
|
523
|
-
table = ("<table><tr><th>Name</th><th>
|
|
629
|
+
table = ("<table><tr><th>Name</th><th>API key</th><th>Created</th><th>Last used</th>"
|
|
524
630
|
f"<th></th><th></th></tr>{rows}</table>" if rows
|
|
525
631
|
else "<p class='muted'>No API keys yet.</p>")
|
|
526
632
|
body = f"""
|
|
527
633
|
<h1>API Keys</h1>
|
|
634
|
+
<p class="muted">You can view and copy your keys whenever you are logged in.</p>
|
|
528
635
|
{table}
|
|
529
636
|
<h2>Create key</h2>
|
|
530
637
|
<form method="post" action="/keys/create">
|
|
@@ -544,13 +651,15 @@ async def web_key_create(request: Request) -> Response:
|
|
|
544
651
|
plaintext = auth.generate_api_key()
|
|
545
652
|
conn = _open_db(request)
|
|
546
653
|
try:
|
|
547
|
-
db.create_api_key(conn, user["
|
|
654
|
+
db.create_api_key(conn, user["uid"], name, plaintext,
|
|
655
|
+
master_key=_master_key(request))
|
|
548
656
|
finally:
|
|
549
657
|
conn.close()
|
|
550
658
|
body = f"""
|
|
551
659
|
<h1>API key created</h1>
|
|
552
|
-
<p>
|
|
553
|
-
<code class="key">{_e(plaintext)}</code>
|
|
660
|
+
<p>You can view and copy it anytime from API Keys while logged in.</p>
|
|
661
|
+
<code class="key" id="new-api-key">{_e(plaintext)}</code>
|
|
662
|
+
<button type="button" data-copy-target="new-api-key">Copy</button>
|
|
554
663
|
<p>Use it with: <code>confsync login --server {_e(_settings(request).external_url)}</code></p>
|
|
555
664
|
<p><a class="btn" href="/keys">Back to keys</a></p>
|
|
556
665
|
"""
|
|
@@ -564,7 +673,7 @@ async def web_key_revoke(request: Request) -> Response:
|
|
|
564
673
|
key_id = int(request.path_params["key_id"])
|
|
565
674
|
conn = _open_db(request)
|
|
566
675
|
try:
|
|
567
|
-
db.revoke_api_key(conn, user["
|
|
676
|
+
db.revoke_api_key(conn, user["uid"], key_id)
|
|
568
677
|
finally:
|
|
569
678
|
conn.close()
|
|
570
679
|
return _redirect("/keys", flash="Key revoked.")
|
|
@@ -580,10 +689,37 @@ async def web_admin(request: Request) -> Response:
|
|
|
580
689
|
return _page("Forbidden", "", user, error="Admin only.")
|
|
581
690
|
conn = _open_db(request)
|
|
582
691
|
try:
|
|
692
|
+
accounts = db.list_accounts(conn)
|
|
583
693
|
allowed = db.list_allowed_logins(conn)
|
|
584
694
|
finally:
|
|
585
695
|
conn.close()
|
|
586
|
-
rows = ""
|
|
696
|
+
rows = ""
|
|
697
|
+
for a in accounts:
|
|
698
|
+
admin_badge = " <b>· admin</b>" if a["is_admin"] else ""
|
|
699
|
+
emails = " · ".join(
|
|
700
|
+
f"{_e(e)} <form class='inline' method='post'"
|
|
701
|
+
f" action='/admin/accounts/{a['uid']}/emails/remove'>"
|
|
702
|
+
f"<input type='hidden' name='email' value='{_e(e)}'>"
|
|
703
|
+
f"<button type='submit'>×</button></form>"
|
|
704
|
+
for e in a["emails"]
|
|
705
|
+
) or "<span class='muted'>none</span>"
|
|
706
|
+
rows += (
|
|
707
|
+
f"<tr><td>{a['uid']}</td>"
|
|
708
|
+
f"<td><b>{_e(a['username'])}</b>{admin_badge}"
|
|
709
|
+
f"<br><span class='muted'>{_e(a['identities'] or 'no linked logins')}</span></td>"
|
|
710
|
+
f"<td>{emails}</td>"
|
|
711
|
+
f"<td><form class='inline' method='post' action='/admin/accounts/{a['uid']}/emails/add'>"
|
|
712
|
+
f"<input type='text' name='email' placeholder='add email' required>"
|
|
713
|
+
f"<button type='submit'>Bind</button></form></td>"
|
|
714
|
+
f"<td><form class='inline' method='post' action='/admin/accounts/{a['uid']}/admin'>"
|
|
715
|
+
f"<button type='submit'>{'Revoke admin' if a['is_admin'] else 'Make admin'}</button></form></td>"
|
|
716
|
+
f"</tr>"
|
|
717
|
+
)
|
|
718
|
+
accounts_table = (
|
|
719
|
+
"<table><tr><th>uid</th><th>username</th><th>email bindings</th>"
|
|
720
|
+
f"<th></th><th></th></tr>{rows}</table>"
|
|
721
|
+
)
|
|
722
|
+
allow_rows = "".join(
|
|
587
723
|
f"<tr><td>{_e(login)}</td>"
|
|
588
724
|
f"<td><form class='inline' method='post' action='/admin/disallow'>"
|
|
589
725
|
f"<input type='hidden' name='login' value='{_e(login)}'>"
|
|
@@ -591,17 +727,114 @@ async def web_admin(request: Request) -> Response:
|
|
|
591
727
|
for login in allowed
|
|
592
728
|
)
|
|
593
729
|
body = f"""
|
|
594
|
-
<h1>Admin —
|
|
595
|
-
<
|
|
596
|
-
|
|
730
|
+
<h1>Admin — accounts</h1>
|
|
731
|
+
<p class="muted">Each account has one uid + username and any number of bound
|
|
732
|
+
emails. GitHub/Gitea logins map to an account by linked identity, or by
|
|
733
|
+
email binding; documents are private to an account.</p>
|
|
734
|
+
{accounts_table}
|
|
735
|
+
<h2>Create account</h2>
|
|
736
|
+
<form method="post" action="/admin/accounts/create">
|
|
737
|
+
<input type="text" name="username" placeholder="username" required>
|
|
738
|
+
<input type="text" name="emails" placeholder="emails, comma separated (optional)">
|
|
739
|
+
<button class="primary" type="submit">Create</button>
|
|
740
|
+
</form>
|
|
741
|
+
<h2>Allowlist (usernames that may self-register)</h2>
|
|
742
|
+
<table><tr><th>Username</th><th></th></tr>{allow_rows}</table>
|
|
597
743
|
<form method="post" action="/admin/allow">
|
|
598
|
-
<input type="text" name="login" placeholder="username (
|
|
744
|
+
<input type="text" name="login" placeholder="username (as they log in on GitHub/Gitea)" required>
|
|
599
745
|
<button class="primary" type="submit">Allow</button>
|
|
600
746
|
</form>
|
|
601
747
|
"""
|
|
602
748
|
return _page("Admin", body, user, **_flash_error(request))
|
|
603
749
|
|
|
604
750
|
|
|
751
|
+
def _admin_action(request: Request):
|
|
752
|
+
"""Returns (user, response). response is set when not an admin."""
|
|
753
|
+
user, resp = _require_web_user(request)
|
|
754
|
+
if resp:
|
|
755
|
+
return None, resp
|
|
756
|
+
if not user["is_admin"]:
|
|
757
|
+
return None, _page("Forbidden", "", user, error="Admin only.")
|
|
758
|
+
return user, None
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
async def web_admin_account_create(request: Request) -> Response:
|
|
762
|
+
user, resp = _admin_action(request)
|
|
763
|
+
if resp:
|
|
764
|
+
return resp
|
|
765
|
+
form = await request.form()
|
|
766
|
+
username = str(form.get("username", "")).strip()
|
|
767
|
+
emails = [e.strip() for e in str(form.get("emails", "")).split(",") if e.strip()]
|
|
768
|
+
if not username:
|
|
769
|
+
return _redirect("/admin", error="Username is required.")
|
|
770
|
+
conn = _open_db(request)
|
|
771
|
+
try:
|
|
772
|
+
try:
|
|
773
|
+
account = db.create_account(conn, username)
|
|
774
|
+
for e in emails:
|
|
775
|
+
db.bind_email(conn, account["uid"], e)
|
|
776
|
+
except (ValueError, LookupError, sqlite3.IntegrityError) as exc:
|
|
777
|
+
return _redirect("/admin", error=f"Cannot create account: {exc}")
|
|
778
|
+
finally:
|
|
779
|
+
conn.close()
|
|
780
|
+
return _redirect("/admin", flash=f"Created account '{account['username']}' (uid {account['uid']}).")
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
async def web_admin_email_add(request: Request) -> Response:
|
|
784
|
+
user, resp = _admin_action(request)
|
|
785
|
+
if resp:
|
|
786
|
+
return resp
|
|
787
|
+
uid = int(request.path_params["uid"])
|
|
788
|
+
form = await request.form()
|
|
789
|
+
email = str(form.get("email", "")).strip()
|
|
790
|
+
conn = _open_db(request)
|
|
791
|
+
try:
|
|
792
|
+
try:
|
|
793
|
+
added = db.bind_email(conn, uid, email)
|
|
794
|
+
except (ValueError, LookupError) as exc:
|
|
795
|
+
return _redirect("/admin", error=f"Cannot bind email: {exc}")
|
|
796
|
+
finally:
|
|
797
|
+
conn.close()
|
|
798
|
+
flash = f"Bound {email}." if added else f"{email} was already bound."
|
|
799
|
+
return _redirect("/admin", flash=flash)
|
|
800
|
+
|
|
801
|
+
|
|
802
|
+
async def web_admin_email_remove(request: Request) -> Response:
|
|
803
|
+
user, resp = _admin_action(request)
|
|
804
|
+
if resp:
|
|
805
|
+
return resp
|
|
806
|
+
uid = int(request.path_params["uid"])
|
|
807
|
+
form = await request.form()
|
|
808
|
+
email = str(form.get("email", "")).strip()
|
|
809
|
+
conn = _open_db(request)
|
|
810
|
+
try:
|
|
811
|
+
removed = db.unbind_email(conn, uid, email)
|
|
812
|
+
finally:
|
|
813
|
+
conn.close()
|
|
814
|
+
if not removed:
|
|
815
|
+
return _redirect("/admin", error=f"{email} was not bound to uid {uid}.")
|
|
816
|
+
return _redirect("/admin", flash=f"Unbound {email} from uid {uid}.")
|
|
817
|
+
|
|
818
|
+
|
|
819
|
+
async def web_admin_account_admin(request: Request) -> Response:
|
|
820
|
+
user, resp = _admin_action(request)
|
|
821
|
+
if resp:
|
|
822
|
+
return resp
|
|
823
|
+
uid = int(request.path_params["uid"])
|
|
824
|
+
conn = _open_db(request)
|
|
825
|
+
try:
|
|
826
|
+
account = db.get_account_by_uid(conn, uid)
|
|
827
|
+
if account is None:
|
|
828
|
+
return _redirect("/admin", error=f"No account uid={uid}.")
|
|
829
|
+
if uid == user["uid"]:
|
|
830
|
+
return _redirect("/admin", error="You cannot revoke your own admin.")
|
|
831
|
+
db.set_account_admin(conn, uid, not account["is_admin"])
|
|
832
|
+
finally:
|
|
833
|
+
conn.close()
|
|
834
|
+
verb = "granted admin to" if not account["is_admin"] else "revoked admin from"
|
|
835
|
+
return _redirect("/admin", flash=f"{verb} uid {uid} ({account['username']}).")
|
|
836
|
+
|
|
837
|
+
|
|
605
838
|
async def web_admin_allow(request: Request) -> Response:
|
|
606
839
|
user, resp = _require_web_user(request)
|
|
607
840
|
if resp:
|
|
@@ -647,7 +880,8 @@ async def api_whoami(request: Request) -> Response:
|
|
|
647
880
|
user, resp = await _require_api_user(request)
|
|
648
881
|
if resp:
|
|
649
882
|
return resp
|
|
650
|
-
return JSONResponse({"
|
|
883
|
+
return JSONResponse({"username": user["username"], "login": user["username"],
|
|
884
|
+
"name": user["name"]})
|
|
651
885
|
|
|
652
886
|
|
|
653
887
|
async def api_list(request: Request) -> Response:
|
|
@@ -656,7 +890,7 @@ async def api_list(request: Request) -> Response:
|
|
|
656
890
|
return resp
|
|
657
891
|
conn = _open_db(request)
|
|
658
892
|
try:
|
|
659
|
-
docs = db.list_documents(conn, user["
|
|
893
|
+
docs = db.list_documents(conn, user["uid"])
|
|
660
894
|
finally:
|
|
661
895
|
conn.close()
|
|
662
896
|
return JSONResponse({"documents": [
|
|
@@ -673,7 +907,7 @@ async def api_get(request: Request) -> Response:
|
|
|
673
907
|
app, name = request.path_params["app"], request.path_params["name"]
|
|
674
908
|
conn = _open_db(request)
|
|
675
909
|
try:
|
|
676
|
-
row = db.get_document(conn, user["
|
|
910
|
+
row = db.get_document(conn, user["uid"], app, name)
|
|
677
911
|
if row is None:
|
|
678
912
|
return JSONResponse({"error": f"no document {app}/{name}"}, status_code=404)
|
|
679
913
|
return JSONResponse({
|
|
@@ -698,7 +932,7 @@ async def api_put(request: Request) -> Response:
|
|
|
698
932
|
return JSONResponse({"error": "body must be {\"content\": \"...\"}"}, status_code=400)
|
|
699
933
|
if len(content.encode()) > MAX_CONTENT_BYTES:
|
|
700
934
|
return JSONResponse({"error": "content exceeds 4 MB limit"}, status_code=413)
|
|
701
|
-
version = _store_doc(request, user["
|
|
935
|
+
version = _store_doc(request, user["uid"], app, name, content)
|
|
702
936
|
return JSONResponse({"app": app, "name": name, "version": version})
|
|
703
937
|
|
|
704
938
|
|
|
@@ -709,7 +943,7 @@ async def api_delete(request: Request) -> Response:
|
|
|
709
943
|
app, name = request.path_params["app"], request.path_params["name"]
|
|
710
944
|
conn = _open_db(request)
|
|
711
945
|
try:
|
|
712
|
-
existed = db.delete_document(conn, user["
|
|
946
|
+
existed = db.delete_document(conn, user["uid"], app, name)
|
|
713
947
|
finally:
|
|
714
948
|
conn.close()
|
|
715
949
|
if not existed:
|
|
@@ -724,7 +958,7 @@ async def api_history(request: Request) -> Response:
|
|
|
724
958
|
app, name = request.path_params["app"], request.path_params["name"]
|
|
725
959
|
conn = _open_db(request)
|
|
726
960
|
try:
|
|
727
|
-
rows = db.list_history(conn, user["
|
|
961
|
+
rows = db.list_history(conn, user["uid"], app, name)
|
|
728
962
|
finally:
|
|
729
963
|
conn.close()
|
|
730
964
|
return JSONResponse({"history": [
|
|
@@ -741,7 +975,7 @@ async def api_history_get(request: Request) -> Response:
|
|
|
741
975
|
version = int(request.path_params["version"])
|
|
742
976
|
conn = _open_db(request)
|
|
743
977
|
try:
|
|
744
|
-
row = db.get_history_version(conn, user["
|
|
978
|
+
row = db.get_history_version(conn, user["uid"], app, name, version)
|
|
745
979
|
if row is None:
|
|
746
980
|
return JSONResponse({"error": f"no version {version}"}, status_code=404)
|
|
747
981
|
return JSONResponse({
|
|
@@ -782,6 +1016,10 @@ def create_app(settings: ServerSettings | None = None) -> Starlette:
|
|
|
782
1016
|
Route("/admin", web_admin),
|
|
783
1017
|
Route("/admin/allow", web_admin_allow, methods=["POST"]),
|
|
784
1018
|
Route("/admin/disallow", web_admin_disallow, methods=["POST"]),
|
|
1019
|
+
Route("/admin/accounts/create", web_admin_account_create, methods=["POST"]),
|
|
1020
|
+
Route("/admin/accounts/{uid:int}/emails/add", web_admin_email_add, methods=["POST"]),
|
|
1021
|
+
Route("/admin/accounts/{uid:int}/emails/remove", web_admin_email_remove, methods=["POST"]),
|
|
1022
|
+
Route("/admin/accounts/{uid:int}/admin", web_admin_account_admin, methods=["POST"]),
|
|
785
1023
|
Route("/docs/{app}/{name:path}/raw", web_doc_raw),
|
|
786
1024
|
Route("/docs/{app}/{name:path}/rollback", web_doc_rollback, methods=["POST"]),
|
|
787
1025
|
Route("/docs/{app}/{name:path}/delete", web_doc_delete, methods=["POST"]),
|