Admin user editing, knight-rider demos, self-contained user seeds

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-05-10 02:23:53 +12:00
parent b02a182bf1
commit f7892dd31b
16 changed files with 864 additions and 75 deletions

View File

@@ -54,4 +54,5 @@ class InviteToken(Base):
consumed_by_user_id: Mapped[int | None] = mapped_column(
ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True
)
grants_superuser: Mapped[bool] = mapped_column(Boolean, default=False)
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=_utc_naive)

View File

@@ -3,6 +3,7 @@ from contextlib import asynccontextmanager
from fastapi import Depends, FastAPI
from fastapi.staticfiles import StaticFiles
from sqlalchemy import text
from sqlalchemy.orm import sessionmaker
from editor_app.config import STATIC_DIR, WORKSPACE_ROOT
@@ -21,6 +22,15 @@ async def lifespan(_app: FastAPI):
(WORKSPACE_ROOT / "lib").mkdir(parents=True, exist_ok=True)
engine = get_engine()
Base.metadata.create_all(bind=engine)
with engine.begin() as conn:
cols = conn.execute(text("PRAGMA table_info(invite_tokens)")).fetchall()
column_names = {row[1] for row in cols}
if column_names and "grants_superuser" not in column_names:
conn.execute(
text(
"ALTER TABLE invite_tokens ADD COLUMN grants_superuser BOOLEAN NOT NULL DEFAULT 0"
)
)
factory = sessionmaker(autocommit=False, autoflush=False, bind=engine)
db = factory()
try:

View File

