Add registration toggle and password change; genericise deploy

Two things the running instance needed.

**Registration toggle.** Admin -> General, backed by a new settings table
group rather than the environment. LEMBAS_ALLOW_SIGNUP now seeds only the
initial value: once an administrator saves the setting, the stored value
wins. The alternative -- environment always winning -- means a toggle in
the UI silently reverts on the next restart, which is worse than not
offering one. Closing registration also removes the "Create one" link
from the sign-in page, so the link never leads somewhere that refuses.

**Password change**, on the user settings page. Changing a password
revokes every other session and immediately re-issues a cookie for the
current one: if the reason for the change is that somebody else knows
the password, leaving their session alive defeats the point, but signing
the user out of the tab they are standing in is merely rude.

**deploy/ is now host-agnostic.** This repository is public, so the unit
and vhost became templates with __PREFIX__ / __SITE_HOST__ / __APP_PORT__
substituted at install time, and every path, hostname and port moved to
environment variables. REPO_URL defaults to the checkout's own origin so
a fork deploys itself. Machine-specific values belong in private notes,
not here -- CLAUDE.md now says so.

83 tests, ruff clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jaroslav Beneš
2026-07-21 11:14:33 +02:00
parent dd9e0e9440
commit ba2fb1e13d
17 changed files with 727 additions and 153 deletions
+39 -2
View File
@@ -11,7 +11,8 @@ from sqlalchemy import func, select
from sqlalchemy.orm import Session as DBSession
from lembas.api.deps import AdminUser, Db
from lembas.db.models import Connection, Model
from lembas.db.models import Connection, Model, User
from lembas.services import settings_store
from lembas.services.crypto import decrypt, encrypt, mask
from lembas.services.llm.openai_client import Endpoint, LLMError, list_models
from lembas.web.templating import render
@@ -39,7 +40,43 @@ def _connections(db: DBSession) -> list[Connection]:
@router.get("")
async def admin_home(user: AdminUser):
return RedirectResponse("/admin/connections", status_code=status.HTTP_303_SEE_OTHER)
return RedirectResponse("/admin/general", status_code=status.HTTP_303_SEE_OTHER)
@router.get("/general")
async def general_page(request: Request, db: Db, user: AdminUser, saved: bool = False):
return render(
request,
"admin/general.html",
{
"values": settings_store.get_group(db),
"saved": saved,
"user_count": db.scalar(select(func.count()).select_from(User)),
},
)
@router.post("/general")
async def save_general(
db: Db,
user: AdminUser,
instance_name: str = Form("LLeMbas"),
allow_signup: bool = Form(False),
) -> Response:
"""Save instance settings.
Unchecked checkboxes are simply absent from a form post, which is why
allow_signup defaults to False here -- that absence *is* the "off" signal.
"""
settings_store.update(
db,
{
"instance_name": instance_name.strip()[:120] or "LLeMbas",
"allow_signup": allow_signup,
},
)
log.info("registration %s by %s", "opened" if allow_signup else "closed", user.email)
return RedirectResponse("/admin/general?saved=1", status_code=status.HTTP_303_SEE_OTHER)
@router.get("/connections")
+33 -17
View File
@@ -13,6 +13,7 @@ from lembas.config import settings
from lembas.db.models import ROLE_ADMIN, ROLE_USER, User
from lembas.security.passwords import hash_password, validate_password, verify_password
from lembas.security.sessions import COOKIE_NAME, create_session, revoke_session
from lembas.services import settings_store
from lembas.web.templating import render
log = logging.getLogger(__name__)
@@ -48,6 +49,19 @@ def _safe_next(raw: str | None) -> str:
return raw
def _login_page(request: Request, db: Db, *, status_code: int = 200, **context):
"""Render the sign-in page.
Always goes through here so `allow_signup` reflects the *stored* setting
rather than the environment default baked in by render(). Otherwise the
"Create one" link would keep appearing after an administrator closed
registration, offering a link that only leads to a refusal.
"""
context.setdefault("next", "/")
context["allow_signup"] = settings_store.signup_allowed(db)
return render(request, "auth/login.html", context, status_code=status_code)
@router.get("/login")
async def login_form(request: Request, db: Db, user: CurrentUser, next: str = "/"):
if user is not None:
@@ -57,7 +71,7 @@ async def login_form(request: Request, db: Db, user: CurrentUser, next: str = "/
# cannot possibly satisfy.
if _no_users_yet(db):
return RedirectResponse("/auth/register", status_code=status.HTTP_303_SEE_OTHER)
return render(request, "auth/login.html", {"next": _safe_next(next)})
return _login_page(request, db, next=_safe_next(next))
@router.post("/login")
@@ -75,21 +89,23 @@ async def login(
# cannot be used to discover which addresses are registered.
if user is None or not verify_password(password, user.password_hash):
log.info("failed sign-in for %s", email)
return render(
return _login_page(
request,
"auth/login.html",
{"error": "That email and password do not match.", "email": email,
"next": _safe_next(next)},
db,
status_code=status.HTTP_401_UNAUTHORIZED,
error="That email and password do not match.",
email=email,
next=_safe_next(next),
)
if not user.active:
return render(
return _login_page(
request,
"auth/login.html",
{"error": "This account has been deactivated. Ask an administrator.",
"email": email, "next": _safe_next(next)},
db,
status_code=status.HTTP_403_FORBIDDEN,
error="This account has been deactivated. Ask an administrator.",
email=email,
next=_safe_next(next),
)
token = create_session(
@@ -108,12 +124,12 @@ async def register_form(request: Request, db: Db, user: CurrentUser):
if user is not None:
return RedirectResponse("/", status_code=status.HTTP_303_SEE_OTHER)
first_run = _no_users_yet(db)
if not first_run and not settings.allow_signup:
return render(
if not first_run and not settings_store.signup_allowed(db):
return _login_page(
request,
"auth/login.html",
{"error": "Registration is closed. Ask an administrator for an account."},
db,
status_code=status.HTTP_403_FORBIDDEN,
error="Registration is closed. Ask an administrator for an account.",
)
return render(request, "auth/register.html", {"first_run": first_run})
@@ -127,12 +143,12 @@ async def register(
password: str = Form(...),
):
first_run = _no_users_yet(db)
if not first_run and not settings.allow_signup:
return render(
if not first_run and not settings_store.signup_allowed(db):
return _login_page(
request,
"auth/login.html",
{"error": "Registration is closed. Ask an administrator for an account."},
db,
status_code=status.HTTP_403_FORBIDDEN,
error="Registration is closed. Ask an administrator for an account.",
)
name = name.strip()
+11 -1
View File
@@ -97,13 +97,23 @@ async def chat_detail(request: Request, db: Db, user: RequiredUser, chat_id: str
@router.get("/settings")
async def settings_page(request: Request, db: Db, user: RequiredUser):
async def settings_page(
request: Request,
db: Db,
user: RequiredUser,
error: str = "",
saved: str = "",
):
# error/saved arrive as query parameters because the password form redirects
# back here: a POST that re-rendered in place would re-submit on refresh.
return render(
request,
"settings.html",
{
"chat": None,
"models": chat_service.available_models(db),
"error": error,
"saved": saved,
**_sidebar_context(db, user),
},
)
+74 -1
View File
@@ -2,9 +2,17 @@
from __future__ import annotations
from fastapi import APIRouter, Body
import logging
from fastapi import APIRouter, Body, Form, Request, status
from fastapi.responses import RedirectResponse, Response
from lembas.api.deps import Db, RequiredUser
from lembas.config import settings
from lembas.security.passwords import hash_password, validate_password, verify_password
from lembas.security.sessions import COOKIE_NAME, create_session, revoke_all_for_user
log = logging.getLogger(__name__)
router = APIRouter(prefix="/api/preferences", tags=["preferences"])
@@ -27,3 +35,68 @@ async def set_theme(db: Db, user: RequiredUser, theme: str = Body(..., embed=Tru
user.settings_json = {**(user.settings_json or {}), "theme": theme}
db.commit()
return {"ok": True, "theme": theme}
@router.post("/password")
async def change_password(
request: Request,
db: Db,
user: RequiredUser,
current_password: str = Form(...),
new_password: str = Form(...),
confirm_password: str = Form(...),
) -> Response:
"""Change your own password.
Every other session is revoked on success. If the reason for changing a
password is that someone else knows it, leaving their session alive would
defeat the point.
"""
def back(message: str, ok: bool = False) -> Response:
from urllib.parse import quote
field = "saved" if ok else "error"
return RedirectResponse(
f"/settings?{field}={quote(message)}", status_code=status.HTTP_303_SEE_OTHER
)
if not verify_password(current_password, user.password_hash):
log.info("failed password change for %s: current password wrong", user.email)
return back("Your current password is not correct.")
if new_password != confirm_password:
return back("The new passwords do not match.")
if (problem := validate_password(new_password)) is not None:
return back(problem)
if verify_password(new_password, user.password_hash):
return back("That is already your password.")
user.password_hash = hash_password(new_password)
db.commit()
revoke_all_for_user(db, user)
token = create_session(
db,
user,
user_agent=request.headers.get("user-agent", ""),
ip_address=request.client.host if request.client else "",
)
log.info("password changed for %s; other sessions revoked", user.email)
# revoke_all_for_user killed this session too, so hand back a fresh cookie
# -- otherwise changing your password would sign you out of the tab you are
# standing in.
response = back("Password changed. Any other sessions have been signed out.", ok=True)
response.set_cookie(
COOKIE_NAME,
token,
max_age=settings.session_ttl,
httponly=True,
samesite="lax",
secure=False,
path="/",
)
return response
+63
View File
@@ -0,0 +1,63 @@
"""Instance-wide settings that administrators can change at runtime.
Distinct from ``lembas.config``, which holds deployment configuration read from
the environment at startup. Anything here is editable from the admin UI and
lives in the ``settings`` table.
Environment variables act as the *initial* value only. Once an administrator
sets something in the UI, the stored value wins -- otherwise a toggle in the
interface would silently revert on the next restart, which is worse than not
offering the toggle at all.
"""
from __future__ import annotations
from typing import Any
from sqlalchemy.orm import Session as DBSession
from lembas.config import settings as env_settings
from lembas.db.models import Setting
GENERAL = "general"
def _defaults() -> dict[str, Any]:
return {
"allow_signup": env_settings.allow_signup,
# When on, new accounts land in the `pending` role and cannot sign in
# until an administrator approves them. Reserved for the users pass.
"require_approval": False,
"instance_name": "LLeMbas",
}
def get_group(db: DBSession, key: str = GENERAL) -> dict[str, Any]:
"""Stored settings for a group, with defaults filled in for absent keys."""
values = _defaults() if key == GENERAL else {}
row = db.get(Setting, key)
if row is not None and isinstance(row.value, dict):
values.update(row.value)
return values
def get(db: DBSession, name: str, *, key: str = GENERAL) -> Any:
return get_group(db, key).get(name)
def update(db: DBSession, changes: dict[str, Any], *, key: str = GENERAL) -> dict[str, Any]:
"""Merge changes into a settings group and persist them."""
row = db.get(Setting, key)
if row is None:
row = Setting(key=key, value={})
db.add(row)
# Reassigned rather than mutated: SQLAlchemy only reliably detects a change
# to a JSON column when the whole value is replaced.
row.value = {**(row.value or {}), **changes}
db.commit()
return get_group(db, key)
def signup_allowed(db: DBSession) -> bool:
return bool(get(db, "allow_signup"))
+5 -1
View File
@@ -22,6 +22,10 @@
<nav class="sidebar__scroll" aria-label="Administration">
<div class="nav-group">
<div class="nav-group__label">Administration</div>
<a class="nav-item {{ 'is-active' if section == 'general' }}" href="/admin/general">
{{ icon("gear", "icon--sm") }}
<span class="nav-item__label">General</span>
</a>
<a class="nav-item {{ 'is-active' if section == 'connections' }}"
href="/admin/connections">
{{ icon("server", "icon--sm") }}
@@ -40,7 +44,7 @@
<span class="nav-item__label">Users &amp; groups</span>
</span>
<span class="nav-item is-disabled">
{{ icon("gear", "icon--sm") }}
{{ icon("sliders", "icon--sm") }}
<span class="nav-item__label">Tools</span>
</span>
</div>
@@ -0,0 +1,74 @@
{% extends "admin/_layout.html" %}
{% from "_macros.html" import icon %}
{% set section = "general" %}
{% block title %}General - LLeMbas{% endblock %}
{% block heading %}General{% endblock %}
{% block admin_content %}
<p class="admin-lede">
Instance-wide settings. These are stored in the database and take effect
immediately — no restart, and they survive one.
</p>
{% if saved %}
<div class="alert alert--success">{{ icon("check", "icon--sm") }} <span>Settings saved.</span></div>
{% endif %}
<form method="post" action="/admin/general">
<section class="card">
<h2 class="card__title">Identity</h2>
<div class="field">
<label class="field__label" for="instance-name">Instance name</label>
<input class="input" id="instance-name" name="instance_name"
value="{{ values.instance_name }}" maxlength="120">
<p class="field__hint">Shown in the browser tab and on the sign-in page.</p>
</div>
</section>
<section class="card">
<h2 class="card__title">
Registration
{% if values.allow_signup %}
<span class="badge badge--success">open</span>
{% else %}
<span class="badge badge--danger">closed</span>
{% endif %}
</h2>
<div class="field">
<label class="checkbox">
<input type="checkbox" name="allow_signup" value="true"
{{ 'checked' if values.allow_signup }}>
<span>Anyone who can reach this instance may create an account</span>
</label>
<p class="field__hint">
Turn this off once your users exist. Sign-in is unaffected — existing
accounts keep working, and the "Create one" link disappears from the
sign-in page.
</p>
</div>
{% if values.allow_signup and user_count > 0 %}
<div class="alert alert--warning">
{{ icon("warning", "alert__icon") }}
<div>
<strong>Registration is open.</strong>
<div class="text-sm" style="margin-top: var(--sp-1)">
This instance has {{ user_count }} account{{ '' if user_count == 1 else 's' }}.
Anyone who can reach it can add another, and every account can use your
configured models and API keys.
</div>
</div>
</div>
{% endif %}
<p class="field__hint">
<code>LEMBAS_ALLOW_SIGNUP</code> in the environment sets only the starting
value. Once saved here, this setting wins.
</p>
</section>
<button class="btn btn--primary" type="submit">Save settings</button>
</form>
{% endblock %}
+39
View File
@@ -21,6 +21,17 @@
<div class="admin-scroll">
<div class="admin-page">
{% if error %}
<div class="alert alert--error" role="alert">
{{ icon("warning", "alert__icon") }} <span>{{ error }}</span>
</div>
{% endif %}
{% if saved %}
<div class="alert alert--success" role="status">
{{ icon("check", "icon--sm") }} <span>{{ saved }}</span>
</div>
{% endif %}
<section class="card">
<h2 class="card__title">Account</h2>
<div class="field">
@@ -55,6 +66,34 @@
</p>
</section>
<section class="card">
<h2 class="card__title">Change password</h2>
<form method="post" action="/api/preferences/password">
<div class="field">
<label class="field__label" for="current-password">Current password</label>
<input class="input" type="password" id="current-password"
name="current_password" required autocomplete="current-password">
</div>
<div class="field">
<label class="field__label" for="new-password">New password</label>
<input class="input" type="password" id="new-password" name="new_password"
required minlength="8" autocomplete="new-password">
<p class="field__hint">At least 8 characters.</p>
</div>
<div class="field">
<label class="field__label" for="confirm-password">Confirm new password</label>
<input class="input" type="password" id="confirm-password"
name="confirm_password" required minlength="8"
autocomplete="new-password">
</div>
<button class="btn btn--primary" type="submit">Change password</button>
<p class="field__hint" style="margin-top: var(--sp-3)">
Every other session is signed out when the password changes. You
stay signed in here.
</p>
</form>
</section>
<section class="card">
<h2 class="card__title">Session</h2>
<form method="post" action="/auth/logout">