Files
romm/backend/models/user.py
Georges-Antoine Assi 2d6a937d4a fix(auth): link an OIDC sign-in by email only when an admin or the provider set it
A first OIDC sign-in linked any account holding the same email and applied
the provider's role claim to it. Users choose their own email (profile edit,
invite registration), so one could take an address belonging to someone at
the provider and receive that identity and its role on their first sign-in.

Users gain an email_trusted flag: set when an admin creates the account or
saves its email, or when the provider writes it, and cleared when the user
or a delegated non-admin manager sets it. Email matching refuses an account
whose email is untrusted with a 403. Existing accounts are migrated as
trusted so pending first sign-ins keep working.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:37:54 -05:00

208 lines
8.0 KiB
Python

from __future__ import annotations
import enum
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, Final
from sqlalchemy import (
TIMESTAMP,
Boolean,
Enum,
ForeignKey,
Index,
Integer,
String,
false,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from starlette.authentication import SimpleUser
from config import OIDC_ENABLED
from handler.auth.constants import Scope
from models.base import BaseModel
from models.permission import PermissionGroup
from utils.database import CustomJSON, ExactString
from utils.datetime import older_than
if TYPE_CHECKING:
from models.assets import MemoryCard, Save, Screenshot, State
from models.client_token import ClientToken
from models.collection import Collection, SmartCollection
from models.device import Device
from models.music import MusicPlaylist
from models.play_session import PlaySession
from models.rom import RomNote, RomUser
class Role(enum.StrEnum):
# Two kinds only: admins bypass all permission checks; everyone else is a
# `user` whose access comes entirely from their permission group + overrides.
# (The old viewer/editor split was folded into groups.)
USER = "user"
ADMIN = "admin"
@classmethod
def coerce(cls, value: str | None) -> Role:
"""Map any role string to the two-value set. Only an exact ``admin``
becomes ADMIN; everything else (``user``, the legacy ``viewer`` /
``editor`` from in-flight invites, unknown, empty) collapses to USER."""
return cls.ADMIN if (value or "").strip().lower() == "admin" else cls.USER
TEXT_FIELD_LENGTH = 255
# Id of the synthetic, unauthenticated visitor KIOSK_MODE hands out. Negative so
# it can never collide with an auto-increment row.
KIOSK_USER_ID: Final = -1
class User(BaseModel, SimpleUser):
__tablename__ = "users"
__table_args__ = (
Index("ix_users_oidc_identity", "oidc_issuer", "oidc_sub", unique=True),
{"extend_existing": True},
)
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
username: Mapped[str] = mapped_column(
String(length=TEXT_FIELD_LENGTH), unique=True, index=True
)
hashed_password: Mapped[str | None] = mapped_column(
String(length=TEXT_FIELD_LENGTH)
)
email: Mapped[str | None] = mapped_column(
String(length=TEXT_FIELD_LENGTH), unique=True, index=True
)
# Set by an admin or the provider rather than chosen by the user, so a first
# OIDC sign-in may link the account by it.
email_trusted: Mapped[bool] = mapped_column(
Boolean, default=False, server_default=false()
)
# The provider's `iss` and `sub` claims: a stable identity that survives an
# email change. Exact, since a `sub` is case-sensitive.
oidc_issuer: Mapped[str | None] = mapped_column(ExactString(TEXT_FIELD_LENGTH))
oidc_sub: Mapped[str | None] = mapped_column(ExactString(TEXT_FIELD_LENGTH))
enabled: Mapped[bool] = mapped_column(default=True)
# VARCHAR-backed (native_enum=False) storing the lowercase value, so the
# vocabulary stays portable across SQLite/MariaDB/Postgres.
role: Mapped[Role] = mapped_column(
Enum(
Role,
native_enum=False,
length=20,
values_callable=lambda e: [m.value for m in e],
),
default=Role.USER,
)
# The granular permission group this user belongs to. NULL falls back to the
# server-wide default group in the resolver. Admins bypass groups entirely.
permission_group_id: Mapped[int | None] = mapped_column(
ForeignKey("permission_groups.id", ondelete="SET NULL"),
nullable=True,
index=True,
)
# Per-user replacements for the group's age limit settings; NULL inherits.
age_limit: Mapped[int | None] = mapped_column(Integer(), nullable=True)
hide_unrated_roms: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
avatar_path: Mapped[str] = mapped_column(
String(length=TEXT_FIELD_LENGTH), default=""
)
last_login: Mapped[datetime | None] = mapped_column(TIMESTAMP(timezone=True))
last_active: Mapped[datetime | None] = mapped_column(TIMESTAMP(timezone=True))
ra_username: Mapped[str | None] = mapped_column(
String(length=TEXT_FIELD_LENGTH), default=""
)
ra_progression: Mapped[dict[str, Any] | None] = mapped_column(
CustomJSON(), default=dict
)
ui_settings: Mapped[dict[str, Any] | None] = mapped_column(
CustomJSON(), default=dict
)
saves: Mapped[list[Save]] = relationship(lazy="raise", back_populates="user")
states: Mapped[list[State]] = relationship(lazy="raise", back_populates="user")
memory_cards: Mapped[list[MemoryCard]] = relationship(
lazy="raise", back_populates="user"
)
screenshots: Mapped[list[Screenshot]] = relationship(
lazy="raise", back_populates="user"
)
rom_users: Mapped[list[RomUser]] = relationship(lazy="raise", back_populates="user")
notes: Mapped[list[RomNote]] = relationship(lazy="raise", back_populates="user")
collections: Mapped[list[Collection]] = relationship(
lazy="raise", back_populates="user"
)
smart_collections: Mapped[list["SmartCollection"]] = relationship(
lazy="raise", back_populates="user"
)
music_playlists: Mapped[list["MusicPlaylist"]] = relationship(
lazy="raise", back_populates="user"
)
devices: Mapped[list["Device"]] = relationship(
lazy="raise", back_populates="user", cascade="all, delete-orphan"
)
client_tokens: Mapped[list["ClientToken"]] = relationship(
lazy="raise", back_populates="user", cascade="all, delete-orphan"
)
play_sessions: Mapped[list["PlaySession"]] = relationship(
lazy="raise", back_populates="user", cascade="all, delete-orphan"
)
# Loaded explicitly by the permission resolver; lazy="raise" keeps it off
# every other user query so the schema-wide query shape is unchanged.
permission_group: Mapped[PermissionGroup | None] = relationship(lazy="raise")
@classmethod
def kiosk_mode_user(cls) -> User:
now = datetime.now(timezone.utc)
return cls(
id=KIOSK_USER_ID,
username="kiosk",
role=Role.USER,
enabled=True,
avatar_path="",
last_active=now,
last_login=now,
created_at=now,
updated_at=now,
)
@property
def is_kiosk_guest(self) -> bool:
"""The shared anonymous visitor, not a real account."""
return self.id == KIOSK_USER_ID
@property
def oauth_scopes(self) -> list[Scope]:
# Derived from the granular permission model (groups + overrides),
# projected onto the legacy coarse scopes. Resolved per access via its
# own session; admins short-circuit without touching the DB.
# Local import: breaks the models.user <-> handler.auth.permissions cycle.
from handler.auth.permissions import compute_oauth_scopes
return compute_oauth_scopes(self)
@property
def has_password(self) -> bool:
"""Whether the account can sign in with a password: OIDC-provisioned
accounts hold a random placeholder instead of a bcrypt hash."""
return bool(self.hashed_password and self.hashed_password.startswith("$2"))
@property
def email_managed_by_oidc(self) -> bool:
"""Whether the provider owns the email: it overwrites a linked account's
at every sign-in, and finds an unlinked password-less account by it."""
return OIDC_ENABLED and (self.oidc_sub is not None or not self.has_password)
@property
def fs_safe_folder_name(self) -> str:
# Uses the ID to avoid issues with username changes
return f"User:{self.id}".encode().hex()
def set_last_active(self) -> None:
from handler.database import db_user_handler
from handler.database.users_handler import LAST_ACTIVE_DEBOUNCE
if older_than(self.last_active, LAST_ACTIVE_DEBOUNCE):
db_user_handler.update_last_active(self.id)