@@ -6,7 +6,7 @@ from sqlalchemy.orm import Session
from editor_app.db.session import get_db
from editor_app.db.models import User
from editor_app.deps import require_superuser
from editor_app.schemas.users import InviteCreateRequest, InviteCreateResponse, UserCreateAdmin, UserPublic
from editor_app.schemas.users import InviteCreateRequest, InviteCreateResponse, UserPublic, UserUpdateAdmin
from editor_app.services import accounts
router = APIRouter(prefix="/api/users", tags=["users"])
@@ -20,21 +20,26 @@ async def list_users(
return [UserPublic.model_validate(u) for u in accounts.list_users(db)]
@router.post("", response_model=UserPublic)
async def create_user_admin(
body: UserCreateAdmin,
admin: User = Depends(require_superuser),
@router.patch("/{user_id}", response_model=UserPublic)
async def patch_user_admin(
user_id: int,
body: UserUpdateAdmin,
_admin: User = Depends(require_superuser),
db: Session = Depends(get_db),
) -> UserPublic:
if accounts.get_user_by_username(db, body.username):
raise HTTPException(status_code=409, detail="Username already taken")
user = accounts.create_user(
db,
body.username,
body.password,
is_superuser=body.is_superuser,
)
return UserPublic.model_validate(user)
try:
updated = accounts.update_user(
db,
user_id,
username=body.username,
password=body.password,
is_superuser=body.is_superuser,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if updated is None:
raise HTTPException(status_code=404, detail="User not found")
return UserPublic.model_validate(updated)
@router.delete("/{user_id}")

View File

@@ -1,4 +1,4 @@
from pydantic import BaseModel, Field, field_validator
from pydantic import BaseModel, Field, field_validator, model_validator
class RegisterRequest(BaseModel):
@@ -6,6 +6,14 @@ class RegisterRequest(BaseModel):
password: str = Field(min_length=8, max_length=128)
invite_token: str | None = Field(default=None, min_length=8, max_length=256)
@field_validator("invite_token", mode="before")
@classmethod
def normalize_invite_token(cls, v: object) -> object:
if isinstance(v, str):
s = v.strip()
return s if s else None
return v
@field_validator("username")
@classmethod
def username_chars(cls, v: str) -> str:
@@ -28,19 +36,34 @@ class UserPublic(BaseModel):
model_config = {"from_attributes": True}
class UserCreateAdmin(BaseModel):
username: str = Field(min_length=3, max_length=64)
password: str = Field(min_length=8, max_length=128)
is_superuser: bool = False
class UserUpdateAdmin(BaseModel):
username: str | None = Field(default=None, min_length=3, max_length=64)
password: str | None = Field(default=None, min_length=8, max_length=128)
is_superuser: bool | None = None
@field_validator("username", "password", mode="before")
@classmethod
def empty_str_to_none(cls, v: object) -> object:
if isinstance(v, str) and not v.strip():
return None
return v
@field_validator("username")
@classmethod
def username_chars(cls, v: str) -> str:
def username_chars(cls, v: str | None) -> str | None:
if v is None:
return None
s = v.strip()
if not s.replace("_", "").isalnum():
raise ValueError("Username may only contain letters, numbers, and underscores")
return s
@model_validator(mode="after")
def none_empty_patch(self):
if self.username is None and self.password is None and self.is_superuser is None:
raise ValueError("Provide username, password, and/or superuser changes")
return self
class AuthStatusResponse(BaseModel):
auth_enabled: bool

View File

@@ -88,7 +88,7 @@ def register_user_with_invite(db: Session, username: str, password: str, invite_
raise ValueError("Invite is invalid or expired")
if get_user_by_username(db, username):
raise ValueError("Username already taken")
user = create_user(db, username, password, is_superuser=False)
user = create_user(db, username, password, is_superuser=bool(invite.grants_superuser))
invite.used_at = _utc_naive()
invite.consumed_by_user_id = user.id
db.add(invite)
@@ -149,11 +149,59 @@ def delete_user(db: Session, user_id: int) -> bool:
return True
def update_user(
db: Session,
user_id: int,
*,
username: str | None = None,
password: str | None = None,
is_superuser: bool | None = None,
) -> User | None:
user = get_user_by_id(db, user_id)
if user is None:
return None
old_username = user.username
if username is not None:
normalized = username.strip()
if normalized != old_username:
dup = db.scalars(select(User).where(User.username == normalized, User.id != user_id)).first()
if dup is not None:
raise ValueError("Username already taken")
user_workspace.rename_user_workspace_leaf(user_id, old_username, normalized)
user.username = normalized
if password is not None:
user.password_hash = hash_password(password)
if is_superuser is not None:
if user.is_superuser and not is_superuser:
remaining = db.scalar(
select(func.count())
.select_from(User)
.where(User.is_superuser.is_(True), User.id != user_id)
)
if not remaining:
raise ValueError("Cannot demote the last administrator")
user.is_superuser = is_superuser
db.add(user)
db.commit()
db.refresh(user)
return user
def invite_required() -> bool:
return os.environ.get("AUTH_INVITE_ONLY", "true").strip().lower() in ("1", "true", "yes", "on")
def create_invite(db: Session, email: str, invited_by_user_id: int | None = None, expires_days: int = 7) -> InviteToken:
def create_invite(
db: Session,
email: str,
invited_by_user_id: int | None = None,
expires_days: int = 7,
) -> InviteToken:
token = secrets.token_urlsafe(36)
expires = _utc_naive() + dt.timedelta(days=max(1, min(30, int(expires_days))))
row = InviteToken(

View File

@@ -1,12 +1,20 @@
from __future__ import annotations
import re
import shutil
from pathlib import Path
from editor_app import config
DEFAULT_MAIN_PY = 'print("Hello, World!")\n'
# Self-contained demos copied from shipped `workspace/code/` (stdlib + machine/neopixel/time only).
_CANONICAL_DEMO_FILENAMES = (
"pattern_rainbow_demo.py",
"pattern_twinkle_demo.py",
"pattern_chase_demo.py",
)
def safe_workspace_leaf(username: str, user_id: int) -> str:
base = re.sub(r"[^a-zA-Z0-9._-]+", "-", username.strip()).strip("-").lower() or "user"
@@ -18,10 +26,41 @@ def user_workspace_root(user_id: int, username: str, workspace_root: Path | None
return root / "users" / safe_workspace_leaf(username, user_id)
def _seed_canonical_demos_into_code(code_dir: Path) -> None:
src_root = config.PROJECT_ROOT.resolve() / "workspace" / "code"
for filename in _CANONICAL_DEMO_FILENAMES:
dst = code_dir / filename
if dst.exists():
continue
src = src_root / filename
if src.is_file():
dst.write_text(src.read_text(encoding="utf-8"), encoding="utf-8")
def ensure_default_code_main(user_root: Path) -> None:
"""Ensure code/ exists and add a starter main.py when missing."""
"""Ensure code/ has main.py and self-contained NeoPixel demos (copied from repo workspace/code/)."""
code_dir = user_root / "code"
code_dir.mkdir(parents=True, exist_ok=True)
main_py = code_dir / "main.py"
if not main_py.exists():
main_py.write_text(DEFAULT_MAIN_PY, encoding="utf-8")
_seed_canonical_demos_into_code(code_dir)
def rename_user_workspace_leaf(
user_id: int, old_username: str, new_username: str, workspace_root: Path | None = None
) -> None:
"""Rename per-user workspace directory when login name changes."""
root = (workspace_root or config.WORKSPACE_ROOT).resolve()
users_dir = root / "users"
src = users_dir / safe_workspace_leaf(old_username, user_id)
dst = users_dir / safe_workspace_leaf(new_username, user_id)
if src.resolve() == dst.resolve():
return
dst.parent.mkdir(parents=True, exist_ok=True)
if dst.exists():
raise ValueError("Workspace folder for new username already exists; pick another username.")
if src.exists():
shutil.move(str(src), str(dst))
else:
ensure_default_code_main(dst)

View File

@@ -105,6 +105,79 @@
border-radius: 6px;
padding: 0.25rem 0.5rem;
}
.user-actions {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
align-items: center;
justify-content: flex-end;
}
.btn-danger {
background: transparent;
border-color: #f87171;
color: #fecaca;
}
.btn-danger:hover:not(:disabled) {
background: rgba(248, 113, 113, 0.15);
}
.btn:disabled {
opacity: 0.45;
cursor: not-allowed;
}
#admin-users-feedback:not(:empty) {
padding: 0.5rem 0.65rem;
border-radius: 8px;
font-size: 0.85rem;
margin: 0.5rem 0;
}
#admin-users-feedback.ok {
background: rgba(34, 197, 94, 0.12);
border: 1px solid rgba(74, 222, 128, 0.35);
color: #bbf7d0;
}
#admin-users-feedback.err {
background: rgba(248, 113, 113, 0.1);
border: 1px solid rgba(248, 113, 113, 0.35);
color: #fecaca;
}
.user-edit-form {
margin-top: 1rem;
padding-top: 1rem;
border-top: 1px solid rgba(148, 163, 184, 0.25);
}
.user-edit-form label {
display: block;
margin-bottom: 0.65rem;
}
.user-edit-form input[type='text'],
.user-edit-form input[type='password'] {
width: 100%;
max-width: 320px;
padding: 0.45rem 0.55rem;
border-radius: 8px;
border: 1px solid #64748b;
background: #0f172a;
color: #e2e8f0;
margin-top: 0.25rem;
box-sizing: border-box;
}
.user-edit-form .edit-actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
margin-top: 0.65rem;
}
.user-edit-form .super-line {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.85rem;
color: #cbd5e1;
margin-bottom: 0.65rem;
}
.user-edit-form .super-line input {
accent-color: #3b82f6;
}
</style>
</head>
<body>
@@ -123,19 +196,48 @@
<input id="api-key" type="password" autocomplete="off" placeholder="Leave blank if not used" />
<p class="note">The key is kept in <code>sessionStorage</code>. You can also use <code>?api_key=…</code> on the editor URL.</p>
</div>
<section id="invite-panel" class="invite-panel hidden">
<strong>Admin invites</strong>
<p class="note" style="margin-top:0.4rem">Create an email invite link for signup.</p>
<div class="invite-row">
<input id="invite-email" type="email" placeholder="new.user@example.com" autocomplete="email" />
<button type="button" class="btn btn-primary" id="invite-create-btn">Create invite</button>
<button type="button" class="btn btn-ghost" id="invite-link-btn">Create link only</button>
</div>
<div id="invite-result" class="invite-result"></div>
</section>
<section id="users-panel" class="users-panel hidden">
<strong>User management</strong>
<p class="note" style="margin-top:0.35rem">
New accounts sign up via an <strong>invite link</strong> below. Remove accounts here or open their workspace.
</p>
<div id="admin-users-feedback" role="status" aria-live="polite"></div>
<p style="margin: 1rem 0 0.35rem 0; font-size: 0.9rem; color: #94a3b8">Accounts</p>
<div id="users-list" class="users-list"></div>
<div id="user-edit-form" class="user-edit-form hidden">
<strong id="user-edit-heading">Edit account</strong>
<p class="note" style="margin: 0.35rem 0 0.5rem">Change login name or admin role; set a password only when you mean to reset it.</p>
<input type="hidden" id="edit-user-id" autocomplete="off" />
<label for="edit-user-username">
Username
<input type="text" id="edit-user-username" name="username" autocomplete="username" minlength="3" maxlength="64" />
</label>
<label for="edit-user-password">
New password
<input type="password" id="edit-user-password" name="password" autocomplete="new-password" minlength="8" maxlength="128" placeholder="Leave blank to keep current" />
</label>
<label class="super-line">
<input type="checkbox" id="edit-user-super" />
Superuser (can manage accounts and invites)
</label>
<div class="edit-actions">
<button type="button" class="btn btn-primary" id="edit-user-save">Save changes</button>
<button type="button" class="btn btn-ghost" id="edit-user-cancel">Cancel</button>
</div>
</div>
</section>
<section id="invite-panel" class="invite-panel hidden">
<strong>Add users via invite link</strong>
<p class="note" style="margin-top:0.4rem">
Each link lets <strong>one</strong> person create their own account at <code>/register?invite=…</code> with a password they choose. After it is used, create a new link for the next person.
</p>
<div class="invite-row">
<input id="invite-email" type="email" placeholder="new.user@example.com" autocomplete="email" />
<button type="button" class="btn btn-primary" id="invite-create-btn">Email invite</button>
<button type="button" class="btn btn-ghost" id="invite-link-btn">Invite link only</button>
</div>
<div id="invite-result" class="invite-result"></div>
<button type="button" class="btn btn-ghost hidden" id="invite-copy-btn" aria-label="Copy invite link">Copy invite link</button>
</section>
<div class="nav">
<a class="btn btn-primary" href="/editor" id="open-editor">Open Editor</a>
@@ -146,6 +248,29 @@
const storageKey = 'python-editor.api_key';
const input = document.getElementById('api-key');
const openLink = document.getElementById('open-editor');
let currentAdminUserId = null;
function formatApiDetail(body) {
if (!body || body.detail === undefined || body.detail === null) return '';
const d = body.detail;
if (typeof d === 'string') return d;
if (Array.isArray(d))
return d
.map((item) =>
typeof item === 'object' && item && item.msg ? String(item.msg) : JSON.stringify(item)
)
.join(' ');
return String(d);
}
function setAdminUsersFeedback(kind, msg) {
const el = document.getElementById('admin-users-feedback');
if (!el) return;
el.textContent = msg || '';
el.classList.remove('ok', 'err');
if (kind === 'ok') el.classList.add('ok');
if (kind === 'err') el.classList.add('err');
}
async function refreshAuthNav() {
const st = await fetch('/api/auth/status');
@@ -158,6 +283,7 @@
const invitePanel = document.getElementById('invite-panel');
const usersPanel = document.getElementById('users-panel');
if (!status.auth_enabled) {
currentAdminUserId = null;
loginEl.classList.add('hidden');
regEl.classList.add('hidden');
outEl.classList.add('hidden');
@@ -181,15 +307,18 @@
if (optionalKey) optionalKey.classList.add('hidden');
if (invitePanel) {
if (j.user && j.user.is_superuser) {
currentAdminUserId = j.user.id;
invitePanel.classList.remove('hidden');
if (usersPanel) usersPanel.classList.remove('hidden');
await refreshUsersList();
await refreshUsersList(j.user.id);
} else {
currentAdminUserId = null;
invitePanel.classList.add('hidden');
if (usersPanel) usersPanel.classList.add('hidden');
}
}
} else {
currentAdminUserId = null;
outEl.classList.add('hidden');
greet.classList.add('hidden');
if (invitePanel) invitePanel.classList.add('hidden');
@@ -197,7 +326,7 @@
}
}
async function refreshUsersList() {
async function refreshUsersList(viewerId) {
const usersList = document.getElementById('users-list');
if (!usersList) return;
usersList.textContent = 'Loading users...';
@@ -214,11 +343,54 @@
row.className = 'user-row';
const name = document.createElement('span');
name.textContent = `${user.username}${user.is_superuser ? ' (admin)' : ''}`;
const actions = document.createElement('div');
actions.className = 'user-actions';
const link = document.createElement('a');
link.href = `/editor?workspace_user_id=${encodeURIComponent(String(user.id))}`;
link.textContent = 'Open workspace';
const editBtn = document.createElement('button');
editBtn.type = 'button';
editBtn.className = 'btn btn-ghost';
editBtn.textContent = 'Edit';
editBtn.title = `Edit ${user.username}`;
editBtn.addEventListener('click', () => openUserEdit(user.id, user.username, user.is_superuser));
const delBtn = document.createElement('button');
delBtn.type = 'button';
delBtn.className = 'btn btn-ghost btn-danger';
delBtn.textContent = 'Remove';
const isSelf = Number(user.id) === Number(viewerId);
delBtn.disabled = isSelf;
delBtn.title = isSelf ? 'You cannot delete your own account here' : 'Permanently remove this user';
delBtn.addEventListener('click', async () => {
const ok = confirm(
`Remove user “${user.username}”? Their workspace folder stays on disk until you delete it manually.`
);
if (!ok) return;
delBtn.disabled = true;
setAdminUsersFeedback('', '');
try {
const dres = await fetch(`/api/users/${encodeURIComponent(String(user.id))}`, {
method: 'DELETE',
credentials: 'include'
});
const body = await dres.json().catch(() => ({}));
if (!dres.ok) {
setAdminUsersFeedback('err', formatApiDetail(body) || dres.statusText || 'Could not remove user');
delBtn.disabled = false;
return;
}
setAdminUsersFeedback('ok', `Removed ${user.username}.`);
await refreshUsersList(viewerId);
} catch (err) {
setAdminUsersFeedback('err', String(err.message || err));
delBtn.disabled = false;
}
});
actions.appendChild(editBtn);
actions.appendChild(link);
actions.appendChild(delBtn);
row.appendChild(name);
row.appendChild(link);
row.appendChild(actions);
usersList.appendChild(row);
}
} catch (_err) {
@@ -226,6 +398,65 @@
}
}
function closeUserEdit() {
const sheet = document.getElementById('user-edit-form');
if (sheet) sheet.classList.add('hidden');
}
function openUserEdit(userId, username, isSuperuser) {
document.getElementById('edit-user-id').value = String(userId);
document.getElementById('edit-user-username').value = username;
document.getElementById('edit-user-password').value = '';
document.getElementById('edit-user-super').checked = Boolean(isSuperuser);
document.getElementById('user-edit-heading').textContent = `Edit @${username}`;
document.getElementById('user-edit-form').classList.remove('hidden');
}
document.getElementById('edit-user-cancel').addEventListener('click', () => closeUserEdit());
document.getElementById('edit-user-save').addEventListener('click', async () => {
const id = document.getElementById('edit-user-id').value;
const u = document.getElementById('edit-user-username').value.trim();
const pw = document.getElementById('edit-user-password').value;
const superU = document.getElementById('edit-user-super').checked;
const saveBtn = document.getElementById('edit-user-save');
setAdminUsersFeedback('', '');
if (!u || u.length < 3) {
setAdminUsersFeedback('err', 'Username must be at least 3 characters.');
return;
}
const payload = { username: u, is_superuser: superU };
const tpw = pw.trim();
if (tpw.length > 0) {
if (tpw.length < 8) {
setAdminUsersFeedback('err', 'New password must be at least 8 characters (or leave blank).');
return;
}
payload.password = tpw;
}
saveBtn.disabled = true;
try {
const res = await fetch(`/api/users/${encodeURIComponent(String(id))}`, {
method: 'PATCH',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const body = await res.json().catch(() => ({}));
if (!res.ok) {
setAdminUsersFeedback('err', formatApiDetail(body) || res.statusText || 'Update failed');
saveBtn.disabled = false;
return;
}
setAdminUsersFeedback('ok', `Updated @${body.username}.`);
closeUserEdit();
await refreshUsersList(currentAdminUserId);
} catch (err) {
setAdminUsersFeedback('err', String(err.message || err));
}
saveBtn.disabled = false;
});
document.getElementById('btn-logout').addEventListener('click', async () => {
await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' });
window.location.reload();
@@ -253,11 +484,56 @@
} catch (_e) {}
});
function showInviteOutcome(inviteUrl, headline) {
const result = document.getElementById('invite-result');
const copyBtn = document.getElementById('invite-copy-btn');
result.textContent = '';
const line = document.createElement('p');
line.style.margin = '0 0 0.35rem 0';
line.textContent = headline;
const a = document.createElement('a');
a.href = inviteUrl;
a.textContent = inviteUrl;
a.style.color = '#93c5fd';
a.style.wordBreak = 'break-all';
result.appendChild(line);
result.appendChild(a);
copyBtn.classList.remove('hidden');
copyBtn.dataset.inviteUrl = inviteUrl;
}
function clearInviteOutcome() {
const result = document.getElementById('invite-result');
const copyBtn = document.getElementById('invite-copy-btn');
result.textContent = '';
copyBtn.classList.add('hidden');
copyBtn.textContent = 'Copy invite link';
delete copyBtn.dataset.inviteUrl;
}
document.getElementById('invite-copy-btn').addEventListener('click', async () => {
const copyBtn = document.getElementById('invite-copy-btn');
const url = copyBtn.dataset.inviteUrl;
if (!url) return;
try {
await navigator.clipboard.writeText(url);
copyBtn.textContent = 'Copied!';
setTimeout(() => {
copyBtn.textContent = 'Copy invite link';
}, 2000);
} catch (_e) {
copyBtn.textContent = 'Copy failed — select the link above';
setTimeout(() => {
copyBtn.textContent = 'Copy invite link';
}, 2500);
}
});
document.getElementById('invite-create-btn').addEventListener('click', async () => {
const emailInput = document.getElementById('invite-email');
const result = document.getElementById('invite-result');
const email = (emailInput.value || '').trim();
result.textContent = '';
clearInviteOutcome();
if (!email) {
result.textContent = 'Enter an email address first.';
return;
@@ -271,18 +547,20 @@
});
const body = await res.json().catch(() => ({}));
if (!res.ok) {
result.textContent = body.detail || res.statusText || 'Failed to create invite';
result.textContent = formatApiDetail(body) || res.statusText || 'Failed to create invite';
return;
}
const delivered = body.delivered ? 'Email sent.' : 'Email not sent (SMTP not configured), copy link manually.';
result.innerHTML = `${delivered}<br><a href="${body.invite_url}" style="color:#93c5fd">${body.invite_url}</a>`;
const headline = body.delivered
? 'Email sent. They can also use this link to register:'
: 'Email not sent (SMTP not configured). Share this registration link:';
showInviteOutcome(body.invite_url, headline);
} catch (err) {
result.textContent = String(err.message || err);
}
});
document.getElementById('invite-link-btn').addEventListener('click', async () => {
const result = document.getElementById('invite-result');
result.textContent = '';
clearInviteOutcome();
try {
const res = await fetch('/api/users/invites', {
method: 'POST',
@@ -292,10 +570,10 @@
});
const body = await res.json().catch(() => ({}));
if (!res.ok) {
result.textContent = body.detail || res.statusText || 'Failed to create invite link';
result.textContent = formatApiDetail(body) || res.statusText || 'Failed to create invite link';
return;
}
result.innerHTML = `Invite link created.<br><a href="${body.invite_url}" style="color:#93c5fd">${body.invite_url}</a>`;
showInviteOutcome(body.invite_url, 'Share this link so they can create an account:');
} catch (err) {
result.textContent = String(err.message || err);
}

View File

@@ -54,6 +54,7 @@
<body>
<main class="card">
<h1>Create account</h1>
<p id="invite-banner" class="hint hidden"></p>
<p class="hint">Username: letters, numbers, underscore (364). Password: at least 8 characters.</p>
<div id="err" class="err"></div>
<form id="form">
@@ -67,9 +68,31 @@
<p><a href="/login">Sign in</a> · <a href="/">Home</a></p>
</main>
<script>
const inviteToken = new URLSearchParams(window.location.search).get("invite") || "";
const inviteTokenRaw = new URLSearchParams(window.location.search).get("invite") || "";
const inviteToken = inviteTokenRaw.trim();
const inviteInput = document.getElementById("invite-token");
if (inviteInput) inviteInput.value = inviteToken;
if (inviteToken) {
const banner = document.getElementById("invite-banner");
if (banner) {
banner.classList.remove("hidden");
banner.textContent =
"You're using an invite link. Choose a username and password — the link works for one signup only.";
}
}
function formatApiDetail(body) {
if (!body || body.detail === undefined || body.detail === null) return "";
const d = body.detail;
if (typeof d === "string") return d;
if (Array.isArray(d))
return d
.map((item) =>
typeof item === "object" && item && item.msg ? String(item.msg) : JSON.stringify(item)
)
.join(" ");
return String(d);
}
(async function checkStatus() {
try {
@@ -98,7 +121,7 @@
const body = {
username: document.getElementById("username").value.trim(),
password: document.getElementById("password").value,
invite_token: inviteToken || null,
invite_token: inviteToken ? inviteToken : null,
};
const res = await fetch("/api/auth/register", {
method: "POST",
@@ -107,7 +130,7 @@
});
if (!res.ok) {
const j = await res.json().catch(() => ({}));
err.textContent = typeof j.detail === "string" ? j.detail : JSON.stringify(j.detail) || res.statusText;
err.textContent = formatApiDetail(j) || res.statusText;
return;
}
window.location.href = "/login?next=/editor";