1d3f6c450b
Four features, plus the schema machinery they needed. **Schema sync.** The first live instance had data in it, and create_all only creates missing *tables* -- a new column silently never appeared. db/migrations.py now diffs the declared models against the database and ALTER TABLE ... ADD COLUMN for what is missing, deriving a backfill default from the column type (SQLite refuses a NOT NULL column without one, and a Python-side `default=dict` cannot be expressed in DDL). Verified against a copy of the live database: eight changes applied, all rows preserved, second run a no-op. Renames, drops and retypes are still manual and say so. **Permissions.** A flat set of named booleans: an instance baseline widened by each group the user belongs to. A group grants and never denies -- with denies, "why can this user not do X" cannot be answered without simulating every group. Admins bypass entirely, because an admin can grant it back to themselves in two clicks and pretending otherwise is theatre. Model *access* is separate: public, or granted to groups. The picker is not the boundary -- switching a chat to a model you cannot reach is a 403. **Model settings.** Ordering, pinned-first, an instance default and a per-user default, display names, descriptions, capability flags, and uploaded images. Images are stored and served locally rather than by URL: a remote URL makes every page render a request to a third party. Uploads are validated by magic number, not the declared content type, and stored under a random name. Models with no image get a generated initial whose hue is derived from the model id, so it is stable. **Reasoning display.** Streams into its own collapsible block above the answer, labelled "Thought for 14 seconds", collapsed once finished, and never replayed as context on the next turn. Two sources: the reasoning_content delta field, and <think> tags inline in content -- the latter needs a streaming splitter because the tags arrive split across chunks. Models emitting no reasoning show nothing, via a :has() rule rather than JavaScript. Verified against qwen35-9b on llama-swap: 694 reasoning events, 52 answer tokens, cleanly separated. Two bugs found and fixed while testing: - A bare `Mapped[list]` relationship is treated by SQLAlchemy as a scalar and returns None instead of []. It needs the element type. - FastAPI substitutes the default for an empty form value, so with `x: str | None = Form(None)` a submitted `x=` is indistinguishable from an absent field. That silently broke clearing a system prompt or a temperature. update_chat now reads the raw form and checks key presence. 143 tests, ruff clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
101 lines
3.9 KiB
Python
101 lines
3.9 KiB
Python
"""Users, groups and login sessions."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
from typing import TYPE_CHECKING, Any
|
|
|
|
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Index, String, Table, Text
|
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|
|
|
from lembas.db.base import Base, Timestamps, UUIDPrimaryKey
|
|
from lembas.db.types import JSONDict
|
|
|
|
if TYPE_CHECKING:
|
|
# Annotation only; SQLAlchemy resolves the real class from its registry.
|
|
from lembas.db.models.connection import Model
|
|
|
|
# Roles are a simple ordered ladder rather than a permission matrix. Groups
|
|
# (below) carry finer-grained permissions once the users/groups UI lands.
|
|
ROLE_ADMIN = "admin"
|
|
ROLE_USER = "user"
|
|
ROLE_PENDING = "pending" # registered but awaiting admin approval
|
|
|
|
user_groups = Table(
|
|
"user_groups",
|
|
Base.metadata,
|
|
Column("user_id", String(32), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True),
|
|
Column("group_id", String(32), ForeignKey("groups.id", ondelete="CASCADE"), primary_key=True),
|
|
)
|
|
|
|
|
|
class User(UUIDPrimaryKey, Timestamps, Base):
|
|
__tablename__ = "users"
|
|
|
|
email: Mapped[str] = mapped_column(String(320), unique=True, nullable=False, index=True)
|
|
name: Mapped[str] = mapped_column(String(120), nullable=False)
|
|
password_hash: Mapped[str] = mapped_column(Text, nullable=False)
|
|
role: Mapped[str] = mapped_column(String(16), default=ROLE_USER, nullable=False)
|
|
active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
|
last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
|
|
|
# Per-user preferences: theme, default model, composer behaviour, etc.
|
|
settings_json: Mapped[dict[str, Any]] = mapped_column(JSONDict, default=dict)
|
|
|
|
groups: Mapped[list[Group]] = relationship(secondary=user_groups, back_populates="users")
|
|
sessions: Mapped[list[Session]] = relationship(
|
|
back_populates="user", cascade="all, delete-orphan"
|
|
)
|
|
|
|
@property
|
|
def is_admin(self) -> bool:
|
|
return self.role == ROLE_ADMIN
|
|
|
|
def __repr__(self) -> str:
|
|
return f"<User {self.email} role={self.role}>"
|
|
|
|
|
|
class Group(UUIDPrimaryKey, Timestamps, Base):
|
|
"""A named set of users. Permissions are enforced once the RBAC pass lands."""
|
|
|
|
__tablename__ = "groups"
|
|
|
|
name: Mapped[str] = mapped_column(String(120), unique=True, nullable=False)
|
|
description: Mapped[str] = mapped_column(Text, default="")
|
|
|
|
# Only the granted keys need be present. Absent means "no opinion", not
|
|
# "deny" -- permissions union across a user's groups. See
|
|
# lembas.security.permissions.
|
|
permissions_json: Mapped[dict[str, Any]] = mapped_column(JSONDict, default=dict)
|
|
|
|
users: Mapped[list[User]] = relationship(secondary=user_groups, back_populates="groups")
|
|
models: Mapped[list[Model]] = relationship(
|
|
"Model", secondary="model_groups", back_populates="groups"
|
|
)
|
|
|
|
|
|
class Session(UUIDPrimaryKey, Timestamps, Base):
|
|
"""Server-side login session.
|
|
|
|
Sessions live in the database rather than in a signed JWT so that logging
|
|
out, banning a user, or rotating a device actually revokes access
|
|
immediately instead of waiting for a token to expire.
|
|
"""
|
|
|
|
__tablename__ = "sessions"
|
|
|
|
user_id: Mapped[str] = mapped_column(
|
|
String(32), ForeignKey("users.id", ondelete="CASCADE"), nullable=False
|
|
)
|
|
# SHA-256 of the cookie value. The raw token is shown to the browser once
|
|
# and never stored, so a database leak does not hand over live sessions.
|
|
token_hash: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
|
|
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
|
user_agent: Mapped[str] = mapped_column(Text, default="")
|
|
ip_address: Mapped[str] = mapped_column(String(45), default="")
|
|
|
|
user: Mapped[User] = relationship(back_populates="sessions")
|
|
|
|
|
|
Index("ix_sessions_user_id", Session.user_id)
|