Files
romm/backend/models/user.py
Sam Dornan 9ee2e95bc9 feat(steam): import a user's Steam library
Users can link a Steam account (SteamID64, profile link or custom URL name)
and sync the games it owns. The sync links each owned game to the rom that
already stands for it on win, linux or mac, matched by Steam app id, and
gives the rest a store-only rom on win (created with its folder when the
library has none). Store-only roms have no file: `roms.storefront` marks
them and, like physical games, keeps them out of the missing-file sync,
the missing cleanup, the feeds and the exporters. Store-only roms that no
source has matched yet are queued for a rom-id scan after each sync.

- STEAM_API_KEY enables it; the heartbeat reports STEAM_LIBRARY_ENABLED.
- PUT/DELETE /api/users/{id}/steam link and unlink an account,
  POST /api/users/{id}/steam/sync queues the sync for one user.
- sync_steam_libraries syncs every linked user on a schedule
  (ENABLE_SCHEDULED_STEAM_LIBRARY_SYNC, SCHEDULED_STEAM_LIBRARY_SYNC_CRON).
- steam_library_entries holds each user's owned games with playtime and
  last played time; migration 0155 adds it, the user columns and
  roms.storefront.
- A rom-id scan no longer marks a physical or store-only rom missing.
- New store_only rom filter, part of HAS_FILE_ON_DISK_FILTERS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XGA3D2oZ1hq3QUdnubMNXh
2026-10-26 20:03:49 +00:00

198 lines
7.9 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
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
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
)
# 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
)
# A SteamID64 overflows JavaScript's safe integers, so it is kept as text.
steam_id: Mapped[str | None] = mapped_column(String(length=20), default=None)
steam_persona_name: Mapped[str | None] = mapped_column(
String(length=TEXT_FIELD_LENGTH), default=None
)
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
db_user_handler.update_user(
self.id, {"last_active": datetime.now(timezone.utc)}
)