mirror of
https://github.com/rommapp/romm.git
synced 2026-12-03 02:24:09 +01:00
Merge pull request #3605 from rommapp/chore/permissions-system-rework
feat: granular permission system (groups, overrides, per-entity hiding)
This commit is contained in:
366
backend/alembic/versions/0092_permission_system.py
Normal file
366
backend/alembic/versions/0092_permission_system.py
Normal file
@@ -0,0 +1,366 @@
|
||||
"""Granular permission system: groups, grants, overrides, hidden entities, and
|
||||
the narrowing of the user role vocabulary to admin/user.
|
||||
|
||||
Single migration for the whole permissions feature. Backfills so that NO user
|
||||
gains or loses access on upgrade:
|
||||
|
||||
* "Viewer (legacy)" group reproduces the old non-kiosk default user
|
||||
(WRITE_SCOPES): read the library, manage only own collections/assets/devices.
|
||||
* "Editor (legacy)" group reproduces EDIT_SCOPES: viewer + library-wide write
|
||||
AND delete of roms/platforms/firmware (today's deletes gate on *_WRITE, so
|
||||
editors can already delete -- preserved here as explicit delete grants).
|
||||
* Existing users are assigned to the matching group by their current role.
|
||||
Admins are left unassigned (they bypass groups entirely).
|
||||
* The `role` column is then narrowed from the viewer/editor/admin enum to a
|
||||
portable VARCHAR holding just `admin`/`user` (the viewer/editor distinction
|
||||
now lives entirely in permission groups). The group assignment above MUST
|
||||
happen before this, since it reads the old VIEWER/EDITOR values.
|
||||
|
||||
The seeded grant matrix is the frozen twin of ``handler/auth/permissions_map.py``;
|
||||
``tests/handler/auth/test_permissions_parity.py`` keeps the two in lockstep.
|
||||
|
||||
Revision ID: 0092_permission_system
|
||||
Revises: 0091_unique_platform_fs_name
|
||||
Create Date: 2026-06-22 00:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects.postgresql import ENUM as PostgresEnum
|
||||
|
||||
from utils.database import is_postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0092_permission_system"
|
||||
down_revision = "0091_unique_platform_fs_name"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
# (entity, action, own_only) -- frozen snapshot, mirrors permissions_map.py.
|
||||
VIEWER_GRANTS = [
|
||||
("roms", "read", False),
|
||||
("platforms", "read", False),
|
||||
("firmware", "read", False),
|
||||
("collections", "read", False),
|
||||
("collections", "write", True),
|
||||
("collections", "delete", True),
|
||||
("assets", "read", False),
|
||||
("assets", "write", True),
|
||||
("assets", "delete", True),
|
||||
("devices", "read", True),
|
||||
("devices", "write", True),
|
||||
("devices", "delete", True),
|
||||
]
|
||||
EDITOR_EXTRA = [
|
||||
("roms", "write", False),
|
||||
("roms", "delete", False),
|
||||
("platforms", "write", False),
|
||||
("platforms", "delete", False),
|
||||
("firmware", "write", False),
|
||||
("firmware", "delete", False),
|
||||
]
|
||||
EDITOR_GRANTS = VIEWER_GRANTS + EDITOR_EXTRA
|
||||
|
||||
# Legacy-group colours echoing the old role tones (viewer -> blue,
|
||||
# editor -> amber) so they look intentional out of the box.
|
||||
VIEWER_COLOR = "#3b82f6"
|
||||
EDITOR_COLOR = "#f59e0b"
|
||||
|
||||
# The pre-narrowing role enum, used by the role alter_column in both directions.
|
||||
_ROLE_ENUM = sa.Enum("VIEWER", "EDITOR", "ADMIN", name="role")
|
||||
|
||||
|
||||
def _timestamp_cols() -> tuple[sa.Column, sa.Column]:
|
||||
# Fresh Column objects per call: a Column instance can only belong to one
|
||||
# table, so the four create_table calls each need their own pair.
|
||||
return (
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.TIMESTAMP(timezone=True),
|
||||
nullable=False,
|
||||
server_default=sa.text("CURRENT_TIMESTAMP"),
|
||||
),
|
||||
sa.Column(
|
||||
"updated_at",
|
||||
sa.TIMESTAMP(timezone=True),
|
||||
nullable=False,
|
||||
server_default=sa.text("CURRENT_TIMESTAMP"),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"permission_groups",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("name", sa.String(length=255), nullable=False),
|
||||
sa.Column(
|
||||
"description",
|
||||
sa.String(length=1000),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
sa.Column(
|
||||
"is_default",
|
||||
sa.Boolean(),
|
||||
nullable=False,
|
||||
server_default=sa.text("false"),
|
||||
),
|
||||
sa.Column(
|
||||
"is_system",
|
||||
sa.Boolean(),
|
||||
nullable=False,
|
||||
server_default=sa.text("false"),
|
||||
),
|
||||
sa.Column("color", sa.String(length=9), nullable=True),
|
||||
*_timestamp_cols(),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
if_not_exists=True,
|
||||
)
|
||||
with op.batch_alter_table("permission_groups") as batch_op:
|
||||
batch_op.create_index(
|
||||
"ix_permission_groups_name", ["name"], unique=True, if_not_exists=True
|
||||
)
|
||||
batch_op.create_index(
|
||||
"ix_permission_groups_is_default", ["is_default"], if_not_exists=True
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
"permission_group_grants",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("group_id", sa.Integer(), nullable=False),
|
||||
sa.Column("entity", sa.String(length=20), nullable=False),
|
||||
sa.Column("action", sa.String(length=10), nullable=False),
|
||||
sa.Column(
|
||||
"own_only", sa.Boolean(), nullable=False, server_default=sa.text("false")
|
||||
),
|
||||
*_timestamp_cols(),
|
||||
sa.ForeignKeyConstraint(
|
||||
["group_id"], ["permission_groups.id"], ondelete="CASCADE"
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("group_id", "entity", "action", name="uq_group_grant"),
|
||||
if_not_exists=True,
|
||||
)
|
||||
with op.batch_alter_table("permission_group_grants") as batch_op:
|
||||
batch_op.create_index(
|
||||
"ix_permission_group_grants_group_id", ["group_id"], if_not_exists=True
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
"user_permission_overrides",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("entity", sa.String(length=20), nullable=False),
|
||||
sa.Column("action", sa.String(length=10), nullable=False),
|
||||
sa.Column("granted", sa.Boolean(), nullable=False),
|
||||
sa.Column(
|
||||
"own_only", sa.Boolean(), nullable=False, server_default=sa.text("false")
|
||||
),
|
||||
*_timestamp_cols(),
|
||||
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("user_id", "entity", "action", name="uq_user_override"),
|
||||
if_not_exists=True,
|
||||
)
|
||||
with op.batch_alter_table("user_permission_overrides") as batch_op:
|
||||
batch_op.create_index(
|
||||
"ix_user_permission_overrides_user_id", ["user_id"], if_not_exists=True
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
"hidden_entities",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("entity", sa.String(length=20), nullable=False),
|
||||
sa.Column("entity_id", sa.Integer(), nullable=False),
|
||||
sa.Column("user_id", sa.Integer(), nullable=True),
|
||||
sa.Column("group_id", sa.Integer(), nullable=True),
|
||||
*_timestamp_cols(),
|
||||
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
|
||||
sa.ForeignKeyConstraint(
|
||||
["group_id"], ["permission_groups.id"], ondelete="CASCADE"
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint(
|
||||
"entity", "entity_id", "user_id", "group_id", name="uq_hidden_entity"
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"(user_id IS NULL) <> (group_id IS NULL)",
|
||||
name="ck_hidden_one_principal",
|
||||
),
|
||||
if_not_exists=True,
|
||||
)
|
||||
with op.batch_alter_table("hidden_entities") as batch_op:
|
||||
batch_op.create_index(
|
||||
"ix_hidden_entities_entity_id", ["entity_id"], if_not_exists=True
|
||||
)
|
||||
batch_op.create_index(
|
||||
"ix_hidden_entities_user_id", ["user_id"], if_not_exists=True
|
||||
)
|
||||
batch_op.create_index(
|
||||
"ix_hidden_entities_group_id", ["group_id"], if_not_exists=True
|
||||
)
|
||||
batch_op.create_index(
|
||||
"idx_hidden_user_lookup", ["user_id", "entity"], if_not_exists=True
|
||||
)
|
||||
batch_op.create_index(
|
||||
"idx_hidden_group_lookup", ["group_id", "entity"], if_not_exists=True
|
||||
)
|
||||
|
||||
with op.batch_alter_table("users") as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column("permission_group_id", sa.Integer(), nullable=True),
|
||||
if_not_exists=True,
|
||||
)
|
||||
batch_op.create_foreign_key(
|
||||
"fk_users_permission_group_id",
|
||||
"permission_groups",
|
||||
["permission_group_id"],
|
||||
["id"],
|
||||
ondelete="SET NULL",
|
||||
)
|
||||
batch_op.create_index(
|
||||
"ix_users_permission_group_id",
|
||||
["permission_group_id"],
|
||||
if_not_exists=True,
|
||||
)
|
||||
|
||||
# Seed + assign by current role while `role` still holds VIEWER/EDITOR/ADMIN.
|
||||
_seed_legacy_groups()
|
||||
|
||||
# Now collapse the role vocabulary to the two-value lowercase set. Convert
|
||||
# the native enum to a portable VARCHAR first, then normalize the values.
|
||||
# On Postgres the cast needs an explicit USING and the orphaned enum type
|
||||
# must be dropped so a later downgrade can recreate it cleanly.
|
||||
connection = op.get_bind()
|
||||
with op.batch_alter_table("users") as batch_op:
|
||||
batch_op.alter_column(
|
||||
"role",
|
||||
existing_type=_ROLE_ENUM,
|
||||
type_=sa.String(length=20),
|
||||
existing_nullable=False,
|
||||
postgresql_using="role::text",
|
||||
)
|
||||
op.execute("UPDATE users SET role = 'admin' WHERE UPPER(role) = 'ADMIN'")
|
||||
op.execute(
|
||||
"UPDATE users SET role = 'user' "
|
||||
"WHERE UPPER(role) IN ('VIEWER', 'EDITOR', 'USER') OR role IS NULL"
|
||||
)
|
||||
if is_postgresql(connection):
|
||||
PostgresEnum(name="role").drop(connection, checkfirst=True)
|
||||
|
||||
|
||||
def _seed_legacy_groups() -> None:
|
||||
conn = op.get_bind()
|
||||
|
||||
groups_t = sa.table(
|
||||
"permission_groups",
|
||||
sa.column("id", sa.Integer),
|
||||
sa.column("name", sa.String),
|
||||
sa.column("description", sa.String),
|
||||
sa.column("is_default", sa.Boolean),
|
||||
sa.column("is_system", sa.Boolean),
|
||||
sa.column("color", sa.String),
|
||||
)
|
||||
grants_t = sa.table(
|
||||
"permission_group_grants",
|
||||
sa.column("group_id", sa.Integer),
|
||||
sa.column("entity", sa.String),
|
||||
sa.column("action", sa.String),
|
||||
sa.column("own_only", sa.Boolean),
|
||||
)
|
||||
|
||||
conn.execute(
|
||||
groups_t.insert(),
|
||||
[
|
||||
{
|
||||
"name": "Viewer (legacy)",
|
||||
"description": (
|
||||
"Read the library; manage only your own collections, "
|
||||
"assets and devices. Reproduces the pre-upgrade default user."
|
||||
),
|
||||
"is_default": True,
|
||||
"is_system": True,
|
||||
"color": VIEWER_COLOR,
|
||||
},
|
||||
{
|
||||
"name": "Editor (legacy)",
|
||||
"description": (
|
||||
"Viewer access plus library-wide create/edit/delete of "
|
||||
"roms, platforms and firmware. Reproduces the pre-upgrade "
|
||||
"editor role."
|
||||
),
|
||||
"is_default": False,
|
||||
"is_system": True,
|
||||
"color": EDITOR_COLOR,
|
||||
},
|
||||
],
|
||||
)
|
||||
|
||||
name_to_id = {
|
||||
name: gid
|
||||
for gid, name in conn.execute(
|
||||
sa.select(groups_t.c.id, groups_t.c.name).where(
|
||||
groups_t.c.name.in_(["Viewer (legacy)", "Editor (legacy)"])
|
||||
)
|
||||
).all()
|
||||
}
|
||||
viewer_id = name_to_id["Viewer (legacy)"]
|
||||
editor_id = name_to_id["Editor (legacy)"]
|
||||
|
||||
grant_rows = [
|
||||
{"group_id": viewer_id, "entity": e, "action": a, "own_only": o}
|
||||
for (e, a, o) in VIEWER_GRANTS
|
||||
] + [
|
||||
{"group_id": editor_id, "entity": e, "action": a, "own_only": o}
|
||||
for (e, a, o) in EDITOR_GRANTS
|
||||
]
|
||||
conn.execute(grants_t.insert(), grant_rows)
|
||||
|
||||
# Assign existing users to the group matching their current role. Admins are
|
||||
# intentionally left NULL: they bypass the group system.
|
||||
conn.execute(
|
||||
sa.text("UPDATE users SET permission_group_id = :gid WHERE role = 'EDITOR'"),
|
||||
{"gid": editor_id},
|
||||
)
|
||||
conn.execute(
|
||||
sa.text("UPDATE users SET permission_group_id = :gid WHERE role = 'VIEWER'"),
|
||||
{"gid": viewer_id},
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Restore the role enum (reverse of the narrowing) before tearing down the
|
||||
# permission infrastructure. Values are restored while still VARCHAR.
|
||||
connection = op.get_bind()
|
||||
op.execute("UPDATE users SET role = 'VIEWER' WHERE LOWER(role) = 'user'")
|
||||
op.execute("UPDATE users SET role = 'ADMIN' WHERE LOWER(role) = 'admin'")
|
||||
# On Postgres the native enum type was dropped on upgrade; recreate it
|
||||
# explicitly (create_type=False keeps the alter from re-issuing CREATE TYPE)
|
||||
# and cast the column back with an explicit USING.
|
||||
role_type: sa.Enum = _ROLE_ENUM
|
||||
if is_postgresql(connection):
|
||||
role_type = PostgresEnum(
|
||||
"VIEWER", "EDITOR", "ADMIN", name="role", create_type=False
|
||||
)
|
||||
role_type.create(connection, checkfirst=True)
|
||||
with op.batch_alter_table("users") as batch_op:
|
||||
batch_op.alter_column(
|
||||
"role",
|
||||
existing_type=sa.String(length=20),
|
||||
type_=role_type,
|
||||
existing_nullable=False,
|
||||
postgresql_using="role::role",
|
||||
)
|
||||
|
||||
with op.batch_alter_table("users") as batch_op:
|
||||
batch_op.drop_constraint("fk_users_permission_group_id", type_="foreignkey")
|
||||
batch_op.drop_index("ix_users_permission_group_id", if_exists=True)
|
||||
batch_op.drop_column("permission_group_id", if_exists=True)
|
||||
|
||||
op.drop_table("hidden_entities", if_exists=True)
|
||||
op.drop_table("user_permission_overrides", if_exists=True)
|
||||
op.drop_table("permission_group_grants", if_exists=True)
|
||||
op.drop_table("permission_groups", if_exists=True)
|
||||
@@ -7,6 +7,7 @@ from decorators.auth import protected_route
|
||||
from endpoints.responses.activity import ActivityClearSchema, ActivityEntrySchema
|
||||
from handler.activity_handler import ActivityEntry, activity_handler
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import get_permissions
|
||||
from handler.database import db_device_handler, db_rom_handler, db_save_handler
|
||||
from handler.socket_handler import socket_handler
|
||||
from logger.logger import log
|
||||
@@ -19,6 +20,22 @@ router = APIRouter(
|
||||
)
|
||||
|
||||
|
||||
def _visible_activity(
|
||||
request: Request, entries: list[ActivityEntry]
|
||||
) -> list[ActivityEntrySchema]:
|
||||
"""Drop sessions whose ROM is hidden from the caller (platform or rom hide)."""
|
||||
perms = get_permissions(request)
|
||||
if not perms.is_admin and (perms.hidden_platform_ids or perms.hidden_rom_ids):
|
||||
rom_ids = [e["rom_id"] for e in entries]
|
||||
hidden = db_rom_handler.get_hidden_rom_ids_among(
|
||||
rom_ids,
|
||||
list(perms.hidden_platform_ids),
|
||||
list(perms.hidden_rom_ids),
|
||||
)
|
||||
entries = [e for e in entries if e["rom_id"] not in hidden]
|
||||
return [ActivityEntrySchema(**e) for e in entries]
|
||||
|
||||
|
||||
class DeviceHeartbeatPayload(BaseModel):
|
||||
rom_id: int = Field(ge=1)
|
||||
device_id: str = Field(min_length=1, max_length=255)
|
||||
@@ -28,14 +45,14 @@ class DeviceHeartbeatPayload(BaseModel):
|
||||
async def get_all_activity(request: Request) -> list[ActivityEntrySchema]:
|
||||
"""Return every currently active play session across all users."""
|
||||
entries = await activity_handler.get_all_active()
|
||||
return [ActivityEntrySchema(**e) for e in entries]
|
||||
return _visible_activity(request, entries)
|
||||
|
||||
|
||||
@protected_route(router.get, "/rom/{rom_id}", [Scope.ROMS_USER_READ])
|
||||
async def get_rom_activity(request: Request, rom_id: int) -> list[ActivityEntrySchema]:
|
||||
"""Return all active play sessions for a specific ROM."""
|
||||
entries = await activity_handler.get_active_for_rom(rom_id)
|
||||
return [ActivityEntrySchema(**e) for e in entries]
|
||||
return _visible_activity(request, entries)
|
||||
|
||||
|
||||
@protected_route(router.post, "/heartbeat", [Scope.ROMS_USER_WRITE])
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import json
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
from typing import Annotated
|
||||
from typing import Annotated, TypeVar
|
||||
|
||||
from fastapi import File, Form, HTTPException
|
||||
from fastapi import Path as PathVar
|
||||
@@ -20,7 +20,8 @@ from exceptions.endpoint_exceptions import (
|
||||
CollectionPermissionError,
|
||||
)
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database import db_collection_handler
|
||||
from handler.auth.dependencies import get_permissions
|
||||
from handler.database import db_collection_handler, db_rom_handler
|
||||
from handler.filesystem import fs_resource_handler
|
||||
from handler.filesystem.assets_handler import validate_image_upload
|
||||
from handler.filesystem.base_handler import CoverSize
|
||||
@@ -42,6 +43,43 @@ router = APIRouter(
|
||||
|
||||
COLLECTION_ARTWORK_FILE = File(default=None, description="Collection artwork file.")
|
||||
|
||||
CollectionSchemaT = TypeVar(
|
||||
"CollectionSchemaT",
|
||||
CollectionSchema,
|
||||
VirtualCollectionSchema,
|
||||
SmartCollectionSchema,
|
||||
)
|
||||
|
||||
|
||||
def _hide_collection_roms(
|
||||
schemas: list[CollectionSchemaT], request: Request
|
||||
) -> list[CollectionSchemaT]:
|
||||
"""Drop hidden roms from each collection's `rom_ids`/`rom_count` for the caller.
|
||||
|
||||
Without this a collection leaks the ids (and inflated count) of roms hidden
|
||||
from the user via the opt-out visibility model.
|
||||
"""
|
||||
if not request.user.is_authenticated or not schemas:
|
||||
return schemas
|
||||
perms = get_permissions(request)
|
||||
if perms.is_admin or (not perms.hidden_platform_ids and not perms.hidden_rom_ids):
|
||||
return schemas
|
||||
|
||||
all_ids = {rid for s in schemas for rid in s.rom_ids}
|
||||
hidden = db_rom_handler.get_hidden_rom_ids_among(
|
||||
list(all_ids),
|
||||
list(perms.hidden_platform_ids),
|
||||
list(perms.hidden_rom_ids),
|
||||
)
|
||||
if not hidden:
|
||||
return schemas
|
||||
for s in schemas:
|
||||
visible = set(s.rom_ids) - hidden
|
||||
if len(visible) != len(s.rom_ids):
|
||||
s.rom_ids = visible
|
||||
s.rom_count = len(visible)
|
||||
return schemas
|
||||
|
||||
|
||||
@protected_route(router.post, "", [Scope.COLLECTIONS_WRITE])
|
||||
async def add_collection(
|
||||
@@ -191,7 +229,9 @@ def get_collections(
|
||||
|
||||
collections = db_collection_handler.get_collections(updated_after=updated_after)
|
||||
|
||||
return CollectionSchema.for_user(request.user.id, collections)
|
||||
return _hide_collection_roms(
|
||||
CollectionSchema.for_user(request.user.id, collections), request
|
||||
)
|
||||
|
||||
|
||||
@protected_route(router.get, "/identifiers", [Scope.COLLECTIONS_READ])
|
||||
@@ -238,7 +278,10 @@ def get_virtual_collections(
|
||||
type=type, limit=limit
|
||||
)
|
||||
|
||||
return [VirtualCollectionSchema.model_validate(vc) for vc in virtual_collections]
|
||||
return _hide_collection_roms(
|
||||
[VirtualCollectionSchema.model_validate(vc) for vc in virtual_collections],
|
||||
request,
|
||||
)
|
||||
|
||||
|
||||
@protected_route(router.get, "/virtual/identifiers", [Scope.COLLECTIONS_READ])
|
||||
@@ -286,7 +329,9 @@ def get_smart_collections(
|
||||
request.user.id, updated_after=updated_after
|
||||
)
|
||||
|
||||
return SmartCollectionSchema.for_user(request.user.id, smart_collections)
|
||||
return _hide_collection_roms(
|
||||
SmartCollectionSchema.for_user(request.user.id, smart_collections), request
|
||||
)
|
||||
|
||||
|
||||
@protected_route(router.get, "/smart/identifiers", [Scope.COLLECTIONS_READ])
|
||||
@@ -329,7 +374,9 @@ def get_collection(request: Request, id: int) -> CollectionSchema:
|
||||
if collection.user_id != request.user.id and not collection.is_public:
|
||||
raise CollectionPermissionError(id)
|
||||
|
||||
return CollectionSchema.model_validate(collection)
|
||||
return _hide_collection_roms(
|
||||
[CollectionSchema.model_validate(collection)], request
|
||||
)[0]
|
||||
|
||||
|
||||
@protected_route(router.get, "/virtual/{id}", [Scope.COLLECTIONS_READ])
|
||||
@@ -348,7 +395,9 @@ def get_virtual_collection(request: Request, id: str) -> VirtualCollectionSchema
|
||||
if not virtual_collection:
|
||||
raise CollectionNotFoundInDatabaseException(id)
|
||||
|
||||
return VirtualCollectionSchema.model_validate(virtual_collection)
|
||||
return _hide_collection_roms(
|
||||
[VirtualCollectionSchema.model_validate(virtual_collection)], request
|
||||
)[0]
|
||||
|
||||
|
||||
@protected_route(router.get, "/smart/{id}", [Scope.COLLECTIONS_READ])
|
||||
@@ -370,7 +419,9 @@ def get_smart_collection(request: Request, id: int) -> SmartCollectionSchema:
|
||||
if smart_collection.user_id != request.user.id and not smart_collection.is_public:
|
||||
raise CollectionPermissionError(id)
|
||||
|
||||
return SmartCollectionSchema.model_validate(smart_collection)
|
||||
return _hide_collection_roms(
|
||||
[SmartCollectionSchema.model_validate(smart_collection)], request
|
||||
)[0]
|
||||
|
||||
|
||||
@protected_route(router.put, "/{id}", [Scope.COLLECTIONS_WRITE])
|
||||
|
||||
@@ -38,6 +38,7 @@ from endpoints.responses.feeds import (
|
||||
WebrcadeFeedSchema,
|
||||
)
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import get_permissions
|
||||
from handler.database import db_platform_handler, db_rom_handler
|
||||
from handler.filesystem import fs_rom_handler
|
||||
from handler.metadata import meta_igdb_handler
|
||||
@@ -78,6 +79,30 @@ router = APIRouter(
|
||||
)
|
||||
|
||||
|
||||
def _hidden_ids(request: Request) -> tuple[list[int], list[int]]:
|
||||
"""Hidden (platform_ids, rom_ids) for the caller; empty when unauthenticated.
|
||||
|
||||
Feeds run unauthenticated under DISABLE_DOWNLOAD_ENDPOINT_AUTH, so there is
|
||||
no caller to scope visibility to in that mode.
|
||||
"""
|
||||
if not request.user.is_authenticated:
|
||||
return [], []
|
||||
perms = get_permissions(request)
|
||||
return list(perms.hidden_platform_ids), list(perms.hidden_rom_ids)
|
||||
|
||||
|
||||
def _platform_roms(request: Request, platform_id: int, *, include_files: bool = False):
|
||||
"""Roms of a platform, excluding any hidden from the caller (cascade included)."""
|
||||
hidden_platforms, hidden_roms = _hidden_ids(request)
|
||||
if platform_id in hidden_platforms:
|
||||
return []
|
||||
return db_rom_handler.get_roms_scalar(
|
||||
platform_ids=[platform_id],
|
||||
include_files=include_files,
|
||||
hidden_rom_ids=hidden_roms,
|
||||
)
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.get,
|
||||
"/webrcade",
|
||||
@@ -94,7 +119,8 @@ def platforms_webrcade_feed(request: Request) -> WebrcadeFeedSchema:
|
||||
WebrcadeFeedSchema: Webrcade feed object schema
|
||||
"""
|
||||
|
||||
platforms = db_platform_handler.get_platforms()
|
||||
hidden_platforms, hidden_roms = _hidden_ids(request)
|
||||
platforms = db_platform_handler.get_platforms(hidden_platform_ids=hidden_platforms)
|
||||
|
||||
categories = []
|
||||
for p in platforms:
|
||||
@@ -102,7 +128,11 @@ def platforms_webrcade_feed(request: Request) -> WebrcadeFeedSchema:
|
||||
continue
|
||||
|
||||
category_items = []
|
||||
roms = db_rom_handler.get_roms_scalar(platform_ids=[p.id])
|
||||
roms = db_rom_handler.get_roms_scalar(
|
||||
platform_ids=[p.id],
|
||||
hidden_platform_ids=hidden_platforms,
|
||||
hidden_rom_ids=hidden_roms,
|
||||
)
|
||||
for rom in roms:
|
||||
download_url = generate_rom_download_url(request, rom)
|
||||
category_item = WebrcadeFeedItemSchema(
|
||||
@@ -213,7 +243,13 @@ async def tinfoil_index_feed(
|
||||
|
||||
return titledb
|
||||
|
||||
roms = db_rom_handler.get_roms_scalar(platform_ids=[switch.id], include_files=True)
|
||||
hidden_platforms, hidden_roms = _hidden_ids(request)
|
||||
roms = db_rom_handler.get_roms_scalar(
|
||||
platform_ids=[switch.id],
|
||||
include_files=True,
|
||||
hidden_platform_ids=hidden_platforms,
|
||||
hidden_rom_ids=hidden_roms,
|
||||
)
|
||||
|
||||
return TinfoilFeedSchema(
|
||||
files=[
|
||||
@@ -329,9 +365,7 @@ def pkgi_ps3_feed(
|
||||
status_code=400, detail=f"Invalid content type: {content_type}"
|
||||
) from e
|
||||
|
||||
roms = db_rom_handler.get_roms_scalar(
|
||||
platform_ids=[ps3_platform.id], include_files=True
|
||||
)
|
||||
roms = _platform_roms(request, ps3_platform.id, include_files=True)
|
||||
txt_lines = []
|
||||
|
||||
for rom in roms:
|
||||
@@ -407,9 +441,7 @@ def pkgi_psvita_feed(
|
||||
status_code=400, detail=f"Invalid content type: {content_type}"
|
||||
) from e
|
||||
|
||||
roms = db_rom_handler.get_roms_scalar(
|
||||
platform_ids=[psvita_platform.id], include_files=True
|
||||
)
|
||||
roms = _platform_roms(request, psvita_platform.id, include_files=True)
|
||||
txt_lines = []
|
||||
|
||||
for rom in roms:
|
||||
@@ -484,9 +516,7 @@ def pkgi_psp_feed(
|
||||
status_code=400, detail=f"Invalid content type: {content_type}"
|
||||
) from e
|
||||
|
||||
roms = db_rom_handler.get_roms_scalar(
|
||||
platform_ids=[psp_platform.id], include_files=True
|
||||
)
|
||||
roms = _platform_roms(request, psp_platform.id, include_files=True)
|
||||
txt_lines = []
|
||||
|
||||
for rom in roms:
|
||||
@@ -560,7 +590,7 @@ def fpkgi_feed(request: Request, platform_slug: str) -> Response:
|
||||
status_code=404, detail=f"Platform {platform_slug} not found"
|
||||
)
|
||||
|
||||
roms = db_rom_handler.get_roms_scalar(platform_ids=[platform.id])
|
||||
roms = _platform_roms(request, platform.id)
|
||||
response_data = {}
|
||||
|
||||
for rom in roms:
|
||||
@@ -606,7 +636,7 @@ def kekatsu_ds_feed(request: Request, platform_slug: str) -> Response:
|
||||
status_code=404, detail=f"Platform {platform_slug} not found"
|
||||
)
|
||||
|
||||
roms = db_rom_handler.get_roms_scalar(platform_ids=[platform.id])
|
||||
roms = _platform_roms(request, platform.id)
|
||||
|
||||
txt_lines = []
|
||||
txt_lines.append("1") # Database version
|
||||
@@ -669,9 +699,7 @@ def pkgj_psp_games_feed(request: Request) -> Response:
|
||||
status_code=404, detail="PlayStation Portable platform not found"
|
||||
)
|
||||
|
||||
roms = db_rom_handler.get_roms_scalar(
|
||||
platform_ids=[platform.id], include_files=True
|
||||
)
|
||||
roms = _platform_roms(request, platform.id, include_files=True)
|
||||
txt_lines = []
|
||||
txt_lines.append(
|
||||
"Title ID\tRegion\tType\tName\tPKG direct link\tContent ID\tLast Modification Date\tRAP\tDownload .RAP file\tFile Size\tSHA256"
|
||||
@@ -735,9 +763,7 @@ def pkgj_psp_dlcs_feed(request: Request) -> Response:
|
||||
status_code=404, detail="PlayStation Portable platform not found"
|
||||
)
|
||||
|
||||
roms = db_rom_handler.get_roms_scalar(
|
||||
platform_ids=[platform.id], include_files=True
|
||||
)
|
||||
roms = _platform_roms(request, platform.id, include_files=True)
|
||||
txt_lines = []
|
||||
txt_lines.append(
|
||||
"Title ID\tRegion\tName\tPKG direct link\tContent ID\tLast Modification Date\tRAP\tDownload .RAP file\tFile Size\tSHA256"
|
||||
@@ -799,9 +825,7 @@ def pkgj_psv_games_feed(request: Request) -> Response:
|
||||
status_code=404, detail="PlayStation Vita platform not found"
|
||||
)
|
||||
|
||||
roms = db_rom_handler.get_roms_scalar(
|
||||
platform_ids=[platform.id], include_files=True
|
||||
)
|
||||
roms = _platform_roms(request, platform.id, include_files=True)
|
||||
txt_lines = []
|
||||
txt_lines.append(
|
||||
"Title ID\tRegion\tName\tPKG direct link\tzRIF\tContent ID\tLast Modification Date\tOriginal Name\tFile Size\tSHA256\tRequired FW\tApp Version"
|
||||
@@ -866,9 +890,7 @@ def pkgj_psv_dlcs_feed(request: Request) -> Response:
|
||||
status_code=404, detail="PlayStation Vita platform not found"
|
||||
)
|
||||
|
||||
roms = db_rom_handler.get_roms_scalar(
|
||||
platform_ids=[platform.id], include_files=True
|
||||
)
|
||||
roms = _platform_roms(request, platform.id, include_files=True)
|
||||
txt_lines = []
|
||||
txt_lines.append(
|
||||
"Title ID\tRegion\tName\tPKG direct link\tzRIF\tContent ID\tLast Modification Date\tFile Size\tSHA256"
|
||||
@@ -925,9 +947,7 @@ def pkgj_psx_games_feed(request: Request) -> Response:
|
||||
if not platform:
|
||||
raise HTTPException(status_code=404, detail="PlayStation platform not found")
|
||||
|
||||
roms = db_rom_handler.get_roms_scalar(
|
||||
platform_ids=[platform.id], include_files=True
|
||||
)
|
||||
roms = _platform_roms(request, platform.id, include_files=True)
|
||||
txt_lines = []
|
||||
txt_lines.append(
|
||||
"Title ID\tRegion\tName\tPKG direct link\tContent ID\tLast Modification Date\tOriginal Name\tFile Size\tSHA256"
|
||||
|
||||
@@ -8,6 +8,12 @@ from decorators.auth import protected_route
|
||||
from endpoints.responses import BulkOperationResponse
|
||||
from endpoints.responses.firmware import AddFirmwareResponse, FirmwareSchema
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import (
|
||||
assert_can,
|
||||
assert_firmware_visible,
|
||||
assert_platform_visible,
|
||||
get_permissions,
|
||||
)
|
||||
from handler.database import db_firmware_handler, db_platform_handler
|
||||
from handler.filesystem import fs_firmware_handler
|
||||
from handler.scan_handler import scan_firmware
|
||||
@@ -15,6 +21,7 @@ from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.firmware import Firmware
|
||||
from models.permission import PermAction, PermEntity
|
||||
from utils.router import APIRouter
|
||||
|
||||
router = APIRouter(
|
||||
@@ -49,6 +56,13 @@ async def add_firmware(
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
# Platform-hide cascades to firmware; 404-mask uploads to hidden platforms.
|
||||
assert_platform_visible(
|
||||
request,
|
||||
db_platform,
|
||||
not_found_detail=f"Platform with ID {platform_id} not found",
|
||||
)
|
||||
|
||||
uploaded_firmware = []
|
||||
firmware_path = fs_firmware_handler.get_firmware_fs_structure(db_platform.fs_slug)
|
||||
|
||||
@@ -119,9 +133,13 @@ def get_platform_firmware(
|
||||
Returns:
|
||||
list[FirmwareSchema]: Firmware stored in the database
|
||||
"""
|
||||
perms = get_permissions(request)
|
||||
return [
|
||||
FirmwareSchema.model_validate(f)
|
||||
for f in db_firmware_handler.list_firmware(platform_id=platform_id)
|
||||
for f in db_firmware_handler.list_firmware(
|
||||
platform_id=platform_id,
|
||||
hidden_platform_ids=perms.hidden_platform_ids,
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
@@ -137,8 +155,10 @@ def get_firmware_identifiers(
|
||||
Returns:
|
||||
list[int]: List of firmware IDs
|
||||
"""
|
||||
perms = get_permissions(request)
|
||||
firmware = db_firmware_handler.list_firmware(
|
||||
only_fields=[Firmware.id],
|
||||
hidden_platform_ids=perms.hidden_platform_ids,
|
||||
)
|
||||
return [f.id for f in firmware]
|
||||
|
||||
@@ -164,6 +184,8 @@ def get_firmware(request: Request, id: int) -> FirmwareSchema:
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
assert_firmware_visible(request, firmware)
|
||||
|
||||
return FirmwareSchema.model_validate(firmware)
|
||||
|
||||
|
||||
@@ -190,6 +212,8 @@ def head_firmware_content(request: Request, id: int, file_name: str):
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
assert_firmware_visible(request, firmware)
|
||||
|
||||
firmware_path = fs_firmware_handler.validate_path(firmware.full_path)
|
||||
|
||||
return FileResponse(
|
||||
@@ -228,6 +252,8 @@ def get_firmware_content(
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
assert_firmware_visible(request, firmware)
|
||||
|
||||
firmware_path = fs_firmware_handler.validate_path(firmware.full_path)
|
||||
|
||||
return FileResponse(path=firmware_path, filename=firmware.file_name)
|
||||
@@ -254,13 +280,17 @@ async def delete_firmware(
|
||||
) -> BulkOperationResponse:
|
||||
"""Delete firmware."""
|
||||
|
||||
perms = get_permissions(request)
|
||||
assert_can(perms, PermEntity.FIRMWARE, PermAction.DELETE)
|
||||
|
||||
successful_items = 0
|
||||
failed_items = 0
|
||||
errors = []
|
||||
|
||||
for id in firmware:
|
||||
fw = db_firmware_handler.get_firmware(id)
|
||||
if not fw:
|
||||
# Treat firmware on a hidden platform as non-existent for this caller.
|
||||
if not fw or not perms.can_see_platform(fw.platform_id):
|
||||
failed_items += 1
|
||||
errors.append(f"Firmware with ID {id} not found")
|
||||
continue
|
||||
|
||||
327
backend/endpoints/permissions.py
Normal file
327
backend/endpoints/permissions.py
Normal file
@@ -0,0 +1,327 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Body, HTTPException, Request, status
|
||||
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses.permission import (
|
||||
GrantSchemaIO,
|
||||
HiddenEntityCreate,
|
||||
HiddenEntitySchema,
|
||||
OverrideSchemaIO,
|
||||
PermissionCatalogSchema,
|
||||
PermissionGroupCreate,
|
||||
PermissionGroupSchema,
|
||||
PermissionGroupUpdate,
|
||||
PermissionsResponse,
|
||||
UserPermissionsSchema,
|
||||
UserPermissionsUpdate,
|
||||
)
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import assert_admin, get_permissions
|
||||
from handler.database import db_permission_handler, db_user_handler
|
||||
from handler.socket_handler import socket_handler
|
||||
from logger.logger import log
|
||||
from models.permission import PermAction, PermEntity, PermissionGroup
|
||||
from utils.router import APIRouter
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/permissions",
|
||||
tags=["permissions"],
|
||||
)
|
||||
|
||||
|
||||
async def emit_permissions_changed(user_id: int) -> None:
|
||||
"""Notify clients that `user_id`'s effective permissions changed.
|
||||
|
||||
Broadcast (Redis-backed fan-out); the frontend re-fetches `/permissions/me`
|
||||
only when the affected user is the current user. Call this from any path that
|
||||
mutates a user's role, group, overrides or hidden entities.
|
||||
"""
|
||||
try:
|
||||
await socket_handler.socket_server.emit(
|
||||
"permissions:changed", {"user_id": user_id}
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
log.warning(f"Failed to broadcast permissions:changed for user {user_id}: {e}")
|
||||
|
||||
|
||||
@protected_route(router.get, "/me", [Scope.ME_READ])
|
||||
def get_my_permissions(request: Request) -> PermissionsResponse:
|
||||
"""Return the caller's effective permissions for the UI to gate on.
|
||||
|
||||
The backend remains the source of truth; this is a UX hint. Includes the
|
||||
granted action keys and the platform/rom ids hidden from the caller.
|
||||
"""
|
||||
return PermissionsResponse.from_resolved(get_permissions(request))
|
||||
|
||||
|
||||
# --- Admin: catalog -----------------------------------------------------------
|
||||
|
||||
|
||||
@protected_route(router.get, "/catalog", [Scope.USERS_READ])
|
||||
def get_permission_catalog(request: Request) -> PermissionCatalogSchema:
|
||||
"""The entity/action vocabulary the admin UI renders its matrix from."""
|
||||
assert_admin(request)
|
||||
return PermissionCatalogSchema(entities=list(PermEntity), actions=list(PermAction))
|
||||
|
||||
|
||||
# --- Admin: permission groups -------------------------------------------------
|
||||
|
||||
|
||||
def _group_schema(group: PermissionGroup) -> PermissionGroupSchema:
|
||||
return PermissionGroupSchema(
|
||||
id=group.id,
|
||||
name=group.name,
|
||||
description=group.description,
|
||||
is_default=group.is_default,
|
||||
is_system=group.is_system,
|
||||
color=group.color,
|
||||
grants=[
|
||||
GrantSchemaIO(entity=g.entity, action=g.action, own_only=g.own_only)
|
||||
for g in group.grants
|
||||
],
|
||||
member_count=len(db_permission_handler.get_group_member_ids(group.id)),
|
||||
hidden=[
|
||||
HiddenEntitySchema(entity=h.entity, entity_id=h.entity_id)
|
||||
for h in db_permission_handler.get_hidden_entities(group_id=group.id)
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@protected_route(router.get, "/groups", [Scope.USERS_READ])
|
||||
def list_permission_groups(request: Request) -> list[PermissionGroupSchema]:
|
||||
"""List all permission groups with their grants."""
|
||||
assert_admin(request)
|
||||
return [_group_schema(g) for g in db_permission_handler.get_groups()]
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.post, "/groups", [Scope.USERS_WRITE], status_code=status.HTTP_201_CREATED
|
||||
)
|
||||
def create_permission_group(
|
||||
request: Request, body: PermissionGroupCreate
|
||||
) -> PermissionGroupSchema:
|
||||
"""Create a permission group."""
|
||||
assert_admin(request)
|
||||
if db_permission_handler.get_group_by_name(body.name):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="A group with that name already exists",
|
||||
)
|
||||
group = db_permission_handler.create_group(
|
||||
name=body.name,
|
||||
description=body.description,
|
||||
is_default=body.is_default,
|
||||
color=body.color,
|
||||
grants=[(g.entity, g.action, g.own_only) for g in body.grants],
|
||||
)
|
||||
return _group_schema(group)
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.put,
|
||||
"/groups/{id}",
|
||||
[Scope.USERS_WRITE],
|
||||
responses={status.HTTP_404_NOT_FOUND: {}},
|
||||
)
|
||||
async def update_permission_group(
|
||||
request: Request, id: int, body: PermissionGroupUpdate
|
||||
) -> PermissionGroupSchema:
|
||||
"""Update a permission group (name/description/default/grants)."""
|
||||
assert_admin(request)
|
||||
group = db_permission_handler.get_group(id)
|
||||
if group is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
|
||||
|
||||
# Renaming onto an existing name would hit the unique constraint as a 500.
|
||||
if body.name is not None:
|
||||
clash = db_permission_handler.get_group_by_name(body.name)
|
||||
if clash is not None and clash.id != id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="A group with that name already exists",
|
||||
)
|
||||
|
||||
# Don't leave the system without a default group; reassign first.
|
||||
if body.is_default is False and group.is_default:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Set another group as default first",
|
||||
)
|
||||
|
||||
updated = db_permission_handler.update_group(
|
||||
id,
|
||||
name=body.name,
|
||||
description=body.description,
|
||||
is_default=body.is_default,
|
||||
color=body.color,
|
||||
grants=(
|
||||
[(g.entity, g.action, g.own_only) for g in body.grants]
|
||||
if body.grants is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
# Grant changes alter every member's effective permissions.
|
||||
for member_id in db_permission_handler.get_group_member_ids(id):
|
||||
await emit_permissions_changed(member_id)
|
||||
return _group_schema(updated) # type: ignore[arg-type]
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.delete,
|
||||
"/groups/{id}",
|
||||
[Scope.USERS_WRITE],
|
||||
responses={status.HTTP_404_NOT_FOUND: {}},
|
||||
)
|
||||
async def delete_permission_group(request: Request, id: int) -> None:
|
||||
"""Delete a permission group. Members fall back to the default group."""
|
||||
assert_admin(request)
|
||||
group = db_permission_handler.get_group(id)
|
||||
if group is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
|
||||
if group.is_default:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot delete the default group; set another default first",
|
||||
)
|
||||
|
||||
member_ids = db_permission_handler.get_group_member_ids(id)
|
||||
db_permission_handler.delete_group(id)
|
||||
for member_id in member_ids:
|
||||
await emit_permissions_changed(member_id)
|
||||
|
||||
|
||||
# --- Admin: per-user assignment ----------------------------------------------
|
||||
|
||||
|
||||
def _user_permissions(
|
||||
user_id: int, permission_group_id: int | None
|
||||
) -> UserPermissionsSchema:
|
||||
overrides = db_permission_handler.get_user_overrides(user_id)
|
||||
hidden = db_permission_handler.get_hidden_entities(user_id=user_id)
|
||||
return UserPermissionsSchema(
|
||||
user_id=user_id,
|
||||
permission_group_id=permission_group_id,
|
||||
overrides=[
|
||||
OverrideSchemaIO(
|
||||
entity=o.entity,
|
||||
action=o.action,
|
||||
granted=o.granted,
|
||||
own_only=o.own_only,
|
||||
)
|
||||
for o in overrides
|
||||
],
|
||||
hidden=[
|
||||
HiddenEntitySchema(entity=h.entity, entity_id=h.entity_id) for h in hidden
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.get,
|
||||
"/users/{user_id}",
|
||||
[Scope.USERS_READ],
|
||||
responses={status.HTTP_404_NOT_FOUND: {}},
|
||||
)
|
||||
def get_user_permissions(request: Request, user_id: int) -> UserPermissionsSchema:
|
||||
"""A user's group membership, per-user overrides and hidden entities."""
|
||||
assert_admin(request)
|
||||
user = db_user_handler.get_user(user_id)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
|
||||
return _user_permissions(user_id, user.permission_group_id)
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.put,
|
||||
"/users/{user_id}",
|
||||
[Scope.USERS_WRITE],
|
||||
responses={status.HTTP_404_NOT_FOUND: {}},
|
||||
)
|
||||
async def update_user_permissions(
|
||||
request: Request, user_id: int, body: UserPermissionsUpdate
|
||||
) -> UserPermissionsSchema:
|
||||
"""Assign a user's group and/or replace their per-user overrides."""
|
||||
assert_admin(request)
|
||||
user = db_user_handler.get_user(user_id)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
|
||||
|
||||
group_id = user.permission_group_id
|
||||
if body.set_group:
|
||||
group_id = body.permission_group_id
|
||||
db_permission_handler.set_user_group(user_id, group_id)
|
||||
if body.overrides is not None:
|
||||
db_permission_handler.replace_user_overrides(
|
||||
user_id,
|
||||
[(o.entity, o.action, o.granted, o.own_only) for o in body.overrides],
|
||||
)
|
||||
|
||||
await emit_permissions_changed(user_id)
|
||||
return _user_permissions(user_id, group_id)
|
||||
|
||||
|
||||
# --- Admin: hidden entities ---------------------------------------------------
|
||||
|
||||
|
||||
@protected_route(router.post, "/hidden", [Scope.USERS_WRITE])
|
||||
async def add_hidden_entity(
|
||||
request: Request, body: HiddenEntityCreate
|
||||
) -> HiddenEntitySchema:
|
||||
"""Hide an entity from a user OR a group (exactly one principal)."""
|
||||
assert_admin(request)
|
||||
if (body.user_id is None) == (body.group_id is None):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Exactly one of user_id or group_id must be set",
|
||||
)
|
||||
|
||||
# Only platforms and roms are honored by the resolver (firmware is hidden via
|
||||
# its platform cascade), so reject other entity types instead of storing a
|
||||
# row the visibility filter would silently ignore. The id itself is a
|
||||
# denylist entry, so a not-yet-present id is a harmless no-op, not an error.
|
||||
if body.entity not in (PermEntity.PLATFORMS, PermEntity.ROMS):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Only platforms and roms can be hidden",
|
||||
)
|
||||
|
||||
db_permission_handler.add_hidden_entity(
|
||||
body.entity, body.entity_id, user_id=body.user_id, group_id=body.group_id
|
||||
)
|
||||
await _emit_for_principal(body.user_id, body.group_id)
|
||||
return HiddenEntitySchema(entity=body.entity, entity_id=body.entity_id)
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.delete,
|
||||
"/hidden",
|
||||
[Scope.USERS_WRITE],
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
)
|
||||
async def remove_hidden_entity(
|
||||
request: Request,
|
||||
entity: Annotated[PermEntity, Body(embed=True)],
|
||||
entity_id: Annotated[int, Body(embed=True)],
|
||||
user_id: Annotated[int | None, Body(embed=True)] = None,
|
||||
group_id: Annotated[int | None, Body(embed=True)] = None,
|
||||
) -> None:
|
||||
"""Un-hide an entity for a user OR a group."""
|
||||
assert_admin(request)
|
||||
if (user_id is None) == (group_id is None):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Exactly one of user_id or group_id must be set",
|
||||
)
|
||||
db_permission_handler.remove_hidden_entity(
|
||||
entity, entity_id, user_id=user_id, group_id=group_id
|
||||
)
|
||||
await _emit_for_principal(user_id, group_id)
|
||||
|
||||
|
||||
async def _emit_for_principal(user_id: int | None, group_id: int | None) -> None:
|
||||
if user_id is not None:
|
||||
await emit_permissions_changed(user_id)
|
||||
elif group_id is not None:
|
||||
for member_id in db_permission_handler.get_group_member_ids(group_id):
|
||||
await emit_permissions_changed(member_id)
|
||||
@@ -10,12 +10,18 @@ from endpoints.responses.platform import PlatformSchema
|
||||
from exceptions.endpoint_exceptions import PlatformNotFoundInDatabaseException
|
||||
from exceptions.fs_exceptions import PlatformAlreadyExistsException
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import (
|
||||
assert_can,
|
||||
assert_platform_visible,
|
||||
get_permissions,
|
||||
)
|
||||
from handler.database import db_platform_handler
|
||||
from handler.filesystem import fs_platform_handler
|
||||
from handler.scan_handler import scan_platform
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.permission import PermAction, PermEntity
|
||||
from models.platform import Platform
|
||||
from utils.platforms import get_supported_platforms
|
||||
from utils.router import APIRouter
|
||||
@@ -61,9 +67,13 @@ def get_platforms(
|
||||
) -> list[PlatformSchema]:
|
||||
"""Retrieve platforms."""
|
||||
|
||||
perms = get_permissions(request)
|
||||
return [
|
||||
PlatformSchema.model_validate(p)
|
||||
for p in db_platform_handler.get_platforms(updated_after=updated_after)
|
||||
for p in db_platform_handler.get_platforms(
|
||||
updated_after=updated_after,
|
||||
hidden_platform_ids=perms.hidden_platform_ids,
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
@@ -73,8 +83,10 @@ def get_platform_identifiers(
|
||||
) -> list[int]:
|
||||
"""Retrieve platform identifiers."""
|
||||
|
||||
perms = get_permissions(request)
|
||||
platforms = db_platform_handler.get_platforms(
|
||||
only_fields=[Platform.id],
|
||||
hidden_platform_ids=perms.hidden_platform_ids,
|
||||
)
|
||||
return [p.id for p in platforms]
|
||||
|
||||
@@ -101,6 +113,7 @@ def get_platform(
|
||||
platform = db_platform_handler.get_platform(id)
|
||||
if not platform:
|
||||
raise PlatformNotFoundInDatabaseException(id)
|
||||
assert_platform_visible(request, platform)
|
||||
return PlatformSchema.model_validate(platform)
|
||||
|
||||
|
||||
@@ -122,6 +135,7 @@ async def update_platform(
|
||||
platform_db = db_platform_handler.get_platform(id)
|
||||
if not platform_db:
|
||||
raise PlatformNotFoundInDatabaseException(id)
|
||||
assert_platform_visible(request, platform_db)
|
||||
|
||||
if custom_name is not None:
|
||||
platform_db.custom_name = custom_name
|
||||
@@ -142,9 +156,12 @@ async def delete_platform(
|
||||
) -> None:
|
||||
"""Delete a platform by ID."""
|
||||
|
||||
perms = get_permissions(request)
|
||||
platform = db_platform_handler.get_platform(id)
|
||||
if not platform:
|
||||
raise PlatformNotFoundInDatabaseException(id)
|
||||
assert_platform_visible(request, platform)
|
||||
assert_can(perms, PermEntity.PLATFORMS, PermAction.DELETE)
|
||||
|
||||
log.info(
|
||||
f"Deleting {hl(platform.name, color=BLUE)} [{hl(platform.fs_slug)}] from database"
|
||||
|
||||
@@ -23,6 +23,7 @@ class UserSchema(BaseModel):
|
||||
email: str | None
|
||||
enabled: bool
|
||||
role: Role
|
||||
permission_group_id: int | None = None
|
||||
oauth_scopes: list[str]
|
||||
avatar_path: str
|
||||
last_login: UTCDatetime | None
|
||||
|
||||
232
backend/endpoints/responses/permission.py
Normal file
232
backend/endpoints/responses/permission.py
Normal file
@@ -0,0 +1,232 @@
|
||||
"""Response schemas for `/permissions/me`.
|
||||
|
||||
`ActionKey` is the canonical, UI-facing action vocabulary (mirrors the v2
|
||||
`useCan` actions). Exposing it here puts it in the OpenAPI schema so the frontend
|
||||
generates the enum and can delete its hand-authored `actions.ts` / `role-map.ts`.
|
||||
|
||||
The grants returned reflect what the BACKEND actually enforces (the source of
|
||||
truth), resolved from the user's groups + overrides. All scopes are global in
|
||||
this phase; per-resource scoping is reserved for later.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from handler.auth.permissions import ResolvedPermissions
|
||||
from models.permission import PermAction, PermEntity
|
||||
|
||||
|
||||
class ActionKey(enum.StrEnum):
|
||||
# ROMs
|
||||
ROM_VIEW = "rom.view"
|
||||
ROM_PLAY = "rom.play"
|
||||
ROM_DOWNLOAD = "rom.download"
|
||||
ROM_UPLOAD = "rom.upload"
|
||||
ROM_EDIT = "rom.edit"
|
||||
ROM_DELETE = "rom.delete"
|
||||
ROM_MATCH = "rom.match"
|
||||
ROM_REFRESH = "rom.refresh"
|
||||
ROM_FAVORITE = "rom.favorite"
|
||||
# Platforms
|
||||
PLATFORM_VIEW = "platform.view"
|
||||
PLATFORM_CREATE = "platform.create"
|
||||
PLATFORM_EDIT = "platform.edit"
|
||||
PLATFORM_DELETE = "platform.delete"
|
||||
# Collections
|
||||
COLLECTION_VIEW = "collection.view"
|
||||
COLLECTION_CREATE = "collection.create"
|
||||
COLLECTION_EDIT = "collection.edit"
|
||||
COLLECTION_DELETE = "collection.delete"
|
||||
# Library
|
||||
LIBRARY_SCAN = "library.scan"
|
||||
# Users
|
||||
USER_VIEW = "user.view"
|
||||
USER_CREATE = "user.create"
|
||||
USER_EDIT = "user.edit"
|
||||
USER_DELETE = "user.delete"
|
||||
# App-wide "is admin" hatch.
|
||||
APP_ADMIN = "app.admin"
|
||||
|
||||
|
||||
# (entity, action) a user holds -> the UI action keys it unlocks. One backend
|
||||
# grant fans out to several UI actions. Kept faithful to backend enforcement:
|
||||
# e.g. platform create/delete and rom delete gate on the platform/rom write or
|
||||
# delete grants the legacy editor already held.
|
||||
_ENTITY_ACTION_KEYS: dict[tuple[PermEntity, PermAction], tuple[ActionKey, ...]] = {
|
||||
(PermEntity.ROMS, PermAction.READ): (
|
||||
ActionKey.ROM_VIEW,
|
||||
ActionKey.ROM_PLAY,
|
||||
ActionKey.ROM_DOWNLOAD,
|
||||
ActionKey.ROM_FAVORITE,
|
||||
),
|
||||
(PermEntity.ROMS, PermAction.WRITE): (
|
||||
ActionKey.ROM_UPLOAD,
|
||||
ActionKey.ROM_EDIT,
|
||||
ActionKey.ROM_MATCH,
|
||||
ActionKey.ROM_REFRESH,
|
||||
),
|
||||
(PermEntity.ROMS, PermAction.DELETE): (ActionKey.ROM_DELETE,),
|
||||
(PermEntity.PLATFORMS, PermAction.READ): (ActionKey.PLATFORM_VIEW,),
|
||||
(PermEntity.PLATFORMS, PermAction.WRITE): (
|
||||
ActionKey.PLATFORM_CREATE,
|
||||
ActionKey.PLATFORM_EDIT,
|
||||
ActionKey.LIBRARY_SCAN,
|
||||
),
|
||||
(PermEntity.PLATFORMS, PermAction.DELETE): (ActionKey.PLATFORM_DELETE,),
|
||||
(PermEntity.COLLECTIONS, PermAction.READ): (ActionKey.COLLECTION_VIEW,),
|
||||
(PermEntity.COLLECTIONS, PermAction.WRITE): (
|
||||
ActionKey.COLLECTION_CREATE,
|
||||
ActionKey.COLLECTION_EDIT,
|
||||
),
|
||||
(PermEntity.COLLECTIONS, PermAction.DELETE): (ActionKey.COLLECTION_DELETE,),
|
||||
(PermEntity.USERS, PermAction.READ): (ActionKey.USER_VIEW,),
|
||||
(PermEntity.USERS, PermAction.WRITE): (
|
||||
ActionKey.USER_CREATE,
|
||||
ActionKey.USER_EDIT,
|
||||
ActionKey.USER_DELETE,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
class PermissionScopeSchema(BaseModel):
|
||||
kind: Literal["global", "platform", "collection", "rom"] = "global"
|
||||
id: int | None = None
|
||||
|
||||
|
||||
class GrantSchema(BaseModel):
|
||||
action: ActionKey
|
||||
scope: PermissionScopeSchema
|
||||
|
||||
|
||||
class HiddenEntitiesSchema(BaseModel):
|
||||
platforms: list[int]
|
||||
roms: list[int]
|
||||
|
||||
|
||||
class PermissionsResponse(BaseModel):
|
||||
is_admin: bool
|
||||
grants: list[GrantSchema]
|
||||
hidden: HiddenEntitiesSchema
|
||||
|
||||
@classmethod
|
||||
def from_resolved(cls, perms: ResolvedPermissions) -> PermissionsResponse:
|
||||
keys = action_keys_for(perms)
|
||||
return cls(
|
||||
is_admin=perms.is_admin,
|
||||
grants=[
|
||||
GrantSchema(action=k, scope=PermissionScopeSchema(kind="global"))
|
||||
for k in keys
|
||||
],
|
||||
hidden=HiddenEntitiesSchema(
|
||||
platforms=sorted(perms.hidden_platform_ids),
|
||||
roms=sorted(perms.hidden_rom_ids),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def action_keys_for(perms: ResolvedPermissions) -> list[ActionKey]:
|
||||
"""The UI action keys a user can perform, in enum order.
|
||||
|
||||
Admins unlock everything (the frontend also short-circuits on `is_admin`).
|
||||
Otherwise each held grant fans out to its UI actions; `owned=True` makes
|
||||
own-only grants (e.g. manage own collections) count as "can do this action".
|
||||
"""
|
||||
if perms.is_admin:
|
||||
return list(ActionKey)
|
||||
|
||||
keys: set[ActionKey] = set()
|
||||
for (entity, action), action_keys in _ENTITY_ACTION_KEYS.items():
|
||||
if perms.allows(entity, action, owned=True):
|
||||
keys.update(action_keys)
|
||||
return [k for k in ActionKey if k in keys]
|
||||
|
||||
|
||||
# --- Admin CRUD schemas -------------------------------------------------------
|
||||
|
||||
|
||||
class GrantSchemaIO(BaseModel):
|
||||
"""A single (entity, action) grant on a group, with the own-only flag."""
|
||||
|
||||
entity: PermEntity
|
||||
action: PermAction
|
||||
own_only: bool = False
|
||||
|
||||
|
||||
class PermissionGroupSchema(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
description: str
|
||||
is_default: bool
|
||||
is_system: bool
|
||||
color: str | None
|
||||
grants: list[GrantSchemaIO]
|
||||
member_count: int
|
||||
# Entities hidden from every member of this group (admin override still
|
||||
# applies per-user on top). Empty for groups with no group-level hides.
|
||||
hidden: list[HiddenEntitySchema] = []
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
class PermissionGroupCreate(BaseModel):
|
||||
name: str
|
||||
description: str = ""
|
||||
is_default: bool = False
|
||||
color: str | None = None
|
||||
grants: list[GrantSchemaIO] = []
|
||||
|
||||
|
||||
class PermissionGroupUpdate(BaseModel):
|
||||
name: str | None = None
|
||||
description: str | None = None
|
||||
is_default: bool | None = None
|
||||
color: str | None = None
|
||||
grants: list[GrantSchemaIO] | None = None
|
||||
|
||||
|
||||
class OverrideSchemaIO(BaseModel):
|
||||
entity: PermEntity
|
||||
action: PermAction
|
||||
granted: bool
|
||||
own_only: bool = False
|
||||
|
||||
|
||||
class HiddenEntitySchema(BaseModel):
|
||||
entity: PermEntity
|
||||
entity_id: int
|
||||
|
||||
|
||||
class HiddenEntityCreate(BaseModel):
|
||||
entity: PermEntity
|
||||
entity_id: int
|
||||
# Exactly one principal must be set (validated by the endpoint).
|
||||
user_id: int | None = None
|
||||
group_id: int | None = None
|
||||
|
||||
|
||||
class UserPermissionsSchema(BaseModel):
|
||||
"""Admin view of one user's permission assignment."""
|
||||
|
||||
user_id: int
|
||||
permission_group_id: int | None
|
||||
overrides: list[OverrideSchemaIO]
|
||||
hidden: list[HiddenEntitySchema]
|
||||
|
||||
|
||||
class UserPermissionsUpdate(BaseModel):
|
||||
# `permission_group_id` is a tri-state: omit to leave unchanged, null to
|
||||
# clear (fall back to default group), an id to assign.
|
||||
permission_group_id: int | None = None
|
||||
set_group: bool = False
|
||||
overrides: list[OverrideSchemaIO] | None = None
|
||||
|
||||
|
||||
class PermissionCatalogSchema(BaseModel):
|
||||
"""The vocabulary the admin UI renders the group/override matrix from."""
|
||||
|
||||
entities: list[PermEntity]
|
||||
actions: list[PermAction]
|
||||
@@ -406,6 +406,23 @@ class SiblingRomSchema(BaseModel):
|
||||
)
|
||||
|
||||
|
||||
def _visible_siblings(db_rom: Rom, request: Request) -> list[Rom]:
|
||||
"""`db_rom.sibling_roms` minus any sibling hidden from the caller.
|
||||
|
||||
Single-rom endpoints (detail / simple fallback) read siblings off the
|
||||
eager-loaded relationship, which bypasses the list query's hidden filter.
|
||||
"""
|
||||
siblings = list(db_rom.sibling_roms)
|
||||
if not request.user.is_authenticated:
|
||||
return siblings
|
||||
|
||||
# Local import: breaks the responses.rom <-> handler.auth.dependencies cycle.
|
||||
from handler.auth.dependencies import get_permissions
|
||||
|
||||
perms = get_permissions(request)
|
||||
return [s for s in siblings if perms.can_see_rom(s.id, s.platform_id)]
|
||||
|
||||
|
||||
class SimpleRomSchema(RomSchema):
|
||||
screenshot_path: str | None = None
|
||||
|
||||
@@ -440,7 +457,7 @@ class SimpleRomSchema(RomSchema):
|
||||
for ru in s.rom_users
|
||||
),
|
||||
)
|
||||
for s in db_rom.sibling_roms
|
||||
for s in _visible_siblings(db_rom, request)
|
||||
]
|
||||
|
||||
db_rom.included_files = list(files) # type: ignore[assignment]
|
||||
@@ -502,7 +519,7 @@ class DetailedRomSchema(RomSchema):
|
||||
for ru in s.rom_users
|
||||
),
|
||||
)
|
||||
for s in db_rom.sibling_roms
|
||||
for s in _visible_siblings(db_rom, request)
|
||||
),
|
||||
key=lambda x: x.sort_comparator,
|
||||
)
|
||||
|
||||
@@ -47,6 +47,11 @@ from endpoints.responses.rom import (
|
||||
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
||||
from exceptions.fs_exceptions import RomAlreadyExistsException
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import (
|
||||
assert_can,
|
||||
assert_rom_visible,
|
||||
get_permissions,
|
||||
)
|
||||
from handler.database import db_rom_handler, db_save_handler
|
||||
from handler.database.base_handler import sync_session
|
||||
from handler.filesystem import fs_resource_handler, fs_rom_handler
|
||||
@@ -64,6 +69,7 @@ from handler.metadata.ss_handler import add_ss_auth_to_url, get_preferred_media_
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.permission import PermAction, PermEntity
|
||||
from models.rom import Rom, RomUserStatus, compute_name_sort_key
|
||||
from utils.background_tasks import fire_and_forget
|
||||
from utils.database import safe_int, safe_str_to_bool
|
||||
@@ -543,6 +549,8 @@ def get_roms(
|
||||
] = False,
|
||||
) -> CustomLimitOffsetPage[SimpleRomSchema]:
|
||||
"""Retrieve roms."""
|
||||
perms = get_permissions(request)
|
||||
|
||||
unfiltered_query, order_by_attr = db_rom_handler.get_roms_query(
|
||||
user_id=request.user.id,
|
||||
order_by=order_by.lower(),
|
||||
@@ -554,6 +562,8 @@ def get_roms(
|
||||
query = db_rom_handler.filter_roms(
|
||||
query=unfiltered_query,
|
||||
user_id=request.user.id,
|
||||
hidden_platform_ids=perms.hidden_platform_ids,
|
||||
hidden_rom_ids=perms.hidden_rom_ids,
|
||||
platform_ids=platform_ids,
|
||||
collection_id=collection_id,
|
||||
virtual_collection_id=virtual_collection_id,
|
||||
@@ -660,6 +670,8 @@ def get_roms(
|
||||
filter_query = db_rom_handler.filter_roms(
|
||||
query=unfiltered_query,
|
||||
user_id=request.user.id,
|
||||
hidden_platform_ids=perms.hidden_platform_ids,
|
||||
hidden_rom_ids=perms.hidden_rom_ids,
|
||||
platform_ids=platform_ids,
|
||||
collection_id=collection_id,
|
||||
virtual_collection_id=virtual_collection_id,
|
||||
@@ -697,7 +709,11 @@ def get_roms(
|
||||
else {}
|
||||
)
|
||||
siblings_by_rom = db_rom_handler.get_siblings_for_roms(
|
||||
rom_ids, user_id=request.user.id, session=session
|
||||
rom_ids,
|
||||
user_id=request.user.id,
|
||||
session=session,
|
||||
hidden_platform_ids=list(perms.hidden_platform_ids),
|
||||
hidden_rom_ids=list(perms.hidden_rom_ids),
|
||||
)
|
||||
|
||||
# Continue-playing rail
|
||||
@@ -747,9 +763,12 @@ def get_rom_identifiers(
|
||||
request: Request,
|
||||
) -> list[int]:
|
||||
"""Retrieve rom identifiers."""
|
||||
perms = get_permissions(request)
|
||||
db_roms = db_rom_handler.get_roms_scalar(
|
||||
user_id=request.user.id,
|
||||
only_fields=[Rom.id],
|
||||
hidden_platform_ids=perms.hidden_platform_ids,
|
||||
hidden_rom_ids=perms.hidden_rom_ids,
|
||||
)
|
||||
|
||||
return [r.id for r in db_roms]
|
||||
@@ -804,6 +823,13 @@ async def download_roms(
|
||||
|
||||
rom_objects = db_rom_handler.get_roms_by_ids(rom_id_list)
|
||||
|
||||
# Drop roms hidden from the caller so they can't be pulled by direct id.
|
||||
if request.user.is_authenticated:
|
||||
perms = get_permissions(request)
|
||||
rom_objects = [
|
||||
rom for rom in rom_objects if perms.can_see_rom(rom.id, rom.platform_id)
|
||||
]
|
||||
|
||||
if not rom_objects:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
@@ -909,12 +935,14 @@ def get_rom_by_metadata_provider(
|
||||
hltb_id=hltb_id,
|
||||
)
|
||||
|
||||
not_found_detail = "ROM not found with given metadata IDs"
|
||||
if not rom:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="ROM not found with given metadata IDs",
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail=not_found_detail
|
||||
)
|
||||
|
||||
assert_rom_visible(request, rom, not_found_detail=not_found_detail)
|
||||
|
||||
return DetailedRomSchema.from_orm_with_request(rom, request)
|
||||
|
||||
|
||||
@@ -946,12 +974,14 @@ def get_rom_by_hash(
|
||||
ra_hash=ra_hash,
|
||||
)
|
||||
|
||||
not_found_detail = "No ROM or file found with given hash values"
|
||||
if not rom:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="No ROM or file found with given hash values",
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail=not_found_detail
|
||||
)
|
||||
|
||||
assert_rom_visible(request, rom, not_found_detail=not_found_detail)
|
||||
|
||||
return DetailedRomSchema.from_orm_with_request(rom, request)
|
||||
|
||||
|
||||
@@ -987,6 +1017,8 @@ def get_rom_simple(
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
assert_rom_visible(request, rom)
|
||||
|
||||
return SimpleRomSchema.from_orm_with_request(rom, request)
|
||||
|
||||
|
||||
@@ -1007,6 +1039,8 @@ def get_rom(
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
assert_rom_visible(request, rom)
|
||||
|
||||
return DetailedRomSchema.from_orm_with_request(rom, request)
|
||||
|
||||
|
||||
@@ -1034,6 +1068,8 @@ async def head_rom_content(
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
assert_rom_visible(request, rom)
|
||||
|
||||
files = rom.files
|
||||
if file_ids:
|
||||
file_id_values = {int(f.strip()) for f in file_ids.split(",") if f.strip()}
|
||||
@@ -1114,6 +1150,8 @@ async def get_rom_content(
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
assert_rom_visible(request, rom)
|
||||
|
||||
# https://muos.dev/help/addcontent#what-about-multi-disc-content
|
||||
hidden_folder = safe_str_to_bool(request.query_params.get("hidden_folder", ""))
|
||||
|
||||
@@ -1276,6 +1314,8 @@ async def update_rom(
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
assert_rom_visible(request, rom)
|
||||
|
||||
if unmatch_metadata:
|
||||
db_rom_handler.update_rom(
|
||||
id,
|
||||
@@ -1692,6 +1732,9 @@ async def delete_roms(
|
||||
) -> BulkOperationResponse:
|
||||
"""Delete roms."""
|
||||
|
||||
perms = get_permissions(request)
|
||||
assert_can(perms, PermEntity.ROMS, PermAction.DELETE)
|
||||
|
||||
successful_items = 0
|
||||
failed_items = 0
|
||||
errors = []
|
||||
@@ -1699,7 +1742,8 @@ async def delete_roms(
|
||||
for id in roms:
|
||||
rom = db_rom_handler.get_rom(id)
|
||||
|
||||
if not rom:
|
||||
# Hidden roms are masked as not-found rather than reported deletable.
|
||||
if not rom or not perms.can_see_rom(rom.id, rom.platform_id):
|
||||
failed_items += 1
|
||||
errors.append(f"ROM with ID {id} not found")
|
||||
continue
|
||||
@@ -1784,6 +1828,8 @@ async def update_rom_user(
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
assert_rom_visible(request, rom)
|
||||
|
||||
db_rom_user = db_rom_handler.get_rom_user(
|
||||
id, request.user.id
|
||||
) or db_rom_handler.add_rom_user(id, request.user.id)
|
||||
|
||||
@@ -14,6 +14,7 @@ from starlette.responses import FileResponse
|
||||
from config import ROM_PATCHER_MAX_FILE_SIZE_BYTES
|
||||
from decorators.auth import protected_route
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import get_permissions
|
||||
from handler.database import db_rom_handler
|
||||
from handler.filesystem import fs_rom_handler
|
||||
from logger.formatter import BLUE
|
||||
@@ -64,12 +65,21 @@ async def patch_rom(
|
||||
request.user.username if request.user.is_authenticated else "unknown"
|
||||
)
|
||||
|
||||
perms = get_permissions(request)
|
||||
|
||||
rom_file = db_rom_handler.get_rom_file_by_id(id)
|
||||
if not rom_file:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"ROM file with id {id} not found",
|
||||
)
|
||||
# 404-mask file bytes of roms hidden from the caller.
|
||||
base_rom = db_rom_handler.get_rom(rom_file.rom_id)
|
||||
if not base_rom or not perms.can_see_rom(base_rom.id, base_rom.platform_id):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"ROM file with id {id} not found",
|
||||
)
|
||||
if rom_file.missing_from_fs:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
@@ -82,6 +92,15 @@ async def patch_rom(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Patch file with id {patch_request.patch_file_id} not found",
|
||||
)
|
||||
# The patch file's bytes are read too; mask it if its rom is hidden.
|
||||
patch_rom_parent = db_rom_handler.get_rom(patch_file.rom_id)
|
||||
if not patch_rom_parent or not perms.can_see_rom(
|
||||
patch_rom_parent.id, patch_rom_parent.platform_id
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Patch file with id {patch_request.patch_file_id} not found",
|
||||
)
|
||||
if patch_file.missing_from_fs:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
|
||||
@@ -6,6 +6,7 @@ from decorators.auth import protected_route
|
||||
from endpoints.responses.search import SearchCoverSchema, SearchRomSchema
|
||||
from exceptions.endpoint_exceptions import SGDBInvalidAPIKeyException
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import get_permissions
|
||||
from handler.database import db_rom_handler
|
||||
from handler.metadata import (
|
||||
meta_flashpoint_handler,
|
||||
@@ -78,6 +79,12 @@ async def search_rom(
|
||||
if not rom:
|
||||
return []
|
||||
|
||||
# Treat a rom hidden from the caller as non-existent.
|
||||
if request.user.is_authenticated and not get_permissions(request).can_see_rom(
|
||||
rom.id, rom.platform_id
|
||||
):
|
||||
return []
|
||||
|
||||
search_term = search_term or rom.fs_name_no_tags
|
||||
if not search_term:
|
||||
return []
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
from fastapi import Request
|
||||
|
||||
from endpoints.responses.stats import StatsReturn
|
||||
from handler.auth.dependencies import get_permissions
|
||||
from handler.database import db_stats_handler
|
||||
from utils.router import APIRouter
|
||||
|
||||
@@ -9,26 +12,42 @@ router = APIRouter(
|
||||
|
||||
|
||||
@router.get("")
|
||||
def stats(include_platform_stats: bool = False) -> StatsReturn:
|
||||
def stats(request: Request, include_platform_stats: bool = False) -> StatsReturn:
|
||||
"""Endpoint to return the current RomM stats
|
||||
|
||||
Returns:
|
||||
dict: Dictionary with all the stats
|
||||
"""
|
||||
|
||||
# Exclude platforms/roms hidden from the caller (admins/anon: no filtering).
|
||||
hidden_platform_ids: list[int] = []
|
||||
hidden_rom_ids: list[int] = []
|
||||
if request.user.is_authenticated:
|
||||
perms = get_permissions(request)
|
||||
hidden_platform_ids = list(perms.hidden_platform_ids)
|
||||
hidden_rom_ids = list(perms.hidden_rom_ids)
|
||||
|
||||
result: StatsReturn = {
|
||||
"PLATFORMS": db_stats_handler.get_platforms_count(),
|
||||
"ROMS": db_stats_handler.get_roms_count(),
|
||||
"PLATFORMS": db_stats_handler.get_platforms_count(
|
||||
hidden_platform_ids, hidden_rom_ids
|
||||
),
|
||||
"ROMS": db_stats_handler.get_roms_count(hidden_platform_ids, hidden_rom_ids),
|
||||
"SAVES": db_stats_handler.get_saves_count(),
|
||||
"STATES": db_stats_handler.get_states_count(),
|
||||
"SCREENSHOTS": db_stats_handler.get_screenshots_count(),
|
||||
"TOTAL_FILESIZE_BYTES": db_stats_handler.get_total_filesize(),
|
||||
"TOTAL_FILESIZE_BYTES": db_stats_handler.get_total_filesize(
|
||||
hidden_platform_ids, hidden_rom_ids
|
||||
),
|
||||
}
|
||||
|
||||
if include_platform_stats:
|
||||
result["METADATA_COVERAGE"] = (
|
||||
db_stats_handler.get_metadata_coverage_by_platform()
|
||||
db_stats_handler.get_metadata_coverage_by_platform(
|
||||
hidden_platform_ids, hidden_rom_ids
|
||||
)
|
||||
)
|
||||
result["REGION_BREAKDOWN"] = db_stats_handler.get_region_breakdown_by_platform(
|
||||
hidden_platform_ids, hidden_rom_ids
|
||||
)
|
||||
result["REGION_BREAKDOWN"] = db_stats_handler.get_region_breakdown_by_platform()
|
||||
|
||||
return result
|
||||
|
||||
@@ -7,6 +7,7 @@ from fastapi import Request, status
|
||||
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.forms.identity import UserForm
|
||||
from endpoints.permissions import emit_permissions_changed
|
||||
from endpoints.responses.identity import InviteLinkSchema, UserSchema
|
||||
from handler.auth import auth_handler
|
||||
from handler.auth.constants import Scope
|
||||
@@ -57,16 +58,28 @@ def add_user(
|
||||
UserSchema: Newly created user
|
||||
"""
|
||||
|
||||
admins_exist = len(db_user_handler.get_admin_users()) > 0
|
||||
|
||||
# If there are admin users already, enforce the USERS_WRITE scope.
|
||||
if (
|
||||
Scope.USERS_WRITE not in request.auth.scopes
|
||||
and len(db_user_handler.get_admin_users()) > 0
|
||||
):
|
||||
if Scope.USERS_WRITE not in request.auth.scopes and admins_exist:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Forbidden",
|
||||
)
|
||||
|
||||
coerced_role = Role.coerce(role)
|
||||
# USERS_WRITE is delegable to non-admins via permission groups, but creating
|
||||
# an admin must stay admin-only or it becomes a privilege-escalation path.
|
||||
if (
|
||||
admins_exist
|
||||
and coerced_role == Role.ADMIN
|
||||
and getattr(request.user, "role", None) != Role.ADMIN
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only an administrator can create admin users",
|
||||
)
|
||||
|
||||
try:
|
||||
validate_username(username)
|
||||
validate_password(password)
|
||||
@@ -97,7 +110,7 @@ def add_user(
|
||||
username=username.lower(),
|
||||
hashed_password=auth_handler.get_password_hash(password),
|
||||
email=email.lower() or None,
|
||||
role=Role[role.upper()],
|
||||
role=coerced_role,
|
||||
)
|
||||
|
||||
return UserSchema.model_validate(db_user_handler.add_user(user))
|
||||
@@ -124,10 +137,9 @@ def create_invite_link(
|
||||
InviteLinkSchema: Invite link
|
||||
"""
|
||||
|
||||
if (
|
||||
Scope.USERS_WRITE not in request.auth.scopes
|
||||
and len(db_user_handler.get_admin_users()) > 0
|
||||
):
|
||||
admins_exist = len(db_user_handler.get_admin_users()) > 0
|
||||
|
||||
if Scope.USERS_WRITE not in request.auth.scopes and admins_exist:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Forbidden",
|
||||
@@ -141,6 +153,17 @@ def create_invite_link(
|
||||
detail=msg,
|
||||
)
|
||||
|
||||
# Mirrors add_user: only a real admin can mint admin invite links.
|
||||
if (
|
||||
admins_exist
|
||||
and Role.coerce(role) == Role.ADMIN
|
||||
and getattr(request.user, "role", None) != Role.ADMIN
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only an administrator can create admin invite links",
|
||||
)
|
||||
|
||||
if expiration is not None and expiration <= 0:
|
||||
msg = "Invite link expiration must be a positive integer"
|
||||
log.error(msg)
|
||||
@@ -205,7 +228,7 @@ def create_user_from_invite(
|
||||
username=username.lower(),
|
||||
hashed_password=auth_handler.get_password_hash(password),
|
||||
email=email.lower() or None,
|
||||
role=Role[role.upper()],
|
||||
role=Role.coerce(role),
|
||||
)
|
||||
|
||||
created_user = db_user_handler.add_user(user)
|
||||
@@ -359,7 +382,18 @@ async def update_user(
|
||||
|
||||
# You can't change your own role
|
||||
if form_data.role and request.user.id != id:
|
||||
cleaned_data["role"] = Role[form_data.role.upper()] # type: ignore[assignment]
|
||||
new_role = Role.coerce(form_data.role)
|
||||
# You can't demote the last admin (mirrors the delete guard).
|
||||
if (
|
||||
db_user.role == Role.ADMIN
|
||||
and new_role != Role.ADMIN
|
||||
and len(db_user_handler.get_admin_users()) == 1
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="You cannot demote the last admin user",
|
||||
)
|
||||
cleaned_data["role"] = new_role # type: ignore[assignment]
|
||||
|
||||
# You can't disable yourself
|
||||
if form_data.enabled is not None and request.user.id != id:
|
||||
@@ -402,6 +436,10 @@ async def update_user(
|
||||
if cleaned_data:
|
||||
db_user_handler.update_user(id, cleaned_data)
|
||||
|
||||
# A role change alters the user's effective permissions; tell their UI.
|
||||
if "role" in cleaned_data:
|
||||
await emit_permissions_changed(id)
|
||||
|
||||
# Log out the current user if username or password changed
|
||||
creds_updated = cleaned_data.get("username") or cleaned_data.get(
|
||||
"hashed_password"
|
||||
|
||||
@@ -416,18 +416,20 @@ class OpenIDHandler:
|
||||
detail=f"'{OIDC_USERNAME_ATTRIBUTE}' attribute is missing from token.",
|
||||
)
|
||||
|
||||
role = Role.VIEWER
|
||||
# Admin claim grants admin; the legacy editor/viewer claims both map to
|
||||
# the single `user` kind now (env var names kept to avoid a breaking
|
||||
# ops rename). No matching claim -> no access.
|
||||
role = Role.USER
|
||||
claims_provided = OIDC_CLAIM_ROLES and OIDC_CLAIM_ROLES in userinfo
|
||||
if claims_provided:
|
||||
roles = userinfo[OIDC_CLAIM_ROLES] or []
|
||||
if OIDC_ROLE_ADMIN and OIDC_ROLE_ADMIN in roles:
|
||||
role = Role.ADMIN
|
||||
elif OIDC_ROLE_EDITOR and OIDC_ROLE_EDITOR in roles:
|
||||
role = Role.EDITOR
|
||||
elif OIDC_ROLE_VIEWER and (
|
||||
OIDC_ROLE_VIEWER in roles or OIDC_ROLE_VIEWER == "*"
|
||||
elif (OIDC_ROLE_EDITOR and OIDC_ROLE_EDITOR in roles) or (
|
||||
OIDC_ROLE_VIEWER
|
||||
and (OIDC_ROLE_VIEWER in roles or OIDC_ROLE_VIEWER == "*")
|
||||
):
|
||||
role = Role.VIEWER
|
||||
role = Role.USER
|
||||
else:
|
||||
log.error("User has not been granted any roles for this application.")
|
||||
raise HTTPException(
|
||||
|
||||
151
backend/handler/auth/dependencies.py
Normal file
151
backend/handler/auth/dependencies.py
Normal file
@@ -0,0 +1,151 @@
|
||||
"""Fine-grained, DB-backed permission checks for endpoint handlers.
|
||||
|
||||
The coarse ``@protected_route(..., [Scope.X])`` gate stays the first line of
|
||||
defense (and is what client tokens / kiosk rely on). These helpers add the
|
||||
authoritative per-entity / per-action / ownership / visibility decisions on top,
|
||||
resolved once per request and cached on ``request.state``.
|
||||
|
||||
Typical use inside a handler::
|
||||
|
||||
perms = get_permissions(request)
|
||||
assert_can(perms, PermEntity.ROMS, PermAction.DELETE) # library-wide
|
||||
assert_can(perms, PermEntity.COLLECTIONS, PermAction.WRITE,
|
||||
owner_id=collection.user_id) # own-data ok
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from fastapi import HTTPException, Request, status
|
||||
|
||||
from exceptions.endpoint_exceptions import (
|
||||
PlatformNotFoundInDatabaseException,
|
||||
RomNotFoundInDatabaseException,
|
||||
)
|
||||
from handler.auth.permissions import ResolvedPermissions, resolve_permissions
|
||||
from models.permission import PermAction, PermEntity
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from models.firmware import Firmware
|
||||
from models.platform import Platform
|
||||
from models.rom import Rom
|
||||
|
||||
|
||||
def get_permissions(request: Request) -> ResolvedPermissions:
|
||||
"""Resolve (and cache for the request) the caller's effective permissions."""
|
||||
cached = getattr(request.state, "permissions", None)
|
||||
if cached is not None:
|
||||
return cached
|
||||
perms = resolve_permissions(request.user)
|
||||
request.state.permissions = perms
|
||||
return perms
|
||||
|
||||
|
||||
def can_access(
|
||||
perms: ResolvedPermissions,
|
||||
entity: PermEntity,
|
||||
action: PermAction,
|
||||
*,
|
||||
owner_id: int | None = None,
|
||||
) -> bool:
|
||||
"""Whether ``perms`` may perform ``action`` on ``entity``.
|
||||
|
||||
Admins bypass. A user may always act on a resource they own (``owner_id``
|
||||
matches). Otherwise a library-wide (non ``own_only``) grant is required.
|
||||
"""
|
||||
if perms.is_admin:
|
||||
return True
|
||||
if owner_id is not None and owner_id == perms.user_id:
|
||||
return True
|
||||
return perms.allows(entity, action, owned=False)
|
||||
|
||||
|
||||
def assert_can(
|
||||
perms: ResolvedPermissions,
|
||||
entity: PermEntity,
|
||||
action: PermAction,
|
||||
*,
|
||||
owner_id: int | None = None,
|
||||
) -> None:
|
||||
"""Raise 403 unless ``perms`` may perform ``action`` on ``entity``."""
|
||||
if not can_access(perms, entity, action, owner_id=owner_id):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Insufficient permissions",
|
||||
)
|
||||
|
||||
|
||||
def require_permission(entity: PermEntity, action: PermAction):
|
||||
"""FastAPI dependency factory for library-wide gating of a route.
|
||||
|
||||
Returns the resolved permissions so the handler can reuse them.
|
||||
"""
|
||||
|
||||
def _dependency(request: Request) -> ResolvedPermissions:
|
||||
perms = get_permissions(request)
|
||||
assert_can(perms, entity, action)
|
||||
return perms
|
||||
|
||||
return _dependency
|
||||
|
||||
|
||||
def assert_admin(request: Request) -> ResolvedPermissions:
|
||||
"""Raise 403 unless the caller is an admin. For permission-management routes."""
|
||||
perms = get_permissions(request)
|
||||
if not perms.is_admin:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Administrator privileges required",
|
||||
)
|
||||
return perms
|
||||
|
||||
|
||||
# 404-masking helpers: a hidden entity must read as non-existent, not forbidden,
|
||||
# so its existence isn't leaked. The auth guard skips the check on unauthenticated
|
||||
# download endpoints, which carry no permission context to resolve.
|
||||
def assert_rom_visible(
|
||||
request: Request, rom: Rom, *, not_found_detail: str | None = None
|
||||
) -> None:
|
||||
"""Raise 404 (not 403) when the rom is hidden from the caller.
|
||||
|
||||
Defaults to the standard ``RomNotFoundInDatabaseException`` message; pass
|
||||
``not_found_detail`` for endpoints with a bespoke 404 (metadata-id / hash
|
||||
lookups) so the masked response is indistinguishable from their not-found.
|
||||
"""
|
||||
if request.user.is_authenticated and not get_permissions(request).can_see_rom(
|
||||
rom.id, rom.platform_id
|
||||
):
|
||||
if not_found_detail is not None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail=not_found_detail
|
||||
)
|
||||
raise RomNotFoundInDatabaseException(rom.id)
|
||||
|
||||
|
||||
def assert_platform_visible(
|
||||
request: Request, platform: Platform, *, not_found_detail: str | None = None
|
||||
) -> None:
|
||||
"""Raise 404 (not 403) when the platform is hidden from the caller.
|
||||
|
||||
Pass ``not_found_detail`` to match an endpoint's bespoke 404 message.
|
||||
"""
|
||||
if request.user.is_authenticated and not get_permissions(request).can_see_platform(
|
||||
platform.id
|
||||
):
|
||||
if not_found_detail is not None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail=not_found_detail
|
||||
)
|
||||
raise PlatformNotFoundInDatabaseException(platform.id)
|
||||
|
||||
|
||||
def assert_firmware_visible(request: Request, firmware: Firmware) -> None:
|
||||
"""Raise 404 when the firmware's platform is hidden (firmware inherits it)."""
|
||||
if request.user.is_authenticated and not get_permissions(request).can_see_platform(
|
||||
firmware.platform_id
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Firmware with ID {firmware.id} not found",
|
||||
)
|
||||
200
backend/handler/auth/permissions.py
Normal file
200
backend/handler/auth/permissions.py
Normal file
@@ -0,0 +1,200 @@
|
||||
"""Per-request permission resolution and the coarse ``oauth_scopes`` projection.
|
||||
|
||||
This is the authoritative source the auth layer consults. ``resolve_permissions``
|
||||
computes a user's effective grants (group ∪ overrides, admin bypass) plus the set
|
||||
of entity ids hidden from them; ``compute_oauth_scopes`` projects the grants onto
|
||||
the legacy coarse ``Scope`` vocabulary so the existing scope-based enforcement,
|
||||
client tokens and OAuth flow keep working unchanged.
|
||||
|
||||
Precedence: admin bypass > per-user override > group grant > legacy default.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from config import KIOSK_MODE
|
||||
from decorators.database import begin_session
|
||||
from handler.auth.constants import FULL_SCOPES, READ_SCOPES, Scope
|
||||
from handler.auth.permissions_map import (
|
||||
grants_to_scopes,
|
||||
order_scopes,
|
||||
)
|
||||
from models.permission import PermAction, PermEntity
|
||||
from models.user import Role, User
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ResolvedGrant:
|
||||
entity: PermEntity
|
||||
action: PermAction
|
||||
own_only: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ResolvedPermissions:
|
||||
is_admin: bool
|
||||
user_id: int | None
|
||||
grants: frozenset[ResolvedGrant]
|
||||
hidden_platform_ids: frozenset[int]
|
||||
hidden_rom_ids: frozenset[int]
|
||||
|
||||
def allows(
|
||||
self, entity: PermEntity, action: PermAction, *, owned: bool | None = None
|
||||
) -> bool:
|
||||
if self.is_admin:
|
||||
return True
|
||||
for g in self.grants:
|
||||
if g.entity != entity or g.action != action:
|
||||
continue
|
||||
# own_only grants only satisfy a check on an owned resource.
|
||||
if g.own_only and owned is not True:
|
||||
continue
|
||||
return True
|
||||
return False
|
||||
|
||||
def can_see_platform(self, platform_id: int) -> bool:
|
||||
return self.is_admin or platform_id not in self.hidden_platform_ids
|
||||
|
||||
def can_see_rom(self, rom_id: int, platform_id: int) -> bool:
|
||||
if self.is_admin:
|
||||
return True
|
||||
return (
|
||||
platform_id not in self.hidden_platform_ids
|
||||
and rom_id not in self.hidden_rom_ids
|
||||
)
|
||||
|
||||
|
||||
def _effective_group_id(user: User, *, session) -> int | None:
|
||||
"""The group a non-admin user follows: their own, else the server default.
|
||||
|
||||
Used by both the grant map and the hidden-entity lookup so a user with no
|
||||
explicit group still inherits the default group's grants AND its hides.
|
||||
"""
|
||||
|
||||
from handler.database import db_permission_handler
|
||||
|
||||
if user.permission_group_id is not None:
|
||||
return user.permission_group_id
|
||||
default_group = db_permission_handler.get_default_group(session=session)
|
||||
return default_group.id if default_group else None
|
||||
|
||||
|
||||
def _resolve_grant_map(
|
||||
user: User, *, session
|
||||
) -> dict[tuple[PermEntity, PermAction], bool]:
|
||||
"""Effective ``(entity, action) -> own_only`` map for a non-admin user."""
|
||||
|
||||
from handler.database import db_permission_handler
|
||||
|
||||
base: dict[tuple[PermEntity, PermAction], bool] = {}
|
||||
group_id = _effective_group_id(user, session=session)
|
||||
if group_id is not None:
|
||||
for g in db_permission_handler.get_group_grants(group_id, session=session):
|
||||
base[(g.entity, g.action)] = g.own_only
|
||||
|
||||
# Per-user overrides win over the group: grant adds, revoke removes.
|
||||
# Override identity is (entity, action) only, so a grant override fully
|
||||
# replaces the group's own_only for that key rather than merging. Both
|
||||
# directions are admin-initiated and the narrowing case fails closed, so
|
||||
# this is a granularity limit, not a privilege leak.
|
||||
if user.id is not None:
|
||||
for ov in db_permission_handler.get_user_overrides(user.id, session=session):
|
||||
if ov.granted:
|
||||
base[(ov.entity, ov.action)] = ov.own_only
|
||||
else:
|
||||
base.pop((ov.entity, ov.action), None)
|
||||
|
||||
return base
|
||||
|
||||
|
||||
def resolve_permissions(
|
||||
user: User,
|
||||
*,
|
||||
session=None, # type: ignore
|
||||
) -> ResolvedPermissions:
|
||||
# Admins bypass everything -- no DB access needed.
|
||||
if user.role == Role.ADMIN:
|
||||
return ResolvedPermissions(
|
||||
is_admin=True,
|
||||
user_id=user.id,
|
||||
grants=frozenset(),
|
||||
hidden_platform_ids=frozenset(),
|
||||
hidden_rom_ids=frozenset(),
|
||||
)
|
||||
return _resolve_non_admin(user, session=session)
|
||||
|
||||
|
||||
@begin_session
|
||||
def _resolve_non_admin(
|
||||
user: User,
|
||||
*,
|
||||
session=None, # type: ignore
|
||||
) -> ResolvedPermissions:
|
||||
from handler.database import db_permission_handler
|
||||
|
||||
grant_map = _resolve_grant_map(user, session=session)
|
||||
grants = frozenset(
|
||||
ResolvedGrant(entity, action, own_only)
|
||||
for (entity, action), own_only in grant_map.items()
|
||||
)
|
||||
# Kiosk mode locks every non-admin to read-only at the fine layer too, so a
|
||||
# mutating route gated only by `assert_can` (no coarse scope) stays blocked.
|
||||
if KIOSK_MODE:
|
||||
grants = frozenset(g for g in grants if g.action == PermAction.READ)
|
||||
|
||||
# Resolve the effective group (own or default) so hides assigned to the
|
||||
# default group apply to group-less users too, not just their grants.
|
||||
group_id = _effective_group_id(user, session=session)
|
||||
hidden_platforms = db_permission_handler.get_hidden_entity_ids(
|
||||
PermEntity.PLATFORMS, user.id, group_id, session=session
|
||||
)
|
||||
hidden_roms = db_permission_handler.get_hidden_entity_ids(
|
||||
PermEntity.ROMS, user.id, group_id, session=session
|
||||
)
|
||||
|
||||
return ResolvedPermissions(
|
||||
is_admin=False,
|
||||
user_id=user.id,
|
||||
grants=grants,
|
||||
hidden_platform_ids=frozenset(hidden_platforms),
|
||||
hidden_rom_ids=frozenset(hidden_roms),
|
||||
)
|
||||
|
||||
|
||||
def compute_oauth_scopes(
|
||||
user: User,
|
||||
*,
|
||||
session=None, # type: ignore
|
||||
) -> list[Scope]:
|
||||
"""Project a user's effective grants onto the coarse legacy ``Scope`` set.
|
||||
|
||||
Admins get the full set; ``KIOSK_MODE`` caps every non-admin user to
|
||||
read-only (the public-display lockdown).
|
||||
"""
|
||||
|
||||
# Admins bypass everything -- no DB access needed. Keep the canonical
|
||||
# FULL_SCOPES order (same as the non-admin path) to avoid token churn.
|
||||
if user.role == Role.ADMIN:
|
||||
return order_scopes(FULL_SCOPES)
|
||||
return _compute_non_admin_scopes(user, session=session)
|
||||
|
||||
|
||||
@begin_session
|
||||
def _compute_non_admin_scopes(
|
||||
user: User,
|
||||
*,
|
||||
session=None, # type: ignore
|
||||
) -> list[Scope]:
|
||||
grant_map = _resolve_grant_map(user, session=session)
|
||||
scopes = set(
|
||||
grants_to_scopes(
|
||||
(entity, action, own_only)
|
||||
for (entity, action), own_only in grant_map.items()
|
||||
)
|
||||
)
|
||||
# Only non-admins reach here (admins short-circuit above), so kiosk mode
|
||||
# locks all of them down to read-only.
|
||||
if KIOSK_MODE:
|
||||
scopes &= set(READ_SCOPES)
|
||||
return order_scopes(scopes)
|
||||
122
backend/handler/auth/permissions_map.py
Normal file
122
backend/handler/auth/permissions_map.py
Normal file
@@ -0,0 +1,122 @@
|
||||
"""Pure mapping between the granular permission model and legacy OAuth scopes.
|
||||
|
||||
Intentionally free of SQLAlchemy / FastAPI imports so it can be reused by both
|
||||
the runtime ``oauth_scopes`` projection (added in a later PR) and the unit tests
|
||||
that prove the migration backfill preserves every user's access.
|
||||
|
||||
The grant matrices below are the single source of truth for "what a legacy
|
||||
viewer/editor could do". ``grants_to_scopes`` projects a resolved grant set back
|
||||
onto the coarse ``Scope`` vocabulary. On day one the round-trip
|
||||
|
||||
role -> legacy grants -> projected scopes
|
||||
|
||||
must equal the user's pre-migration ``oauth_scopes`` exactly (verified by
|
||||
``tests/handler/auth/test_permissions_parity.py``). The Alembic migration that
|
||||
seeds the legacy groups inlines the SAME matrix as frozen literals; a test keeps
|
||||
the two in lockstep.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
|
||||
from handler.auth.constants import FULL_SCOPES, Scope
|
||||
from models.permission import PermAction, PermEntity
|
||||
|
||||
# (entity, action, own_only)
|
||||
Grant = tuple[PermEntity, PermAction, bool]
|
||||
|
||||
# Canonical scope ordering == the legacy READ -> WRITE -> EDIT -> FULL order
|
||||
# (each is a prefix of FULL_SCOPES). Ordering projected scopes this way
|
||||
# reproduces the exact list the old role-based `oauth_scopes` returned.
|
||||
_SCOPE_ORDER: dict[Scope, int] = {s: i for i, s in enumerate(FULL_SCOPES)}
|
||||
|
||||
|
||||
def order_scopes(scopes: Iterable[Scope]) -> list[Scope]:
|
||||
return sorted(scopes, key=lambda s: _SCOPE_ORDER[s])
|
||||
|
||||
|
||||
# Scopes granted unconditionally to any authenticated non-admin "user"
|
||||
# (self-service): own profile + own per-rom data (play status, notes, ratings).
|
||||
# These are never gated behind a group -- losing them would, e.g., stop a user
|
||||
# saving their own game progress.
|
||||
ALWAYS_ON_SCOPES: frozenset[Scope] = frozenset(
|
||||
{
|
||||
Scope.ME_READ,
|
||||
Scope.ME_WRITE,
|
||||
Scope.ROMS_USER_READ,
|
||||
Scope.ROMS_USER_WRITE,
|
||||
}
|
||||
)
|
||||
|
||||
# (entity, action) -> coarse scopes it projects to. DELETE projects to nothing:
|
||||
# there is no delete scope today (deletes gate on the matching *_WRITE scope),
|
||||
# so delete granularity lives only in the new fine-grained layer.
|
||||
_GRANT_SCOPES: dict[tuple[PermEntity, PermAction], frozenset[Scope]] = {
|
||||
(PermEntity.ROMS, PermAction.READ): frozenset({Scope.ROMS_READ}),
|
||||
(PermEntity.ROMS, PermAction.WRITE): frozenset({Scope.ROMS_WRITE}),
|
||||
(PermEntity.PLATFORMS, PermAction.READ): frozenset({Scope.PLATFORMS_READ}),
|
||||
(PermEntity.PLATFORMS, PermAction.WRITE): frozenset({Scope.PLATFORMS_WRITE}),
|
||||
(PermEntity.FIRMWARE, PermAction.READ): frozenset({Scope.FIRMWARE_READ}),
|
||||
(PermEntity.FIRMWARE, PermAction.WRITE): frozenset({Scope.FIRMWARE_WRITE}),
|
||||
(PermEntity.COLLECTIONS, PermAction.READ): frozenset({Scope.COLLECTIONS_READ}),
|
||||
(PermEntity.COLLECTIONS, PermAction.WRITE): frozenset({Scope.COLLECTIONS_WRITE}),
|
||||
(PermEntity.ASSETS, PermAction.READ): frozenset({Scope.ASSETS_READ}),
|
||||
(PermEntity.ASSETS, PermAction.WRITE): frozenset({Scope.ASSETS_WRITE}),
|
||||
(PermEntity.DEVICES, PermAction.READ): frozenset({Scope.DEVICES_READ}),
|
||||
(PermEntity.DEVICES, PermAction.WRITE): frozenset({Scope.DEVICES_WRITE}),
|
||||
(PermEntity.USERS, PermAction.READ): frozenset({Scope.USERS_READ}),
|
||||
(PermEntity.USERS, PermAction.WRITE): frozenset({Scope.USERS_WRITE}),
|
||||
(PermEntity.TASKS, PermAction.WRITE): frozenset({Scope.TASKS_RUN}),
|
||||
(PermEntity.LOGS, PermAction.READ): frozenset({Scope.LOGS_READ}),
|
||||
}
|
||||
|
||||
# --- Legacy group matrices ----------------------------------------------------
|
||||
# "Viewer (legacy)" == today's non-kiosk default user (WRITE_SCOPES): read the
|
||||
# library; create/modify/delete only OWN collections/assets/devices.
|
||||
LEGACY_VIEWER_GRANTS: tuple[Grant, ...] = (
|
||||
(PermEntity.ROMS, PermAction.READ, False),
|
||||
(PermEntity.PLATFORMS, PermAction.READ, False),
|
||||
(PermEntity.FIRMWARE, PermAction.READ, False),
|
||||
(PermEntity.COLLECTIONS, PermAction.READ, False),
|
||||
(PermEntity.COLLECTIONS, PermAction.WRITE, True),
|
||||
(PermEntity.COLLECTIONS, PermAction.DELETE, True),
|
||||
(PermEntity.ASSETS, PermAction.READ, False),
|
||||
(PermEntity.ASSETS, PermAction.WRITE, True),
|
||||
(PermEntity.ASSETS, PermAction.DELETE, True),
|
||||
(PermEntity.DEVICES, PermAction.READ, True),
|
||||
(PermEntity.DEVICES, PermAction.WRITE, True),
|
||||
(PermEntity.DEVICES, PermAction.DELETE, True),
|
||||
)
|
||||
|
||||
# "Editor (legacy)" == EDIT_SCOPES: viewer + library-wide write AND delete of
|
||||
# roms/platforms/firmware. Delete is True here because today's delete endpoints
|
||||
# gate on *_WRITE -- editors can already delete, so preserving that is required
|
||||
# to avoid silently revoking access on upgrade.
|
||||
_LEGACY_EDITOR_EXTRA: tuple[Grant, ...] = (
|
||||
(PermEntity.ROMS, PermAction.WRITE, False),
|
||||
(PermEntity.ROMS, PermAction.DELETE, False),
|
||||
(PermEntity.PLATFORMS, PermAction.WRITE, False),
|
||||
(PermEntity.PLATFORMS, PermAction.DELETE, False),
|
||||
(PermEntity.FIRMWARE, PermAction.WRITE, False),
|
||||
(PermEntity.FIRMWARE, PermAction.DELETE, False),
|
||||
)
|
||||
|
||||
LEGACY_EDITOR_GRANTS: tuple[Grant, ...] = LEGACY_VIEWER_GRANTS + _LEGACY_EDITOR_EXTRA
|
||||
|
||||
|
||||
def grants_to_scopes(grants: Iterable[Grant], *, is_admin: bool = False) -> list[Scope]:
|
||||
"""Project a resolved grant set onto the coarse legacy ``Scope`` vocabulary.
|
||||
|
||||
Admins always get the full set. For everyone else, the self-service
|
||||
``ALWAYS_ON_SCOPES`` are unioned with the scopes implied by each grant.
|
||||
Returned in canonical legacy READ -> WRITE -> EDIT -> FULL order.
|
||||
"""
|
||||
|
||||
if is_admin:
|
||||
return list(FULL_SCOPES)
|
||||
|
||||
out: set[Scope] = set(ALWAYS_ON_SCOPES)
|
||||
for entity, action, _own_only in grants:
|
||||
out |= _GRANT_SCOPES.get((entity, action), frozenset())
|
||||
return order_scopes(out)
|
||||
@@ -3,6 +3,7 @@ from .collections_handler import DBCollectionsHandler
|
||||
from .device_save_sync_handler import DBDeviceSaveSyncHandler
|
||||
from .devices_handler import DBDevicesHandler
|
||||
from .firmware_handler import DBFirmwareHandler
|
||||
from .permissions_handler import DBPermissionsHandler
|
||||
from .platforms_handler import DBPlatformsHandler
|
||||
from .play_sessions_handler import DBPlaySessionsHandler
|
||||
from .roms_handler import DBRomsHandler
|
||||
@@ -18,6 +19,7 @@ db_collection_handler = DBCollectionsHandler()
|
||||
db_device_handler = DBDevicesHandler()
|
||||
db_device_save_sync_handler = DBDeviceSaveSyncHandler()
|
||||
db_firmware_handler = DBFirmwareHandler()
|
||||
db_permission_handler = DBPermissionsHandler()
|
||||
db_platform_handler = DBPlatformsHandler()
|
||||
db_play_session_handler = DBPlaySessionsHandler()
|
||||
db_rom_handler = DBRomsHandler()
|
||||
|
||||
@@ -33,6 +33,7 @@ class DBFirmwareHandler(DBBaseHandler):
|
||||
*,
|
||||
platform_id: int | None = None,
|
||||
only_fields: Sequence[QueryableAttribute] | None = None,
|
||||
hidden_platform_ids: Sequence[int] | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[Firmware]:
|
||||
query = select(Firmware).order_by(Firmware.file_name.asc())
|
||||
@@ -40,6 +41,11 @@ class DBFirmwareHandler(DBBaseHandler):
|
||||
if platform_id:
|
||||
query = query.filter_by(platform_id=platform_id)
|
||||
|
||||
# Firmware inherits its platform's visibility: hide firmware whose
|
||||
# platform an admin has hidden from the caller.
|
||||
if hidden_platform_ids:
|
||||
query = query.filter(Firmware.platform_id.not_in(hidden_platform_ids))
|
||||
|
||||
if only_fields:
|
||||
query = query.options(load_only(*only_fields))
|
||||
|
||||
|
||||
325
backend/handler/database/permissions_handler.py
Normal file
325
backend/handler/database/permissions_handler.py
Normal file
@@ -0,0 +1,325 @@
|
||||
from collections.abc import Iterable, Sequence
|
||||
|
||||
from sqlalchemy import and_, delete, or_, select, update
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from decorators.database import begin_session
|
||||
from models.permission import (
|
||||
HiddenEntity,
|
||||
PermAction,
|
||||
PermEntity,
|
||||
PermissionGroup,
|
||||
PermissionGroupGrant,
|
||||
UserPermissionOverride,
|
||||
)
|
||||
from models.user import User
|
||||
|
||||
from .base_handler import DBBaseHandler
|
||||
|
||||
# (entity, action, own_only)
|
||||
GrantTuple = tuple[PermEntity, PermAction, bool]
|
||||
# (entity, action, granted, own_only)
|
||||
OverrideTuple = tuple[PermEntity, PermAction, bool, bool]
|
||||
|
||||
|
||||
class DBPermissionsHandler(DBBaseHandler):
|
||||
"""Read and admin-write access to the granular permission model.
|
||||
|
||||
The read helpers (`get_default_group`, `get_group_grants`,
|
||||
`get_user_overrides`, `get_hidden_entity_ids`) feed the per-request resolver;
|
||||
the rest is the admin CRUD surface for managing groups, memberships,
|
||||
overrides and hidden entities.
|
||||
"""
|
||||
|
||||
@begin_session
|
||||
def get_default_group(
|
||||
self,
|
||||
session: Session = None, # type: ignore
|
||||
) -> PermissionGroup | None:
|
||||
return session.scalar(
|
||||
select(PermissionGroup).filter_by(is_default=True).limit(1)
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_group_grants(
|
||||
self,
|
||||
group_id: int,
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[PermissionGroupGrant]:
|
||||
return session.scalars(
|
||||
select(PermissionGroupGrant).filter_by(group_id=group_id)
|
||||
).all()
|
||||
|
||||
@begin_session
|
||||
def get_user_overrides(
|
||||
self,
|
||||
user_id: int,
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[UserPermissionOverride]:
|
||||
return session.scalars(
|
||||
select(UserPermissionOverride).filter_by(user_id=user_id)
|
||||
).all()
|
||||
|
||||
@begin_session
|
||||
def get_hidden_entity_ids(
|
||||
self,
|
||||
entity: PermEntity,
|
||||
user_id: int | None,
|
||||
group_id: int | None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> set[int]:
|
||||
"""Ids of `entity` hidden from the given user OR their group.
|
||||
|
||||
Cascade (a hidden platform hiding its roms/firmware) is applied at query
|
||||
time by the consuming handlers, not here.
|
||||
"""
|
||||
principals = []
|
||||
if user_id is not None:
|
||||
principals.append(HiddenEntity.user_id == user_id)
|
||||
if group_id is not None:
|
||||
principals.append(HiddenEntity.group_id == group_id)
|
||||
if not principals:
|
||||
return set()
|
||||
|
||||
rows = session.scalars(
|
||||
select(HiddenEntity.entity_id).where(
|
||||
HiddenEntity.entity == entity, or_(*principals)
|
||||
)
|
||||
).all()
|
||||
return set(rows)
|
||||
|
||||
# --- Admin CRUD: groups ---------------------------------------------------
|
||||
|
||||
@begin_session
|
||||
def get_groups(
|
||||
self,
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[PermissionGroup]:
|
||||
return (
|
||||
session.scalars(select(PermissionGroup).order_by(PermissionGroup.name))
|
||||
.unique()
|
||||
.all()
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_group(
|
||||
self,
|
||||
group_id: int,
|
||||
session: Session = None, # type: ignore
|
||||
) -> PermissionGroup | None:
|
||||
return session.get(PermissionGroup, group_id)
|
||||
|
||||
@begin_session
|
||||
def get_group_by_name(
|
||||
self,
|
||||
name: str,
|
||||
session: Session = None, # type: ignore
|
||||
) -> PermissionGroup | None:
|
||||
return session.scalar(select(PermissionGroup).filter_by(name=name).limit(1))
|
||||
|
||||
@begin_session
|
||||
def create_group(
|
||||
self,
|
||||
name: str,
|
||||
description: str = "",
|
||||
is_default: bool = False,
|
||||
color: str | None = None,
|
||||
grants: Iterable[GrantTuple] = (),
|
||||
session: Session = None, # type: ignore
|
||||
) -> PermissionGroup:
|
||||
group = PermissionGroup(
|
||||
name=name,
|
||||
description=description,
|
||||
is_default=is_default,
|
||||
color=color,
|
||||
is_system=False,
|
||||
)
|
||||
session.add(group)
|
||||
session.flush()
|
||||
self._replace_group_grants(group.id, grants, session=session)
|
||||
if is_default:
|
||||
self._clear_other_defaults(group.id, session=session)
|
||||
session.refresh(group)
|
||||
return group
|
||||
|
||||
@begin_session
|
||||
def update_group(
|
||||
self,
|
||||
group_id: int,
|
||||
*,
|
||||
name: str | None = None,
|
||||
description: str | None = None,
|
||||
is_default: bool | None = None,
|
||||
color: str | None = None,
|
||||
grants: Iterable[GrantTuple] | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> PermissionGroup | None:
|
||||
group = session.get(PermissionGroup, group_id)
|
||||
if group is None:
|
||||
return None
|
||||
if name is not None:
|
||||
group.name = name
|
||||
if description is not None:
|
||||
group.description = description
|
||||
if color is not None:
|
||||
group.color = color
|
||||
if is_default is not None:
|
||||
group.is_default = is_default
|
||||
if is_default:
|
||||
self._clear_other_defaults(group_id, session=session)
|
||||
if grants is not None:
|
||||
self._replace_group_grants(group_id, grants, session=session)
|
||||
session.flush()
|
||||
session.refresh(group)
|
||||
return group
|
||||
|
||||
@begin_session
|
||||
def delete_group(
|
||||
self,
|
||||
group_id: int,
|
||||
session: Session = None, # type: ignore
|
||||
) -> None:
|
||||
session.execute(delete(PermissionGroup).where(PermissionGroup.id == group_id))
|
||||
|
||||
def _replace_group_grants(
|
||||
self, group_id: int, grants: Iterable[GrantTuple], *, session: Session
|
||||
) -> None:
|
||||
session.execute(
|
||||
delete(PermissionGroupGrant).where(
|
||||
PermissionGroupGrant.group_id == group_id
|
||||
)
|
||||
)
|
||||
for entity, action, own_only in grants:
|
||||
session.add(
|
||||
PermissionGroupGrant(
|
||||
group_id=group_id, entity=entity, action=action, own_only=own_only
|
||||
)
|
||||
)
|
||||
session.flush()
|
||||
|
||||
def _clear_other_defaults(self, keep_id: int, *, session: Session) -> None:
|
||||
session.execute(
|
||||
update(PermissionGroup)
|
||||
.where(PermissionGroup.id != keep_id, PermissionGroup.is_default.is_(True))
|
||||
.values(is_default=False)
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_group_member_ids(
|
||||
self,
|
||||
group_id: int,
|
||||
session: Session = None, # type: ignore
|
||||
) -> list[int]:
|
||||
return list(
|
||||
session.scalars(
|
||||
select(User.id).where(User.permission_group_id == group_id)
|
||||
).all()
|
||||
)
|
||||
|
||||
# --- Admin CRUD: user membership + overrides ------------------------------
|
||||
|
||||
@begin_session
|
||||
def set_user_group(
|
||||
self,
|
||||
user_id: int,
|
||||
group_id: int | None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> None:
|
||||
session.execute(
|
||||
update(User)
|
||||
.where(User.id == user_id)
|
||||
.values(permission_group_id=group_id)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def replace_user_overrides(
|
||||
self,
|
||||
user_id: int,
|
||||
overrides: Iterable[OverrideTuple],
|
||||
session: Session = None, # type: ignore
|
||||
) -> None:
|
||||
session.execute(
|
||||
delete(UserPermissionOverride).where(
|
||||
UserPermissionOverride.user_id == user_id
|
||||
)
|
||||
)
|
||||
for entity, action, granted, own_only in overrides:
|
||||
session.add(
|
||||
UserPermissionOverride(
|
||||
user_id=user_id,
|
||||
entity=entity,
|
||||
action=action,
|
||||
granted=granted,
|
||||
own_only=own_only,
|
||||
)
|
||||
)
|
||||
|
||||
# --- Admin CRUD: hidden entities ------------------------------------------
|
||||
|
||||
@begin_session
|
||||
def get_hidden_entities(
|
||||
self,
|
||||
*,
|
||||
user_id: int | None = None,
|
||||
group_id: int | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[HiddenEntity]:
|
||||
query = select(HiddenEntity)
|
||||
if user_id is not None:
|
||||
query = query.filter_by(user_id=user_id)
|
||||
if group_id is not None:
|
||||
query = query.filter_by(group_id=group_id)
|
||||
return session.scalars(query).all()
|
||||
|
||||
@begin_session
|
||||
def add_hidden_entity(
|
||||
self,
|
||||
entity: PermEntity,
|
||||
entity_id: int,
|
||||
*,
|
||||
user_id: int | None = None,
|
||||
group_id: int | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> None:
|
||||
# Idempotent: a repeated hide is a no-op rather than a unique violation.
|
||||
existing = session.scalar(
|
||||
select(HiddenEntity)
|
||||
.filter_by(
|
||||
entity=entity,
|
||||
entity_id=entity_id,
|
||||
user_id=user_id,
|
||||
group_id=group_id,
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
if existing is None:
|
||||
session.add(
|
||||
HiddenEntity(
|
||||
entity=entity,
|
||||
entity_id=entity_id,
|
||||
user_id=user_id,
|
||||
group_id=group_id,
|
||||
)
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def remove_hidden_entity(
|
||||
self,
|
||||
entity: PermEntity,
|
||||
entity_id: int,
|
||||
*,
|
||||
user_id: int | None = None,
|
||||
group_id: int | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> None:
|
||||
session.execute(
|
||||
delete(HiddenEntity).where(
|
||||
and_(
|
||||
HiddenEntity.entity == entity,
|
||||
HiddenEntity.entity_id == entity_id,
|
||||
HiddenEntity.user_id == user_id,
|
||||
HiddenEntity.group_id == group_id,
|
||||
)
|
||||
)
|
||||
)
|
||||
@@ -68,12 +68,18 @@ class DBPlatformsHandler(DBBaseHandler):
|
||||
self,
|
||||
updated_after: datetime | None = None,
|
||||
only_fields: Sequence[QueryableAttribute] | None = None,
|
||||
hidden_platform_ids: Sequence[int] | None = None,
|
||||
query: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[Platform]:
|
||||
if updated_after:
|
||||
query = query.filter(Platform.updated_at > updated_after)
|
||||
|
||||
# Admin-driven visibility (opt-out): exclude platforms hidden from the
|
||||
# caller. Empty/None (e.g. admins) skips filtering.
|
||||
if hidden_platform_ids:
|
||||
query = query.filter(Platform.id.not_in(hidden_platform_ids))
|
||||
|
||||
if only_fields:
|
||||
query = query.options(load_only(*only_fields))
|
||||
|
||||
|
||||
@@ -303,18 +303,21 @@ class DBRomsHandler(DBBaseHandler):
|
||||
user_id: int,
|
||||
*,
|
||||
session: Session,
|
||||
hidden_platform_ids: Sequence[int] | None = None,
|
||||
hidden_rom_ids: Sequence[int] | None = None,
|
||||
) -> dict[int, list[tuple[Rom, bool]]]:
|
||||
"""Return {rom_id: [(sibling Rom, is_main_sibling), ...]} in a single query.
|
||||
|
||||
Joins sibling_roms → roms (only the columns SiblingRomSchema needs) and
|
||||
left-joins rom_user for the requesting user, so the per-user
|
||||
`is_main_sibling` flag is resolved without hydrating the wide roms table
|
||||
or its JSON metadata on every page.
|
||||
or its JSON metadata on every page. Siblings hidden from the caller
|
||||
(their platform or the sibling itself) are excluded.
|
||||
"""
|
||||
if not rom_ids:
|
||||
return {}
|
||||
|
||||
rows = session.execute(
|
||||
query = (
|
||||
select(
|
||||
SiblingRom.rom_id,
|
||||
Rom,
|
||||
@@ -338,7 +341,13 @@ class DBRomsHandler(DBBaseHandler):
|
||||
Rom.fs_name_no_ext,
|
||||
)
|
||||
)
|
||||
).all()
|
||||
)
|
||||
if hidden_platform_ids:
|
||||
query = query.where(Rom.platform_id.not_in(hidden_platform_ids))
|
||||
if hidden_rom_ids:
|
||||
query = query.where(Rom.id.not_in(hidden_rom_ids))
|
||||
|
||||
rows = session.execute(query).all()
|
||||
|
||||
# Dedupe by (parent rom, sibling id) so a duplicate join row doesn't
|
||||
# surface the same sibling twice on the wire.
|
||||
@@ -777,6 +786,8 @@ class DBRomsHandler(DBBaseHandler):
|
||||
updated_after: datetime | None = None,
|
||||
include_file_stats: bool = False,
|
||||
include_files: bool = False,
|
||||
hidden_platform_ids: Sequence[int] | None = None,
|
||||
hidden_rom_ids: Sequence[int] | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> Query[Rom]:
|
||||
from handler.scan_handler import MetadataSource
|
||||
@@ -1030,6 +1041,14 @@ class DBRomsHandler(DBBaseHandler):
|
||||
or_(RomUser.hidden.is_(False), RomUser.hidden.is_(None))
|
||||
)
|
||||
|
||||
# Admin-driven visibility (opt-out): hide platforms/roms an admin has
|
||||
# hidden from this user/group. Orthogonal to the personal RomUser.hidden
|
||||
# toggle above. Empty sets (e.g. admins) skip filtering entirely.
|
||||
if hidden_platform_ids:
|
||||
query = query.filter(Rom.platform_id.not_in(hidden_platform_ids))
|
||||
if hidden_rom_ids:
|
||||
query = query.filter(Rom.id.not_in(hidden_rom_ids))
|
||||
|
||||
return query
|
||||
|
||||
@begin_session
|
||||
@@ -1149,9 +1168,32 @@ class DBRomsHandler(DBBaseHandler):
|
||||
user_id=kwargs.get("user_id", None),
|
||||
group_by_meta_id=kwargs.get("group_by_meta_id", False),
|
||||
include_files=kwargs.get("include_files", False),
|
||||
hidden_platform_ids=kwargs.get("hidden_platform_ids", None),
|
||||
hidden_rom_ids=kwargs.get("hidden_rom_ids", None),
|
||||
)
|
||||
return session.scalars(roms).all()
|
||||
|
||||
@begin_session
|
||||
def get_hidden_rom_ids_among(
|
||||
self,
|
||||
rom_ids: Sequence[int],
|
||||
hidden_platform_ids: Sequence[int] | None,
|
||||
hidden_rom_ids: Sequence[int] | None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> set[int]:
|
||||
"""Of `rom_ids`, the subset hidden from the caller (own hide or platform)."""
|
||||
candidates = set(rom_ids)
|
||||
hide: set[int] = candidates & set(hidden_rom_ids or [])
|
||||
if hidden_platform_ids and candidates:
|
||||
rows = session.scalars(
|
||||
select(Rom.id).where(
|
||||
Rom.id.in_(candidates),
|
||||
Rom.platform_id.in_(hidden_platform_ids),
|
||||
)
|
||||
).all()
|
||||
hide.update(rows)
|
||||
return hide
|
||||
|
||||
@begin_session
|
||||
def with_char_index(
|
||||
self,
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
from sqlalchemy import distinct, func, select
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.sql.selectable import Select
|
||||
|
||||
from decorators.database import begin_session
|
||||
from endpoints.responses.stats import MetadataCoverageItem, RegionBreakdownItem
|
||||
@@ -11,26 +14,48 @@ from models.rom import METADATA_SOURCE_COLUMNS, Rom, RomFile
|
||||
from .base_handler import DBBaseHandler
|
||||
|
||||
|
||||
def _exclude_hidden(
|
||||
query: Select,
|
||||
hidden_platform_ids: Sequence[int] | None,
|
||||
hidden_rom_ids: Sequence[int] | None,
|
||||
) -> Select:
|
||||
"""Drop rows for platforms/roms hidden from the caller (admins pass None)."""
|
||||
if hidden_platform_ids:
|
||||
query = query.where(Rom.platform_id.not_in(hidden_platform_ids))
|
||||
if hidden_rom_ids:
|
||||
query = query.where(Rom.id.not_in(hidden_rom_ids))
|
||||
return query
|
||||
|
||||
|
||||
class DBStatsHandler(DBBaseHandler):
|
||||
@begin_session
|
||||
def get_platforms_count(
|
||||
self,
|
||||
hidden_platform_ids: Sequence[int] | None = None,
|
||||
hidden_rom_ids: Sequence[int] | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> int:
|
||||
"""Get the number of platforms with any roms."""
|
||||
return (
|
||||
session.scalar(
|
||||
select(func.count(distinct(Rom.platform_id))).select_from(Rom)
|
||||
)
|
||||
or 0
|
||||
query = _exclude_hidden(
|
||||
select(func.count(distinct(Rom.platform_id))).select_from(Rom),
|
||||
hidden_platform_ids,
|
||||
hidden_rom_ids,
|
||||
)
|
||||
return session.scalar(query) or 0
|
||||
|
||||
@begin_session
|
||||
def get_roms_count(
|
||||
self,
|
||||
hidden_platform_ids: Sequence[int] | None = None,
|
||||
hidden_rom_ids: Sequence[int] | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> int:
|
||||
return session.scalar(select(func.count()).select_from(Rom)) or 0
|
||||
query = _exclude_hidden(
|
||||
select(func.count()).select_from(Rom),
|
||||
hidden_platform_ids,
|
||||
hidden_rom_ids,
|
||||
)
|
||||
return session.scalar(query) or 0
|
||||
|
||||
@begin_session
|
||||
def get_saves_count(
|
||||
@@ -56,15 +81,17 @@ class DBStatsHandler(DBBaseHandler):
|
||||
@begin_session
|
||||
def get_total_filesize(
|
||||
self,
|
||||
hidden_platform_ids: Sequence[int] | None = None,
|
||||
hidden_rom_ids: Sequence[int] | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> int:
|
||||
"""Get the total filesize of all roms in the database, in bytes."""
|
||||
return (
|
||||
session.scalar(
|
||||
select(func.sum(RomFile.file_size_bytes)).select_from(RomFile)
|
||||
query = select(func.sum(RomFile.file_size_bytes)).select_from(RomFile)
|
||||
if hidden_platform_ids or hidden_rom_ids:
|
||||
query = _exclude_hidden(
|
||||
query.join(Rom), hidden_platform_ids, hidden_rom_ids
|
||||
)
|
||||
or 0
|
||||
)
|
||||
return session.scalar(query) or 0
|
||||
|
||||
@begin_session
|
||||
def get_platform_filesize(
|
||||
@@ -86,19 +113,23 @@ class DBStatsHandler(DBBaseHandler):
|
||||
@begin_session
|
||||
def get_metadata_coverage_by_platform(
|
||||
self,
|
||||
hidden_platform_ids: Sequence[int] | None = None,
|
||||
hidden_rom_ids: Sequence[int] | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> dict[int, list[MetadataCoverageItem]]:
|
||||
"""Get the count of ROMs matched per metadata source, grouped by platform."""
|
||||
rows = session.execute(
|
||||
select(
|
||||
Rom.platform_id,
|
||||
*(
|
||||
func.count(col).label(key)
|
||||
for key, col in METADATA_SOURCE_COLUMNS.items()
|
||||
),
|
||||
)
|
||||
.select_from(Rom)
|
||||
.group_by(Rom.platform_id)
|
||||
_exclude_hidden(
|
||||
select(
|
||||
Rom.platform_id,
|
||||
*(
|
||||
func.count(col).label(key)
|
||||
for key, col in METADATA_SOURCE_COLUMNS.items()
|
||||
),
|
||||
).select_from(Rom),
|
||||
hidden_platform_ids,
|
||||
hidden_rom_ids,
|
||||
).group_by(Rom.platform_id)
|
||||
).all()
|
||||
|
||||
result: dict[int, list[MetadataCoverageItem]] = {}
|
||||
@@ -114,11 +145,17 @@ class DBStatsHandler(DBBaseHandler):
|
||||
@begin_session
|
||||
def get_region_breakdown_by_platform(
|
||||
self,
|
||||
hidden_platform_ids: Sequence[int] | None = None,
|
||||
hidden_rom_ids: Sequence[int] | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> dict[int, list[RegionBreakdownItem]]:
|
||||
"""Get the count of ROMs per region, grouped by platform."""
|
||||
rows = session.execute(
|
||||
select(Rom.platform_id, Rom.regions).where(Rom.regions.is_not(None))
|
||||
_exclude_hidden(
|
||||
select(Rom.platform_id, Rom.regions).where(Rom.regions.is_not(None)),
|
||||
hidden_platform_ids,
|
||||
hidden_rom_ids,
|
||||
)
|
||||
).all()
|
||||
|
||||
counter: dict[int, dict[str, int]] = {}
|
||||
|
||||
@@ -40,6 +40,7 @@ from endpoints.firmware import router as firmware_router
|
||||
from endpoints.heartbeat import router as heartbeat_router
|
||||
from endpoints.logs import router as logs_router
|
||||
from endpoints.netplay import router as netplay_router
|
||||
from endpoints.permissions import router as permissions_router
|
||||
from endpoints.platform import router as platform_router
|
||||
from endpoints.play_sessions import router as play_sessions_router
|
||||
from endpoints.raw import router as raw_router
|
||||
@@ -173,6 +174,7 @@ app.include_router(firmware_router, prefix="/api")
|
||||
app.include_router(collections_router, prefix="/api")
|
||||
app.include_router(export_router, prefix="/api")
|
||||
app.include_router(netplay_router, prefix="/api")
|
||||
app.include_router(permissions_router, prefix="/api")
|
||||
|
||||
app.mount("/ws", socket_handler.socket_app)
|
||||
app.mount("/netplay", netplay_socket_handler.socket_app)
|
||||
|
||||
171
backend/models/permission.py
Normal file
171
backend/models/permission.py
Normal file
@@ -0,0 +1,171 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
CheckConstraint,
|
||||
Enum,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
String,
|
||||
UniqueConstraint,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from models.base import BaseModel
|
||||
|
||||
|
||||
class PermEntity(enum.StrEnum):
|
||||
"""Entity-type vocabulary for granular permissions.
|
||||
|
||||
Mirrors the coarse scope domains (see ``handler/auth/constants.py``) so the
|
||||
grant matrix can be projected back onto the legacy ``Scope`` set without
|
||||
drift (see ``handler/auth/permissions_map.py``).
|
||||
"""
|
||||
|
||||
PLATFORMS = "platforms"
|
||||
ROMS = "roms"
|
||||
COLLECTIONS = "collections"
|
||||
FIRMWARE = "firmware"
|
||||
ASSETS = "assets"
|
||||
DEVICES = "devices"
|
||||
USERS = "users"
|
||||
TASKS = "tasks"
|
||||
LOGS = "logs"
|
||||
|
||||
|
||||
class PermAction(enum.StrEnum):
|
||||
READ = "read"
|
||||
WRITE = "write"
|
||||
DELETE = "delete"
|
||||
|
||||
|
||||
def _str_enum(enum_cls: type[enum.StrEnum], length: int) -> Enum:
|
||||
"""A VARCHAR-backed enum that stores the member ``value`` (lowercase).
|
||||
|
||||
``native_enum=False`` keeps the column portable across SQLite/MariaDB/
|
||||
Postgres and free of destructive ``ALTER TYPE`` when the vocabulary grows.
|
||||
``values_callable`` stores the lowercase ``.value`` rather than the
|
||||
uppercase member name, matching the API/permission vocabulary.
|
||||
"""
|
||||
|
||||
return Enum(
|
||||
enum_cls,
|
||||
native_enum=False,
|
||||
length=length,
|
||||
values_callable=lambda e: [m.value for m in e],
|
||||
)
|
||||
|
||||
|
||||
class PermissionGroup(BaseModel):
|
||||
"""A named permission template that users belong to.
|
||||
|
||||
A group carries a read/write/delete matrix over entity types (its
|
||||
``grants``). Exactly one group is the server-wide default (``is_default``)
|
||||
applied to new users. ``is_system`` marks the auto-created legacy groups so
|
||||
the admin UI can warn before editing/deleting them.
|
||||
"""
|
||||
|
||||
__tablename__ = "permission_groups"
|
||||
__table_args__ = {"extend_existing": True}
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(255), unique=True, index=True)
|
||||
description: Mapped[str] = mapped_column(String(1000), default="")
|
||||
is_default: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
|
||||
is_system: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
# Optional hex color (e.g. "#7c5cff") used by the admin UI to render the
|
||||
# group as a colored pill/dot. NULL falls back to a neutral tone.
|
||||
color: Mapped[str | None] = mapped_column(String(9), nullable=True)
|
||||
|
||||
grants: Mapped[list[PermissionGroupGrant]] = relationship(
|
||||
back_populates="group",
|
||||
cascade="all, delete-orphan",
|
||||
lazy="selectin",
|
||||
)
|
||||
|
||||
|
||||
class PermissionGroupGrant(BaseModel):
|
||||
"""A single ``(entity, action)`` capability granted by a group.
|
||||
|
||||
Absence of a row means "not granted". ``own_only`` restricts the grant to
|
||||
entities the user owns (e.g. manage OWN collections/saves) -- the actual
|
||||
ownership check happens in the resolver, this flag only widens the coarse
|
||||
surface enough for the action to appear.
|
||||
"""
|
||||
|
||||
__tablename__ = "permission_group_grants"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("group_id", "entity", "action", name="uq_group_grant"),
|
||||
{"extend_existing": True},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
group_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("permission_groups.id", ondelete="CASCADE"), index=True
|
||||
)
|
||||
entity: Mapped[PermEntity] = mapped_column(_str_enum(PermEntity, 20))
|
||||
action: Mapped[PermAction] = mapped_column(_str_enum(PermAction, 10))
|
||||
own_only: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
group: Mapped[PermissionGroup] = relationship(back_populates="grants")
|
||||
|
||||
|
||||
class UserPermissionOverride(BaseModel):
|
||||
"""A per-user add/revoke applied on top of the user's group matrix.
|
||||
|
||||
``granted=True`` adds a capability the group lacks; ``granted=False``
|
||||
revokes one the group provides. Absence of a row defers to the group.
|
||||
"""
|
||||
|
||||
__tablename__ = "user_permission_overrides"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("user_id", "entity", "action", name="uq_user_override"),
|
||||
{"extend_existing": True},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
user_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="CASCADE"), index=True
|
||||
)
|
||||
entity: Mapped[PermEntity] = mapped_column(_str_enum(PermEntity, 20))
|
||||
action: Mapped[PermAction] = mapped_column(_str_enum(PermAction, 10))
|
||||
granted: Mapped[bool] = mapped_column(Boolean)
|
||||
own_only: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
|
||||
class HiddenEntity(BaseModel):
|
||||
"""An opt-out visibility row: hide a specific entity from a user or group.
|
||||
|
||||
Exactly one principal is set (``user_id`` XOR ``group_id``). Practically
|
||||
only platforms and roms are hidden; firmware is excluded via the platform
|
||||
cascade computed at query time, never materialized here.
|
||||
"""
|
||||
|
||||
__tablename__ = "hidden_entities"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"entity", "entity_id", "user_id", "group_id", name="uq_hidden_entity"
|
||||
),
|
||||
CheckConstraint(
|
||||
"(user_id IS NULL) <> (group_id IS NULL)",
|
||||
name="ck_hidden_one_principal",
|
||||
),
|
||||
Index("idx_hidden_user_lookup", "user_id", "entity"),
|
||||
Index("idx_hidden_group_lookup", "group_id", "entity"),
|
||||
{"extend_existing": True},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
entity: Mapped[PermEntity] = mapped_column(_str_enum(PermEntity, 20))
|
||||
entity_id: Mapped[int] = mapped_column(Integer, index=True)
|
||||
user_id: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="CASCADE"), nullable=True, index=True
|
||||
)
|
||||
group_id: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("permission_groups.id", ondelete="CASCADE"),
|
||||
nullable=True,
|
||||
index=True,
|
||||
)
|
||||
@@ -4,19 +4,13 @@ import enum
|
||||
from datetime import datetime, timezone
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from sqlalchemy import TIMESTAMP, Enum, String
|
||||
from sqlalchemy import TIMESTAMP, Enum, ForeignKey, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from starlette.authentication import SimpleUser
|
||||
|
||||
from config import KIOSK_MODE
|
||||
from handler.auth.constants import (
|
||||
EDIT_SCOPES,
|
||||
FULL_SCOPES,
|
||||
READ_SCOPES,
|
||||
WRITE_SCOPES,
|
||||
Scope,
|
||||
)
|
||||
from handler.auth.constants import Scope
|
||||
from models.base import BaseModel
|
||||
from models.permission import PermissionGroup
|
||||
from utils.database import CustomJSON
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -28,11 +22,20 @@ if TYPE_CHECKING:
|
||||
from models.rom import RomNote, RomUser
|
||||
|
||||
|
||||
class Role(enum.Enum):
|
||||
VIEWER = "viewer"
|
||||
EDITOR = "editor"
|
||||
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
|
||||
|
||||
@@ -53,7 +56,24 @@ class User(BaseModel, SimpleUser):
|
||||
String(length=TEXT_FIELD_LENGTH), unique=True, index=True
|
||||
)
|
||||
enabled: Mapped[bool] = mapped_column(default=True)
|
||||
role: Mapped[Role] = mapped_column(Enum(Role), default=Role.VIEWER)
|
||||
# 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,
|
||||
)
|
||||
avatar_path: Mapped[str] = mapped_column(
|
||||
String(length=TEXT_FIELD_LENGTH), default=""
|
||||
)
|
||||
@@ -91,6 +111,9 @@ class User(BaseModel, SimpleUser):
|
||||
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:
|
||||
@@ -98,7 +121,7 @@ class User(BaseModel, SimpleUser):
|
||||
return cls(
|
||||
id=-1,
|
||||
username="kiosk",
|
||||
role=Role.VIEWER,
|
||||
role=Role.USER,
|
||||
enabled=True,
|
||||
avatar_path="",
|
||||
last_active=now,
|
||||
@@ -109,16 +132,13 @@ class User(BaseModel, SimpleUser):
|
||||
|
||||
@property
|
||||
def oauth_scopes(self) -> list[Scope]:
|
||||
if self.role == Role.ADMIN:
|
||||
return FULL_SCOPES
|
||||
# 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
|
||||
|
||||
if self.role == Role.EDITOR:
|
||||
return EDIT_SCOPES
|
||||
|
||||
if KIOSK_MODE:
|
||||
return READ_SCOPES
|
||||
|
||||
return WRITE_SCOPES
|
||||
return compute_oauth_scopes(self)
|
||||
|
||||
@property
|
||||
def fs_safe_folder_name(self):
|
||||
|
||||
@@ -14,6 +14,7 @@ from config.config_manager import ConfigManager
|
||||
from handler.auth import auth_handler
|
||||
from handler.auth.base_handler import ALGORITHM, oct_key
|
||||
from handler.database import (
|
||||
db_permission_handler,
|
||||
db_platform_handler,
|
||||
db_rom_handler,
|
||||
db_save_handler,
|
||||
@@ -276,20 +277,25 @@ def admin_user():
|
||||
|
||||
@pytest.fixture
|
||||
def editor_user():
|
||||
# role collapses to `user`; editor-level access now comes from the group.
|
||||
group = db_permission_handler.get_group_by_name("Editor (legacy)")
|
||||
user = User(
|
||||
username="test_editor",
|
||||
hashed_password=auth_handler.get_password_hash("test_editor_password"),
|
||||
role=Role.EDITOR,
|
||||
role=Role.USER,
|
||||
permission_group_id=group.id if group else None,
|
||||
)
|
||||
return db_user_handler.add_user(user)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def viewer_user():
|
||||
group = db_permission_handler.get_group_by_name("Viewer (legacy)")
|
||||
user = User(
|
||||
username="test_viewer",
|
||||
hashed_password=auth_handler.get_password_hash("test_viewer_password"),
|
||||
role=Role.VIEWER,
|
||||
role=Role.USER,
|
||||
permission_group_id=group.id if group else None,
|
||||
)
|
||||
return db_user_handler.add_user(user)
|
||||
|
||||
|
||||
@@ -261,8 +261,8 @@ class TestClientTokenAuth:
|
||||
)
|
||||
raw_token = create_resp.json()["raw_token"]
|
||||
|
||||
# Demote user to viewer
|
||||
db_user_handler.update_user(admin_user.id, {"role": Role.VIEWER})
|
||||
# Demote admin to a regular user
|
||||
db_user_handler.update_user(admin_user.id, {"role": Role.USER})
|
||||
|
||||
# users.write should no longer be effective
|
||||
response = client.get(
|
||||
|
||||
@@ -55,7 +55,7 @@ def test_get_user(client, access_token: str, editor_user: User):
|
||||
assert user["username"] == "test_editor"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("new_user_role", [Role.VIEWER, Role.EDITOR, Role.ADMIN])
|
||||
@pytest.mark.parametrize("new_user_role", [Role.USER, Role.ADMIN])
|
||||
def test_add_user_from_admin_user(client, access_token: str, new_user_role: Role):
|
||||
response = client.post(
|
||||
"/api/users",
|
||||
@@ -113,7 +113,7 @@ def test_add_user_from_unauthorized_user(
|
||||
"username": "new_user",
|
||||
"password": "new_user_password",
|
||||
"email": "new_user@example.com",
|
||||
"role": Role.VIEWER.value,
|
||||
"role": Role.USER.value,
|
||||
},
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
@@ -127,7 +127,7 @@ def test_add_user_with_existing_username(client, access_token: str, admin_user:
|
||||
"username": admin_user.username,
|
||||
"password": "new_user_password",
|
||||
"email": "new_user@example.com",
|
||||
"role": Role.VIEWER.value,
|
||||
"role": Role.USER.value,
|
||||
},
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
@@ -138,17 +138,17 @@ def test_add_user_with_existing_username(client, access_token: str, admin_user:
|
||||
|
||||
|
||||
def test_update_user(client, access_token: str, editor_user: User):
|
||||
assert editor_user.role == Role.EDITOR
|
||||
assert editor_user.role == Role.USER
|
||||
|
||||
response = client.put(
|
||||
f"/api/users/{editor_user.id}",
|
||||
data={"username": "editor_user_new_username", "role": "viewer"},
|
||||
data={"username": "editor_user_new_username", "role": "user"},
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
user = response.json()
|
||||
assert user["role"] == "viewer"
|
||||
assert user["role"] == "user"
|
||||
|
||||
|
||||
def test_update_user_rejects_non_image_avatar(
|
||||
|
||||
194
backend/tests/endpoints/test_permissions_admin.py
Normal file
194
backend/tests/endpoints/test_permissions_admin.py
Normal file
@@ -0,0 +1,194 @@
|
||||
"""Admin CRUD for groups, memberships, overrides and hidden entities, and the
|
||||
end-to-end effect on a member's /permissions/me."""
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS
|
||||
from handler.auth import oauth_handler
|
||||
from handler.database import db_user_handler
|
||||
from handler.database.base_handler import sync_session
|
||||
from models.permission import PermissionGroup
|
||||
|
||||
|
||||
def _bearer(token):
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def _fresh_user_auth(user_id):
|
||||
# Mint a token from the user's CURRENT (post-change) projected scopes.
|
||||
user = db_user_handler.get_user(user_id)
|
||||
return _bearer(
|
||||
oauth_handler.create_access_token(
|
||||
data={
|
||||
"sub": user.username,
|
||||
"iss": "romm:oauth",
|
||||
"scopes": " ".join(user.oauth_scopes),
|
||||
},
|
||||
expires_delta=timedelta(seconds=OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _me_actions(client, user_id):
|
||||
body = client.get("/api/permissions/me", headers=_fresh_user_auth(user_id)).json()
|
||||
return {g["action"] for g in body["grants"]}, body
|
||||
|
||||
|
||||
def _cleanup():
|
||||
with sync_session.begin() as s:
|
||||
s.query(PermissionGroup).filter(PermissionGroup.is_system.is_(False)).delete(
|
||||
synchronize_session="evaluate"
|
||||
)
|
||||
|
||||
|
||||
def test_non_admin_forbidden(client, viewer_access_token):
|
||||
h = _bearer(viewer_access_token)
|
||||
assert client.get("/api/permissions/groups", headers=h).status_code == 403
|
||||
assert client.get("/api/permissions/catalog", headers=h).status_code == 403
|
||||
assert (
|
||||
client.post(
|
||||
"/api/permissions/groups", headers=h, json={"name": "x"}
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
|
||||
def test_catalog_lists_vocabulary(client, access_token):
|
||||
body = client.get("/api/permissions/catalog", headers=_bearer(access_token)).json()
|
||||
assert "roms" in body["entities"] and "platforms" in body["entities"]
|
||||
assert set(body["actions"]) == {"read", "write", "delete"}
|
||||
|
||||
|
||||
def test_group_create_assign_and_effective_permissions(
|
||||
client, access_token, viewer_user
|
||||
):
|
||||
try:
|
||||
created = client.post(
|
||||
"/api/permissions/groups",
|
||||
headers=_bearer(access_token),
|
||||
json={
|
||||
"name": "Curators",
|
||||
"description": "roms + platform read",
|
||||
"grants": [
|
||||
{"entity": "roms", "action": "read"},
|
||||
{"entity": "roms", "action": "write"},
|
||||
{"entity": "platforms", "action": "read"},
|
||||
],
|
||||
},
|
||||
)
|
||||
assert created.status_code == 201
|
||||
group = created.json()
|
||||
assert group["member_count"] == 0
|
||||
assert {(g["entity"], g["action"]) for g in group["grants"]} == {
|
||||
("roms", "read"),
|
||||
("roms", "write"),
|
||||
("platforms", "read"),
|
||||
}
|
||||
gid = group["id"]
|
||||
|
||||
assigned = client.put(
|
||||
f"/api/permissions/users/{viewer_user.id}",
|
||||
headers=_bearer(access_token),
|
||||
json={"set_group": True, "permission_group_id": gid},
|
||||
)
|
||||
assert assigned.status_code == 200
|
||||
assert assigned.json()["permission_group_id"] == gid
|
||||
|
||||
actions, _ = _me_actions(client, viewer_user.id)
|
||||
# Group grants -> these actions; nothing from the default viewer matrix.
|
||||
assert {"rom.view", "rom.upload", "platform.view"} <= actions
|
||||
assert "collection.create" not in actions # group grants no collections
|
||||
finally:
|
||||
_cleanup()
|
||||
|
||||
|
||||
def test_user_override_adds_capability(client, access_token, viewer_user):
|
||||
try:
|
||||
gid = client.post(
|
||||
"/api/permissions/groups",
|
||||
headers=_bearer(access_token),
|
||||
json={"name": "RO", "grants": [{"entity": "roms", "action": "read"}]},
|
||||
).json()["id"]
|
||||
client.put(
|
||||
f"/api/permissions/users/{viewer_user.id}",
|
||||
headers=_bearer(access_token),
|
||||
json={
|
||||
"set_group": True,
|
||||
"permission_group_id": gid,
|
||||
"overrides": [{"entity": "roms", "action": "delete", "granted": True}],
|
||||
},
|
||||
)
|
||||
actions, _ = _me_actions(client, viewer_user.id)
|
||||
assert "rom.delete" in actions # granted by override on top of read-only group
|
||||
finally:
|
||||
_cleanup()
|
||||
|
||||
|
||||
def test_hide_entity_for_user(client, access_token, viewer_user):
|
||||
resp = client.post(
|
||||
"/api/permissions/hidden",
|
||||
headers=_bearer(access_token),
|
||||
json={"entity": "platforms", "entity_id": 11, "user_id": viewer_user.id},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
|
||||
_, body = _me_actions(client, viewer_user.id)
|
||||
assert body["hidden"]["platforms"] == [11]
|
||||
|
||||
# Idempotent + removable.
|
||||
client.post(
|
||||
"/api/permissions/hidden",
|
||||
headers=_bearer(access_token),
|
||||
json={"entity": "platforms", "entity_id": 11, "user_id": viewer_user.id},
|
||||
)
|
||||
removed = client.request(
|
||||
"DELETE",
|
||||
"/api/permissions/hidden",
|
||||
headers=_bearer(access_token),
|
||||
json={"entity": "platforms", "entity_id": 11, "user_id": viewer_user.id},
|
||||
)
|
||||
assert removed.status_code == 204
|
||||
_, body = _me_actions(client, viewer_user.id)
|
||||
assert body["hidden"]["platforms"] == []
|
||||
|
||||
|
||||
def test_hidden_requires_exactly_one_principal(client, access_token):
|
||||
resp = client.post(
|
||||
"/api/permissions/hidden",
|
||||
headers=_bearer(access_token),
|
||||
json={"entity": "roms", "entity_id": 1, "user_id": 1, "group_id": 1},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
def test_cannot_delete_default_group(client, access_token):
|
||||
groups = client.get("/api/permissions/groups", headers=_bearer(access_token)).json()
|
||||
default = next(g for g in groups if g["is_default"])
|
||||
resp = client.delete(
|
||||
f"/api/permissions/groups/{default['id']}", headers=_bearer(access_token)
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
def test_delete_group_falls_members_back(client, access_token, viewer_user):
|
||||
gid = client.post(
|
||||
"/api/permissions/groups",
|
||||
headers=_bearer(access_token),
|
||||
json={"name": "Temp", "grants": [{"entity": "roms", "action": "read"}]},
|
||||
).json()["id"]
|
||||
client.put(
|
||||
f"/api/permissions/users/{viewer_user.id}",
|
||||
headers=_bearer(access_token),
|
||||
json={"set_group": True, "permission_group_id": gid},
|
||||
)
|
||||
|
||||
resp = client.delete(
|
||||
f"/api/permissions/groups/{gid}", headers=_bearer(access_token)
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
|
||||
# FK SET NULL -> user falls back to the default (viewer) matrix.
|
||||
user = db_user_handler.get_user(viewer_user.id)
|
||||
assert user.permission_group_id is None
|
||||
actions, _ = _me_actions(client, viewer_user.id)
|
||||
assert "collection.create" in actions # default viewer behaviour restored
|
||||
95
backend/tests/endpoints/test_permissions_me.py
Normal file
95
backend/tests/endpoints/test_permissions_me.py
Normal file
@@ -0,0 +1,95 @@
|
||||
"""`/permissions/me` returns backend-enforced grants in the UI action vocabulary."""
|
||||
|
||||
from handler.database.base_handler import sync_session
|
||||
from models.permission import HiddenEntity, PermEntity
|
||||
|
||||
VIEWER_ACTIONS = {
|
||||
"rom.view",
|
||||
"rom.play",
|
||||
"rom.download",
|
||||
"rom.favorite",
|
||||
"platform.view",
|
||||
"collection.view",
|
||||
"collection.create",
|
||||
"collection.edit",
|
||||
"collection.delete",
|
||||
}
|
||||
|
||||
|
||||
def _actions(payload):
|
||||
return {g["action"] for g in payload["grants"]}
|
||||
|
||||
|
||||
def test_requires_auth(client):
|
||||
assert client.get("/api/permissions/me").status_code == 403
|
||||
|
||||
|
||||
def test_admin_is_admin_and_all_actions(client, access_token):
|
||||
resp = client.get(
|
||||
"/api/permissions/me", headers={"Authorization": f"Bearer {access_token}"}
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["is_admin"] is True
|
||||
# Admin unlocks the full vocabulary, incl. user.* and app.admin.
|
||||
assert {"user.delete", "app.admin", "rom.delete"} <= _actions(body)
|
||||
assert body["hidden"] == {"platforms": [], "roms": []}
|
||||
|
||||
|
||||
def test_viewer_matches_read_only_action_set(client, viewer_access_token):
|
||||
body = client.get(
|
||||
"/api/permissions/me",
|
||||
headers={"Authorization": f"Bearer {viewer_access_token}"},
|
||||
).json()
|
||||
assert body["is_admin"] is False
|
||||
assert _actions(body) == VIEWER_ACTIONS
|
||||
|
||||
|
||||
def test_editor_adds_write_actions(client, editor_access_token):
|
||||
body = client.get(
|
||||
"/api/permissions/me",
|
||||
headers={"Authorization": f"Bearer {editor_access_token}"},
|
||||
).json()
|
||||
assert body["is_admin"] is False
|
||||
actions = _actions(body)
|
||||
assert VIEWER_ACTIONS <= actions
|
||||
# Editor gains library-wide write (and the backend-true delete/create it
|
||||
# always had, which the legacy role-map under-reported).
|
||||
assert {
|
||||
"rom.upload",
|
||||
"rom.edit",
|
||||
"rom.delete",
|
||||
"platform.edit",
|
||||
"platform.create",
|
||||
"platform.delete",
|
||||
"library.scan",
|
||||
} <= actions
|
||||
# Still no user management.
|
||||
assert not {a for a in actions if a.startswith("user.")}
|
||||
|
||||
|
||||
def test_hidden_entities_reported(client, viewer_user, viewer_access_token):
|
||||
with sync_session.begin() as s:
|
||||
s.add(
|
||||
HiddenEntity(
|
||||
entity=PermEntity.PLATFORMS, entity_id=5, user_id=viewer_user.id
|
||||
)
|
||||
)
|
||||
s.add(
|
||||
HiddenEntity(entity=PermEntity.ROMS, entity_id=42, user_id=viewer_user.id)
|
||||
)
|
||||
|
||||
body = client.get(
|
||||
"/api/permissions/me",
|
||||
headers={"Authorization": f"Bearer {viewer_access_token}"},
|
||||
).json()
|
||||
assert body["hidden"]["platforms"] == [5]
|
||||
assert body["hidden"]["roms"] == [42]
|
||||
|
||||
|
||||
def test_grant_scopes_are_global(client, viewer_access_token):
|
||||
body = client.get(
|
||||
"/api/permissions/me",
|
||||
headers={"Authorization": f"Bearer {viewer_access_token}"},
|
||||
).json()
|
||||
assert all(g["scope"]["kind"] == "global" for g in body["grants"])
|
||||
177
backend/tests/endpoints/test_permissions_visibility.py
Normal file
177
backend/tests/endpoints/test_permissions_visibility.py
Normal file
@@ -0,0 +1,177 @@
|
||||
"""End-to-end checks for admin-driven visibility (hiding) and delete enforcement.
|
||||
|
||||
Proves the fine permission layer is actually wired into the endpoints: hidden
|
||||
platforms/roms disappear from lists and 404 on detail, the platform hide cascades
|
||||
to its roms, admins are unaffected, and delete requires a delete grant even when
|
||||
the coarse write scope is present.
|
||||
"""
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
from fastapi import status
|
||||
|
||||
from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS
|
||||
from handler.auth import oauth_handler
|
||||
from handler.database import db_user_handler
|
||||
from handler.database.base_handler import sync_session
|
||||
from models.permission import (
|
||||
HiddenEntity,
|
||||
PermAction,
|
||||
PermEntity,
|
||||
PermissionGroup,
|
||||
PermissionGroupGrant,
|
||||
)
|
||||
|
||||
|
||||
def _auth(user):
|
||||
# Re-reads the user's current (projected) scopes each call.
|
||||
token = oauth_handler.create_access_token(
|
||||
data={
|
||||
"sub": user.username,
|
||||
"iss": "romm:oauth",
|
||||
"scopes": " ".join(user.oauth_scopes),
|
||||
},
|
||||
expires_delta=timedelta(seconds=OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS),
|
||||
)
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def _hide(entity, entity_id, user_id):
|
||||
with sync_session.begin() as s:
|
||||
s.add(HiddenEntity(entity=entity, entity_id=entity_id, user_id=user_id))
|
||||
|
||||
|
||||
def _make_group(name, grants):
|
||||
with sync_session.begin() as s:
|
||||
group = PermissionGroup(name=name, is_system=False)
|
||||
s.add(group)
|
||||
s.flush()
|
||||
gid = group.id
|
||||
for entity, action, own_only in grants:
|
||||
s.add(
|
||||
PermissionGroupGrant(
|
||||
group_id=gid, entity=entity, action=action, own_only=own_only
|
||||
)
|
||||
)
|
||||
return gid
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _cleanup_non_system_groups():
|
||||
# HiddenEntity user rows cascade when clear_database deletes users; only the
|
||||
# non-system groups created here need explicit cleanup.
|
||||
yield
|
||||
with sync_session.begin() as s:
|
||||
s.query(PermissionGroup).filter(PermissionGroup.is_system.is_(False)).delete(
|
||||
synchronize_session="evaluate"
|
||||
)
|
||||
|
||||
|
||||
def test_hidden_platform_excluded_from_list_but_visible_to_admin(
|
||||
client, viewer_user, admin_user, platform
|
||||
):
|
||||
_hide(PermEntity.PLATFORMS, platform.id, viewer_user.id)
|
||||
|
||||
viewer_ids = [
|
||||
p["id"] for p in client.get("/api/platforms", headers=_auth(viewer_user)).json()
|
||||
]
|
||||
assert platform.id not in viewer_ids
|
||||
|
||||
admin_ids = [
|
||||
p["id"] for p in client.get("/api/platforms", headers=_auth(admin_user)).json()
|
||||
]
|
||||
assert platform.id in admin_ids
|
||||
|
||||
|
||||
def test_hidden_platform_detail_is_404_masked(client, viewer_user, platform):
|
||||
_hide(PermEntity.PLATFORMS, platform.id, viewer_user.id)
|
||||
resp = client.get(f"/api/platforms/{platform.id}", headers=_auth(viewer_user))
|
||||
assert resp.status_code == status.HTTP_404_NOT_FOUND
|
||||
|
||||
|
||||
def test_hidden_rom_excluded_and_detail_404(client, viewer_user, rom):
|
||||
_hide(PermEntity.ROMS, rom.id, viewer_user.id)
|
||||
|
||||
listing = client.get("/api/roms", headers=_auth(viewer_user)).json()
|
||||
assert rom.id not in listing["rom_id_index"]
|
||||
|
||||
detail = client.get(f"/api/roms/{rom.id}", headers=_auth(viewer_user))
|
||||
assert detail.status_code == status.HTTP_404_NOT_FOUND
|
||||
|
||||
|
||||
def test_hidden_platform_cascades_to_its_roms(client, viewer_user, rom, platform):
|
||||
_hide(PermEntity.PLATFORMS, platform.id, viewer_user.id)
|
||||
listing = client.get("/api/roms", headers=_auth(viewer_user)).json()
|
||||
assert rom.id not in listing["rom_id_index"]
|
||||
|
||||
|
||||
def test_hidden_rom_cannot_be_downloaded_by_id(client, viewer_user, rom):
|
||||
_hide(PermEntity.ROMS, rom.id, viewer_user.id)
|
||||
# Zip download of a hidden rom is masked as not-found.
|
||||
zip_resp = client.get(
|
||||
f"/api/roms/download?rom_ids={rom.id}", headers=_auth(viewer_user)
|
||||
)
|
||||
assert zip_resp.status_code == status.HTTP_404_NOT_FOUND
|
||||
# Direct content stream is masked too (before any file lookup).
|
||||
content_resp = client.get(
|
||||
f"/api/roms/{rom.id}/content/whatever", headers=_auth(viewer_user)
|
||||
)
|
||||
assert content_resp.status_code == status.HTTP_404_NOT_FOUND
|
||||
|
||||
|
||||
def test_hidden_rom_update_is_404_masked(client, editor_user, rom):
|
||||
# Editor holds library-wide roms write (passes the coarse gate), so the
|
||||
# hidden rom must be 404-masked instead of being editable.
|
||||
_hide(PermEntity.ROMS, rom.id, editor_user.id)
|
||||
resp = client.put(
|
||||
f"/api/roms/{rom.id}", headers=_auth(editor_user), data={"name": "x"}
|
||||
)
|
||||
assert resp.status_code == status.HTTP_404_NOT_FOUND
|
||||
|
||||
|
||||
def test_hidden_rom_props_update_is_404_masked(client, viewer_user, rom):
|
||||
# ROMS_USER_WRITE is a self-service scope every user holds, so the coarse
|
||||
# gate passes; the hidden rom must still be masked, not confirmed.
|
||||
_hide(PermEntity.ROMS, rom.id, viewer_user.id)
|
||||
resp = client.put(
|
||||
f"/api/roms/{rom.id}/props", headers=_auth(viewer_user), json={"rating": 5}
|
||||
)
|
||||
assert resp.status_code == status.HTTP_404_NOT_FOUND
|
||||
|
||||
|
||||
def test_hidden_rom_patch_is_404_masked(client, viewer_user, rom, rom_file):
|
||||
# patch_rom streams file bytes back; a hidden rom's bytes must not leak.
|
||||
_hide(PermEntity.ROMS, rom.id, viewer_user.id)
|
||||
resp = client.post(
|
||||
f"/api/roms/{rom_file.id}/patch",
|
||||
headers=_auth(viewer_user),
|
||||
json={"patch_file_id": rom_file.id},
|
||||
)
|
||||
assert resp.status_code == status.HTTP_404_NOT_FOUND
|
||||
|
||||
|
||||
def test_delete_requires_delete_grant_even_with_write_scope(
|
||||
client, viewer_user, platform
|
||||
):
|
||||
# Group can read+write platforms but NOT delete them.
|
||||
gid = _make_group(
|
||||
"platform-writers",
|
||||
[
|
||||
(PermEntity.PLATFORMS, PermAction.READ, False),
|
||||
(PermEntity.PLATFORMS, PermAction.WRITE, False),
|
||||
],
|
||||
)
|
||||
db_user_handler.update_user(viewer_user.id, {"permission_group_id": gid})
|
||||
user = db_user_handler.get_user(viewer_user.id)
|
||||
|
||||
# Coarse PLATFORMS_WRITE is present (projected from the write grant), so the
|
||||
# request passes the scope gate and is rejected by the fine delete check.
|
||||
assert "platforms.write" in {s.value for s in user.oauth_scopes}
|
||||
resp = client.delete(f"/api/platforms/{platform.id}", headers=_auth(user))
|
||||
assert resp.status_code == status.HTTP_403_FORBIDDEN
|
||||
|
||||
|
||||
def test_admin_can_delete_platform(client, admin_user, platform):
|
||||
resp = client.delete(f"/api/platforms/{platform.id}", headers=_auth(admin_user))
|
||||
assert resp.status_code == status.HTTP_200_OK
|
||||
@@ -142,7 +142,7 @@ async def test_oidc_valid_token_decoding(
|
||||
header={"alg": "RS256"},
|
||||
claims={"iss": OIDC_SERVER_APPLICATION_URL, "email": "test@example.com"},
|
||||
)
|
||||
mock_user = MagicMock(enabled=True, role=Role.VIEWER)
|
||||
mock_user = MagicMock(enabled=True, role=Role.USER)
|
||||
mocker.patch(
|
||||
"handler.database.db_user_handler.get_user_by_email", return_value=mock_user
|
||||
)
|
||||
@@ -168,13 +168,13 @@ async def test_oidc_valid_token_decoding(
|
||||
"config_override,token_roles,romm_role",
|
||||
[
|
||||
# Without OIDC role mapping.
|
||||
[{"OIDC_CLAIM_ROLES": ""}, ["admin", "editor"], Role.VIEWER],
|
||||
[{"OIDC_CLAIM_ROLES": ""}, ["admin", "editor"], Role.USER],
|
||||
# OIDC role mapping.
|
||||
[{}, ["admin", "editor", "viewer"], Role.ADMIN],
|
||||
[{}, ["editor", "viewer"], Role.EDITOR],
|
||||
[{}, ["viewer"], Role.VIEWER],
|
||||
[{}, ["editor", "viewer"], Role.USER],
|
||||
[{}, ["viewer"], Role.USER],
|
||||
# OIDC viewer role fallback.
|
||||
[{"OIDC_ROLE_VIEWER": "*"}, [], Role.VIEWER],
|
||||
[{"OIDC_ROLE_VIEWER": "*"}, [], Role.USER],
|
||||
],
|
||||
ids=["no-mapping", "admin-role", "editor-role", "viewer-role", "viewer-fallback"],
|
||||
)
|
||||
@@ -206,7 +206,7 @@ async def test_oidc_valid_add_user(
|
||||
config_override.get("OIDC_ROLE_VIEWER", "viewer"),
|
||||
)
|
||||
mock_token["userinfo"]["roles"] = token_roles
|
||||
mock_user = MagicMock(enabled=True, role=Role.VIEWER)
|
||||
mock_user = MagicMock(enabled=True, role=Role.USER)
|
||||
mock_add_user = mocker.patch(
|
||||
"handler.database.db_user_handler.add_user", return_value=mock_user
|
||||
)
|
||||
@@ -265,7 +265,7 @@ async def test_oidc_registration_enabled_creates_unknown_user(
|
||||
mocker.patch(
|
||||
"handler.database.db_user_handler.get_user_by_email", return_value=None
|
||||
)
|
||||
mock_user = MagicMock(enabled=True, role=Role.VIEWER)
|
||||
mock_user = MagicMock(enabled=True, role=Role.USER)
|
||||
mock_add_user = mocker.patch(
|
||||
"handler.database.db_user_handler.add_user", return_value=mock_user
|
||||
)
|
||||
@@ -290,7 +290,7 @@ async def test_oidc_registration_disabled_allows_existing_user(
|
||||
mock_openid_configuration,
|
||||
):
|
||||
"""Test that an existing user can still log in when registration is disabled."""
|
||||
mock_user = MagicMock(enabled=True, role=Role.VIEWER)
|
||||
mock_user = MagicMock(enabled=True, role=Role.USER)
|
||||
mocker.patch(
|
||||
"handler.database.db_user_handler.get_user_by_email", return_value=mock_user
|
||||
)
|
||||
@@ -318,7 +318,7 @@ async def test_oidc_valid_edit_user_role(
|
||||
mocker.patch("handler.auth.base_handler.OIDC_CLAIM_ROLES", "roles")
|
||||
mocker.patch("handler.auth.base_handler.OIDC_ROLE_ADMIN", "admin")
|
||||
mock_token["userinfo"]["roles"] = ["admin"]
|
||||
mock_user = MagicMock(enabled=True, role=Role.VIEWER)
|
||||
mock_user = MagicMock(enabled=True, role=Role.USER)
|
||||
mocker.patch(
|
||||
"handler.database.db_user_handler.get_user_by_email", return_value=mock_user
|
||||
)
|
||||
@@ -347,7 +347,7 @@ async def test_oidc_valid_no_edit_user_role_if_mapping_disabled(
|
||||
):
|
||||
"""Test that role is not changed for existing user on login if OIDC role mapping is disabled."""
|
||||
mock_token["userinfo"]["roles"] = ["admin"]
|
||||
mock_user = MagicMock(enabled=True, role=Role.EDITOR)
|
||||
mock_user = MagicMock(enabled=True, role=Role.USER)
|
||||
mocker.patch(
|
||||
"handler.database.db_user_handler.get_user_by_email", return_value=mock_user
|
||||
)
|
||||
@@ -412,7 +412,7 @@ async def test_oidc_token_without_email_verified_claim(
|
||||
header={"alg": "RS256"},
|
||||
claims={"iss": OIDC_SERVER_APPLICATION_URL, "email": "test@example.com"},
|
||||
)
|
||||
mock_user = MagicMock(enabled=True, role=Role.VIEWER)
|
||||
mock_user = MagicMock(enabled=True, role=Role.USER)
|
||||
mocker.patch(
|
||||
"handler.database.db_user_handler.get_user_by_email", return_value=mock_user
|
||||
)
|
||||
|
||||
60
backend/tests/handler/auth/test_permissions_dependencies.py
Normal file
60
backend/tests/handler/auth/test_permissions_dependencies.py
Normal file
@@ -0,0 +1,60 @@
|
||||
"""Pure unit tests for the fine-grained enforcement helpers (no DB needed)."""
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from handler.auth.dependencies import assert_can, can_access
|
||||
from handler.auth.permissions import ResolvedGrant, ResolvedPermissions
|
||||
from models.permission import PermAction, PermEntity
|
||||
|
||||
|
||||
def _perms(*, is_admin=False, user_id=1, grants=()):
|
||||
return ResolvedPermissions(
|
||||
is_admin=is_admin,
|
||||
user_id=user_id,
|
||||
grants=frozenset(grants),
|
||||
hidden_platform_ids=frozenset(),
|
||||
hidden_rom_ids=frozenset(),
|
||||
)
|
||||
|
||||
|
||||
def test_admin_can_do_anything():
|
||||
perms = _perms(is_admin=True)
|
||||
assert can_access(perms, PermEntity.USERS, PermAction.DELETE)
|
||||
assert can_access(perms, PermEntity.ROMS, PermAction.WRITE, owner_id=999)
|
||||
|
||||
|
||||
def test_library_wide_grant_allows_any_resource():
|
||||
perms = _perms(grants=[ResolvedGrant(PermEntity.ROMS, PermAction.DELETE, False)])
|
||||
assert can_access(perms, PermEntity.ROMS, PermAction.DELETE)
|
||||
assert can_access(perms, PermEntity.ROMS, PermAction.DELETE, owner_id=999)
|
||||
|
||||
|
||||
def test_missing_grant_is_denied():
|
||||
perms = _perms(grants=[ResolvedGrant(PermEntity.ROMS, PermAction.READ, False)])
|
||||
assert not can_access(perms, PermEntity.ROMS, PermAction.DELETE)
|
||||
|
||||
|
||||
def test_owner_always_allowed_even_without_grant():
|
||||
perms = _perms(user_id=7, grants=())
|
||||
assert can_access(perms, PermEntity.COLLECTIONS, PermAction.WRITE, owner_id=7)
|
||||
assert not can_access(perms, PermEntity.COLLECTIONS, PermAction.WRITE, owner_id=8)
|
||||
|
||||
|
||||
def test_own_only_grant_does_not_allow_others_resources():
|
||||
# own_only collections.write: may act on own (owner_id match) but not others'.
|
||||
perms = _perms(
|
||||
user_id=7,
|
||||
grants=[ResolvedGrant(PermEntity.COLLECTIONS, PermAction.WRITE, True)],
|
||||
)
|
||||
assert can_access(perms, PermEntity.COLLECTIONS, PermAction.WRITE, owner_id=7)
|
||||
assert not can_access(perms, PermEntity.COLLECTIONS, PermAction.WRITE, owner_id=8)
|
||||
# No owner context (library-wide attempt) -> own_only is insufficient.
|
||||
assert not can_access(perms, PermEntity.COLLECTIONS, PermAction.WRITE)
|
||||
|
||||
|
||||
def test_assert_can_raises_403():
|
||||
perms = _perms(grants=())
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
assert_can(perms, PermEntity.PLATFORMS, PermAction.DELETE)
|
||||
assert exc.value.status_code == 403
|
||||
105
backend/tests/handler/auth/test_permissions_parity.py
Normal file
105
backend/tests/handler/auth/test_permissions_parity.py
Normal file
@@ -0,0 +1,105 @@
|
||||
"""Proves the new permission model preserves every user's pre-upgrade access.
|
||||
|
||||
Two layers:
|
||||
* Pure parity -- the legacy grant matrices, projected back onto coarse scopes,
|
||||
reproduce exactly what each role's ``oauth_scopes`` returns today.
|
||||
* Seed integrity -- the rows the Alembic migration actually wrote into the DB
|
||||
match those same in-code matrices, so the frozen migration literals can't
|
||||
silently drift from ``permissions_map.py``.
|
||||
"""
|
||||
|
||||
from handler.auth.constants import EDIT_SCOPES, FULL_SCOPES, WRITE_SCOPES
|
||||
from handler.auth.permissions_map import (
|
||||
LEGACY_EDITOR_GRANTS,
|
||||
LEGACY_VIEWER_GRANTS,
|
||||
grants_to_scopes,
|
||||
)
|
||||
from handler.database.base_handler import sync_session
|
||||
from models.permission import PermissionGroup
|
||||
from models.user import Role, User
|
||||
|
||||
# --- Pure parity: matrices reproduce legacy scopes ---------------------------
|
||||
|
||||
|
||||
def test_viewer_matrix_projects_to_write_scopes():
|
||||
projected = set(grants_to_scopes(LEGACY_VIEWER_GRANTS))
|
||||
assert projected == set(WRITE_SCOPES)
|
||||
# A group-less user falls back to the default (Viewer legacy) group.
|
||||
assert projected == set(User(role=Role.USER).oauth_scopes)
|
||||
|
||||
|
||||
def test_editor_matrix_projects_to_edit_scopes():
|
||||
from handler.database import db_permission_handler
|
||||
|
||||
projected = set(grants_to_scopes(LEGACY_EDITOR_GRANTS))
|
||||
assert projected == set(EDIT_SCOPES)
|
||||
# Editor-level access now comes from the Editor (legacy) group.
|
||||
editor_group = db_permission_handler.get_group_by_name("Editor (legacy)")
|
||||
assert editor_group is not None
|
||||
assert projected == set(
|
||||
User(role=Role.USER, permission_group_id=editor_group.id).oauth_scopes
|
||||
)
|
||||
|
||||
|
||||
def test_admin_projects_to_full_scopes():
|
||||
projected = set(grants_to_scopes([], is_admin=True))
|
||||
assert projected == set(FULL_SCOPES)
|
||||
assert projected == set(User(role=Role.ADMIN).oauth_scopes)
|
||||
|
||||
|
||||
def test_editor_strictly_extends_viewer():
|
||||
# The only coarse difference is library-wide write of roms/platforms/firmware.
|
||||
extra = set(grants_to_scopes(LEGACY_EDITOR_GRANTS)) - set(
|
||||
grants_to_scopes(LEGACY_VIEWER_GRANTS)
|
||||
)
|
||||
assert {s.value for s in extra} == {
|
||||
"roms.write",
|
||||
"platforms.write",
|
||||
"firmware.write",
|
||||
}
|
||||
|
||||
|
||||
# --- Seed integrity: migration rows match the in-code matrices ---------------
|
||||
|
||||
|
||||
def _grant_tuples(group: PermissionGroup) -> set[tuple[str, str, bool]]:
|
||||
return {(g.entity.value, g.action.value, g.own_only) for g in group.grants}
|
||||
|
||||
|
||||
def _expected_tuples(matrix) -> set[tuple[str, str, bool]]:
|
||||
return {(e.value, a.value, o) for (e, a, o) in matrix}
|
||||
|
||||
|
||||
def test_migration_seeded_legacy_groups():
|
||||
with sync_session.begin() as s:
|
||||
groups = {
|
||||
g.name: g
|
||||
for g in s.query(PermissionGroup)
|
||||
.filter(PermissionGroup.name.in_(["Viewer (legacy)", "Editor (legacy)"]))
|
||||
.all()
|
||||
}
|
||||
|
||||
assert set(groups) == {"Viewer (legacy)", "Editor (legacy)"}
|
||||
|
||||
viewer = groups["Viewer (legacy)"]
|
||||
editor = groups["Editor (legacy)"]
|
||||
|
||||
# Viewer is the server-wide default; both are system groups.
|
||||
assert viewer.is_default is True
|
||||
assert viewer.is_system is True
|
||||
assert editor.is_default is False
|
||||
assert editor.is_system is True
|
||||
|
||||
# Seeded grants equal the frozen matrices (no drift).
|
||||
assert _grant_tuples(viewer) == _expected_tuples(LEGACY_VIEWER_GRANTS)
|
||||
assert _grant_tuples(editor) == _expected_tuples(LEGACY_EDITOR_GRANTS)
|
||||
|
||||
|
||||
def test_exactly_one_default_group():
|
||||
with sync_session.begin() as s:
|
||||
defaults = (
|
||||
s.query(PermissionGroup)
|
||||
.filter(PermissionGroup.is_default.is_(True))
|
||||
.count()
|
||||
)
|
||||
assert defaults == 1
|
||||
191
backend/tests/handler/auth/test_permissions_resolver.py
Normal file
191
backend/tests/handler/auth/test_permissions_resolver.py
Normal file
@@ -0,0 +1,191 @@
|
||||
"""Resolver + projection behavior: precedence, overrides, own_only, hiding, kiosk.
|
||||
|
||||
Complements ``test_permissions_parity.py`` (which proves the static matrices).
|
||||
Here we exercise ``resolve_permissions`` / ``compute_oauth_scopes`` end-to-end
|
||||
against the DB: group membership, per-user overrides, ownership scoping, hidden
|
||||
entities, and the KIOSK_MODE read-only cap.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from handler.auth.constants import EDIT_SCOPES, FULL_SCOPES, READ_SCOPES, WRITE_SCOPES
|
||||
from handler.auth.permissions import resolve_permissions
|
||||
from handler.database import db_user_handler
|
||||
from handler.database.base_handler import sync_session
|
||||
from models.permission import (
|
||||
HiddenEntity,
|
||||
PermAction,
|
||||
PermEntity,
|
||||
PermissionGroup,
|
||||
PermissionGroupGrant,
|
||||
UserPermissionOverride,
|
||||
)
|
||||
from models.user import User
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _cleanup_non_system_groups():
|
||||
# clear_database (conftest) deletes users, cascading overrides + user-hidden
|
||||
# rows via FK. Non-system groups created by these tests are not user-bound,
|
||||
# so drop them (cascading their grants + group-hidden rows) after each test.
|
||||
yield
|
||||
with sync_session.begin() as s:
|
||||
s.query(PermissionGroup).filter(PermissionGroup.is_system.is_(False)).delete(
|
||||
synchronize_session="evaluate"
|
||||
)
|
||||
|
||||
|
||||
def _make_group(name, grants, *, is_default=False):
|
||||
with sync_session.begin() as s:
|
||||
group = PermissionGroup(name=name, is_default=is_default, is_system=False)
|
||||
s.add(group)
|
||||
s.flush()
|
||||
gid = group.id
|
||||
for entity, action, own_only in grants:
|
||||
s.add(
|
||||
PermissionGroupGrant(
|
||||
group_id=gid, entity=entity, action=action, own_only=own_only
|
||||
)
|
||||
)
|
||||
return gid
|
||||
|
||||
|
||||
def _set_group(user: User, group_id: int) -> User:
|
||||
db_user_handler.update_user(user.id, {"permission_group_id": group_id})
|
||||
return db_user_handler.get_user(user.id)
|
||||
|
||||
|
||||
def _add_override(user_id, entity, action, *, granted, own_only=False):
|
||||
with sync_session.begin() as s:
|
||||
s.add(
|
||||
UserPermissionOverride(
|
||||
user_id=user_id,
|
||||
entity=entity,
|
||||
action=action,
|
||||
granted=granted,
|
||||
own_only=own_only,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _hide(entity, entity_id, *, user_id=None, group_id=None):
|
||||
with sync_session.begin() as s:
|
||||
s.add(
|
||||
HiddenEntity(
|
||||
entity=entity, entity_id=entity_id, user_id=user_id, group_id=group_id
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# --- Projection parity through the live property (group-less users) ----------
|
||||
|
||||
|
||||
def test_property_parity_for_group_less_users(admin_user, editor_user, viewer_user):
|
||||
assert set(admin_user.oauth_scopes) == set(FULL_SCOPES)
|
||||
assert set(editor_user.oauth_scopes) == set(EDIT_SCOPES)
|
||||
assert set(viewer_user.oauth_scopes) == set(WRITE_SCOPES)
|
||||
|
||||
|
||||
def test_kiosk_caps_non_admin_to_read(
|
||||
monkeypatch, admin_user, editor_user, viewer_user
|
||||
):
|
||||
monkeypatch.setattr("handler.auth.permissions.KIOSK_MODE", True)
|
||||
# Kiosk locks every non-admin user (including former editors) to read-only.
|
||||
assert set(viewer_user.oauth_scopes) == set(READ_SCOPES)
|
||||
assert set(editor_user.oauth_scopes) == set(READ_SCOPES)
|
||||
# Only admins bypass the kiosk cap.
|
||||
assert set(admin_user.oauth_scopes) == set(FULL_SCOPES)
|
||||
|
||||
|
||||
# --- Precedence: group > legacy role fallback --------------------------------
|
||||
|
||||
|
||||
def test_explicit_group_overrides_role_fallback(editor_user):
|
||||
# A read-only group assigned to an (legacy) editor strips write access.
|
||||
gid = _make_group("readonly", [(PermEntity.ROMS, PermAction.READ, False)])
|
||||
user = _set_group(editor_user, gid)
|
||||
scopes = {s.value for s in user.oauth_scopes}
|
||||
assert "roms.read" in scopes
|
||||
assert "roms.write" not in scopes # role said editor, group says read-only
|
||||
# Self-service scopes are always present regardless of group.
|
||||
assert {"me.read", "me.write", "roms.user.read", "roms.user.write"} <= scopes
|
||||
|
||||
|
||||
# --- Per-user overrides add and revoke ---------------------------------------
|
||||
|
||||
|
||||
def test_override_grants_extra_capability(viewer_user):
|
||||
_add_override(viewer_user.id, PermEntity.ROMS, PermAction.WRITE, granted=True)
|
||||
user = db_user_handler.get_user(viewer_user.id)
|
||||
assert "roms.write" in {s.value for s in user.oauth_scopes}
|
||||
perms = resolve_permissions(user)
|
||||
assert perms.allows(PermEntity.ROMS, PermAction.WRITE)
|
||||
|
||||
|
||||
def test_override_revokes_group_capability(viewer_user):
|
||||
# Viewer matrix grants collections.write (own); a revoke override removes it.
|
||||
_add_override(
|
||||
viewer_user.id, PermEntity.COLLECTIONS, PermAction.WRITE, granted=False
|
||||
)
|
||||
user = db_user_handler.get_user(viewer_user.id)
|
||||
assert "collections.write" not in {s.value for s in user.oauth_scopes}
|
||||
|
||||
|
||||
# --- Admin bypass and own_only semantics -------------------------------------
|
||||
|
||||
|
||||
def test_admin_bypass(admin_user):
|
||||
perms = resolve_permissions(admin_user)
|
||||
assert perms.is_admin
|
||||
assert perms.allows(PermEntity.USERS, PermAction.DELETE)
|
||||
assert perms.allows(PermEntity.ROMS, PermAction.WRITE, owned=False)
|
||||
|
||||
|
||||
def test_own_only_requires_ownership(viewer_user):
|
||||
perms = resolve_permissions(viewer_user)
|
||||
# collections.write is own_only in the viewer matrix.
|
||||
assert perms.allows(PermEntity.COLLECTIONS, PermAction.WRITE, owned=True)
|
||||
assert not perms.allows(PermEntity.COLLECTIONS, PermAction.WRITE, owned=False)
|
||||
assert not perms.allows(PermEntity.COLLECTIONS, PermAction.WRITE)
|
||||
# collections.read is library-wide (own_only False) -> always allowed.
|
||||
assert perms.allows(PermEntity.COLLECTIONS, PermAction.READ)
|
||||
|
||||
|
||||
# --- Hidden entities (user and group principals) -----------------------------
|
||||
|
||||
|
||||
def test_user_hidden_platform_and_rom_cascade(viewer_user):
|
||||
_hide(PermEntity.PLATFORMS, 5, user_id=viewer_user.id)
|
||||
_hide(PermEntity.ROMS, 99, user_id=viewer_user.id)
|
||||
perms = resolve_permissions(viewer_user)
|
||||
assert perms.hidden_platform_ids == frozenset({5})
|
||||
assert perms.hidden_rom_ids == frozenset({99})
|
||||
assert not perms.can_see_platform(5)
|
||||
assert perms.can_see_platform(6)
|
||||
# Rom on a hidden platform is hidden even if the rom itself isn't listed.
|
||||
assert not perms.can_see_rom(1, platform_id=5)
|
||||
assert not perms.can_see_rom(99, platform_id=6)
|
||||
assert perms.can_see_rom(1, platform_id=6)
|
||||
|
||||
|
||||
def test_group_hidden_applies_to_members(viewer_user):
|
||||
gid = _make_group("kids", [(PermEntity.ROMS, PermAction.READ, False)])
|
||||
user = _set_group(viewer_user, gid)
|
||||
_hide(PermEntity.PLATFORMS, 7, group_id=gid)
|
||||
perms = resolve_permissions(user)
|
||||
assert 7 in perms.hidden_platform_ids
|
||||
assert not perms.can_see_platform(7)
|
||||
|
||||
|
||||
def test_admin_sees_everything_despite_hides(admin_user):
|
||||
_hide(PermEntity.PLATFORMS, 5, user_id=admin_user.id)
|
||||
perms = resolve_permissions(admin_user)
|
||||
assert perms.can_see_platform(5)
|
||||
|
||||
|
||||
def test_default_group_is_viewer_legacy():
|
||||
from handler.database import db_permission_handler
|
||||
|
||||
group = db_permission_handler.get_default_group()
|
||||
assert group is not None
|
||||
assert group.name == "Viewer (legacy)"
|
||||
@@ -765,14 +765,14 @@ def test_users(admin_user):
|
||||
new_user = db_user_handler.get_user_by_username("new_user")
|
||||
assert new_user is not None
|
||||
assert new_user.username == "new_user"
|
||||
assert new_user.role == Role.VIEWER
|
||||
assert new_user.role == Role.USER
|
||||
assert new_user.enabled
|
||||
|
||||
db_user_handler.update_user(new_user.id, {"role": Role.EDITOR})
|
||||
db_user_handler.update_user(new_user.id, {"role": Role.ADMIN})
|
||||
|
||||
new_user = db_user_handler.get_user(new_user.id)
|
||||
assert new_user is not None
|
||||
assert new_user.role == Role.EDITOR
|
||||
assert new_user.role == Role.ADMIN
|
||||
|
||||
db_user_handler.delete_user(new_user.id)
|
||||
|
||||
|
||||
62
backend/tests/utils/test_archives.py
Normal file
62
backend/tests/utils/test_archives.py
Normal file
@@ -0,0 +1,62 @@
|
||||
import time
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from utils import archives
|
||||
|
||||
|
||||
def _fake_7z_listing(names: list[str]) -> str:
|
||||
"""Build a `7zz l -slt -ba` style listing for the given member names."""
|
||||
return "\n".join(f"Path = {name}\nSize = 10\nAttributes = A\n" for name in names)
|
||||
|
||||
|
||||
def test_stream_7z_chunks_yields_until_eof():
|
||||
process = MagicMock()
|
||||
process.stdout.read.side_effect = [b"abc", b"def", b""]
|
||||
on_timeout = MagicMock()
|
||||
|
||||
chunks = list(
|
||||
archives._stream_7z_chunks(
|
||||
process, deadline=time.monotonic() + 1000, on_timeout=on_timeout
|
||||
)
|
||||
)
|
||||
|
||||
assert chunks == [b"abc", b"def"]
|
||||
on_timeout.assert_not_called()
|
||||
process.terminate.assert_not_called()
|
||||
|
||||
|
||||
def test_stream_7z_chunks_timeout_terminates_and_signals_once():
|
||||
process = MagicMock()
|
||||
process.stdout.read.side_effect = [b"abc", b"def", b""]
|
||||
on_timeout = MagicMock()
|
||||
|
||||
# A deadline in the past trips on the first chunk.
|
||||
chunks = list(
|
||||
archives._stream_7z_chunks(process, deadline=0.0, on_timeout=on_timeout)
|
||||
)
|
||||
|
||||
assert chunks == []
|
||||
on_timeout.assert_called_once()
|
||||
process.terminate.assert_called_once()
|
||||
|
||||
|
||||
def test_read_7z_archive_files_timeout_logs_once_without_spam(monkeypatch):
|
||||
"""Once the shared budget is spent, no subprocess is spawned per remaining
|
||||
member and the timeout is logged a single time, not once per entry."""
|
||||
names = [f"file{i:02d}.bin" for i in range(20)]
|
||||
listing = MagicMock(stdout=_fake_7z_listing(names))
|
||||
|
||||
# Force the per-archive deadline to be already in the past.
|
||||
monkeypatch.setattr(archives, "SEVEN_ZIP_TIMEOUT", -1)
|
||||
|
||||
with (
|
||||
patch.object(archives.subprocess, "run", return_value=listing),
|
||||
patch.object(archives.subprocess, "Popen") as popen_patch,
|
||||
patch.object(archives.log, "error") as log_error,
|
||||
):
|
||||
results = list(archives.read_7z_archive_files(Path("/fake.7z"), [], []))
|
||||
|
||||
assert results == []
|
||||
popen_patch.assert_not_called()
|
||||
assert log_error.call_count == 1
|
||||
@@ -848,10 +848,8 @@ def main() -> int:
|
||||
# rows already in the target database.
|
||||
if i == 0:
|
||||
username, role = f"admin_{uid}", Role.ADMIN
|
||||
elif i <= 2:
|
||||
username, role = f"editor_{uid}", Role.EDITOR
|
||||
else:
|
||||
username, role = f"viewer_{uid}", Role.VIEWER
|
||||
username, role = f"user_{uid}", Role.USER
|
||||
created = rand_past(rng, now)
|
||||
user_rows.append(
|
||||
{
|
||||
|
||||
@@ -282,13 +282,15 @@ def read_tar_archive_files(
|
||||
|
||||
|
||||
def _stream_7z_chunks(
|
||||
process: subprocess.Popen[bytes], deadline: float
|
||||
process: subprocess.Popen[bytes],
|
||||
deadline: float,
|
||||
on_timeout: Callable[[], None],
|
||||
) -> Iterator[bytes]:
|
||||
assert process.stdout is not None
|
||||
while chunk := process.stdout.read(FILE_READ_CHUNK_SIZE):
|
||||
if time.monotonic() > deadline:
|
||||
process.terminate()
|
||||
log.error("7z extraction timed out during multi-file archive read")
|
||||
on_timeout()
|
||||
return
|
||||
yield chunk
|
||||
|
||||
@@ -350,9 +352,21 @@ def read_7z_archive_files(
|
||||
|
||||
entries.sort(key=lambda e: e[0])
|
||||
|
||||
# Single time budget for reading every member of this archive.
|
||||
deadline = time.monotonic() + SEVEN_ZIP_TIMEOUT
|
||||
timed_out = False
|
||||
|
||||
def _mark_timed_out() -> None:
|
||||
nonlocal timed_out
|
||||
timed_out = True
|
||||
|
||||
for name, size in entries:
|
||||
# Once the shared budget is spent, stop spawning a subprocess per
|
||||
# remaining member; otherwise each one trips the deadline and spams
|
||||
# an identical error line for every entry left in the archive.
|
||||
if timed_out or time.monotonic() > deadline:
|
||||
timed_out = True
|
||||
break
|
||||
try:
|
||||
with subprocess.Popen(
|
||||
[SEVEN_ZIP_PATH, "e", str(file_path), name, "-so", "-y"],
|
||||
@@ -362,8 +376,10 @@ def read_7z_archive_files(
|
||||
) as process:
|
||||
if process.stdout is None:
|
||||
continue
|
||||
yield name, size, _stream_7z_chunks(process, deadline)
|
||||
if process.returncode != 0:
|
||||
yield name, size, _stream_7z_chunks(process, deadline, _mark_timed_out)
|
||||
# A timeout terminates the subprocess, so a non-zero return code is
|
||||
# expected then and is covered by the single log below.
|
||||
if not timed_out and process.returncode != 0:
|
||||
log.error(
|
||||
f"7z extraction of {name} failed with code {process.returncode}"
|
||||
)
|
||||
@@ -372,6 +388,9 @@ def read_7z_archive_files(
|
||||
log.error(f"Error extracting {name} from {file_path}: {e}")
|
||||
continue
|
||||
|
||||
if timed_out:
|
||||
log.error(f"7z extraction timed out reading members of {file_path}")
|
||||
|
||||
|
||||
def read_rar_archive_files(
|
||||
file_path: Path,
|
||||
|
||||
@@ -43,7 +43,12 @@ setup((app) => {
|
||||
}),
|
||||
);
|
||||
|
||||
storePermissions().hydrateFromRole("admin");
|
||||
// Seed an admin so stories render with every gated control available.
|
||||
storePermissions().hydrateFromResponse({
|
||||
is_admin: true,
|
||||
grants: [],
|
||||
hidden: { platforms: [], roms: [] },
|
||||
});
|
||||
});
|
||||
|
||||
const preview: Preview = {
|
||||
|
||||
18
frontend/src/__generated__/index.ts
generated
18
frontend/src/__generated__/index.ts
generated
@@ -3,6 +3,7 @@
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
|
||||
export type { ActionKey } from './models/ActionKey';
|
||||
export type { ActivityEntrySchema } from './models/ActivityEntrySchema';
|
||||
export type { AddFirmwareResponse } from './models/AddFirmwareResponse';
|
||||
export type { Body_add_collection_api_collections_post } from './models/Body_add_collection_api_collections_post';
|
||||
@@ -20,6 +21,7 @@ export type { Body_delete_roms_api_roms_delete_post } from './models/Body_delete
|
||||
export type { Body_delete_saves_api_saves_delete_post } from './models/Body_delete_saves_api_saves_delete_post';
|
||||
export type { Body_delete_states_api_states_delete_post } from './models/Body_delete_states_api_states_delete_post';
|
||||
export type { Body_refresh_retro_achievements_api_users__id__ra_refresh_post } from './models/Body_refresh_retro_achievements_api_users__id__ra_refresh_post';
|
||||
export type { Body_remove_hidden_entity_api_permissions_hidden_delete } from './models/Body_remove_hidden_entity_api_permissions_hidden_delete';
|
||||
export type { Body_request_password_reset_api_forgot_password_post } from './models/Body_request_password_reset_api_forgot_password_post';
|
||||
export type { Body_reset_password_api_reset_password_post } from './models/Body_reset_password_api_reset_password_post';
|
||||
export type { Body_token_api_token_post } from './models/Body_token_api_token_post';
|
||||
@@ -76,7 +78,12 @@ export type { FirmwareSchema } from './models/FirmwareSchema';
|
||||
export type { FrontendDict } from './models/FrontendDict';
|
||||
export type { GenericTaskMeta } from './models/GenericTaskMeta';
|
||||
export type { GenericTaskStatusResponse } from './models/GenericTaskStatusResponse';
|
||||
export type { GrantSchema } from './models/GrantSchema';
|
||||
export type { GrantSchemaIO } from './models/GrantSchemaIO';
|
||||
export type { HeartbeatResponse } from './models/HeartbeatResponse';
|
||||
export type { HiddenEntitiesSchema } from './models/HiddenEntitiesSchema';
|
||||
export type { HiddenEntityCreate } from './models/HiddenEntityCreate';
|
||||
export type { HiddenEntitySchema } from './models/HiddenEntitySchema';
|
||||
export type { HTTPValidationError } from './models/HTTPValidationError';
|
||||
export type { IGDBAgeRating } from './models/IGDBAgeRating';
|
||||
export type { IGDBMetadataMultiplayerMode } from './models/IGDBMetadataMultiplayerMode';
|
||||
@@ -96,7 +103,16 @@ export type { NetplayICEServer } from './models/NetplayICEServer';
|
||||
export type { OIDCDict } from './models/OIDCDict';
|
||||
export type { OIDCLogoutResponse } from './models/OIDCLogoutResponse';
|
||||
export type { OrphanedResourcesCleanupStats } from './models/OrphanedResourcesCleanupStats';
|
||||
export type { OverrideSchemaIO } from './models/OverrideSchemaIO';
|
||||
export type { PatchRequest } from './models/PatchRequest';
|
||||
export type { PermAction } from './models/PermAction';
|
||||
export type { PermEntity } from './models/PermEntity';
|
||||
export type { PermissionCatalogSchema } from './models/PermissionCatalogSchema';
|
||||
export type { PermissionGroupCreate } from './models/PermissionGroupCreate';
|
||||
export type { PermissionGroupSchema } from './models/PermissionGroupSchema';
|
||||
export type { PermissionGroupUpdate } from './models/PermissionGroupUpdate';
|
||||
export type { PermissionScopeSchema } from './models/PermissionScopeSchema';
|
||||
export type { PermissionsResponse } from './models/PermissionsResponse';
|
||||
export type { PlatformBindingPayload } from './models/PlatformBindingPayload';
|
||||
export type { PlatformSchema } from './models/PlatformSchema';
|
||||
export type { PlaySessionEntry } from './models/PlaySessionEntry';
|
||||
@@ -169,6 +185,8 @@ export type { UpdateTaskStatusResponse } from './models/UpdateTaskStatusResponse
|
||||
export type { UserCollectionSchema } from './models/UserCollectionSchema';
|
||||
export type { UserForm } from './models/UserForm';
|
||||
export type { UserNoteSchema } from './models/UserNoteSchema';
|
||||
export type { UserPermissionsSchema } from './models/UserPermissionsSchema';
|
||||
export type { UserPermissionsUpdate } from './models/UserPermissionsUpdate';
|
||||
export type { UserSaveSchema } from './models/UserSaveSchema';
|
||||
export type { UserSchema } from './models/UserSchema';
|
||||
export type { UserScreenshotSchema } from './models/UserScreenshotSchema';
|
||||
|
||||
5
frontend/src/__generated__/models/ActionKey.ts
generated
Normal file
5
frontend/src/__generated__/models/ActionKey.ts
generated
Normal file
@@ -0,0 +1,5 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export type ActionKey = 'rom.view' | 'rom.play' | 'rom.download' | 'rom.upload' | 'rom.edit' | 'rom.delete' | 'rom.match' | 'rom.refresh' | 'rom.favorite' | 'platform.view' | 'platform.create' | 'platform.edit' | 'platform.delete' | 'collection.view' | 'collection.create' | 'collection.edit' | 'collection.delete' | 'library.scan' | 'user.view' | 'user.create' | 'user.edit' | 'user.delete' | 'app.admin';
|
||||
12
frontend/src/__generated__/models/Body_remove_hidden_entity_api_permissions_hidden_delete.ts
generated
Normal file
12
frontend/src/__generated__/models/Body_remove_hidden_entity_api_permissions_hidden_delete.ts
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
import type { PermEntity } from './PermEntity';
|
||||
export type Body_remove_hidden_entity_api_permissions_hidden_delete = {
|
||||
entity: PermEntity;
|
||||
entity_id: number;
|
||||
user_id?: (number | null);
|
||||
group_id?: (number | null);
|
||||
};
|
||||
|
||||
11
frontend/src/__generated__/models/GrantSchema.ts
generated
Normal file
11
frontend/src/__generated__/models/GrantSchema.ts
generated
Normal file
@@ -0,0 +1,11 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
import type { ActionKey } from './ActionKey';
|
||||
import type { PermissionScopeSchema } from './PermissionScopeSchema';
|
||||
export type GrantSchema = {
|
||||
action: ActionKey;
|
||||
scope: PermissionScopeSchema;
|
||||
};
|
||||
|
||||
15
frontend/src/__generated__/models/GrantSchemaIO.ts
generated
Normal file
15
frontend/src/__generated__/models/GrantSchemaIO.ts
generated
Normal file
@@ -0,0 +1,15 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
import type { PermAction } from './PermAction';
|
||||
import type { PermEntity } from './PermEntity';
|
||||
/**
|
||||
* A single (entity, action) grant on a group, with the own-only flag.
|
||||
*/
|
||||
export type GrantSchemaIO = {
|
||||
entity: PermEntity;
|
||||
action: PermAction;
|
||||
own_only?: boolean;
|
||||
};
|
||||
|
||||
9
frontend/src/__generated__/models/HiddenEntitiesSchema.ts
generated
Normal file
9
frontend/src/__generated__/models/HiddenEntitiesSchema.ts
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export type HiddenEntitiesSchema = {
|
||||
platforms: Array<number>;
|
||||
roms: Array<number>;
|
||||
};
|
||||
|
||||
12
frontend/src/__generated__/models/HiddenEntityCreate.ts
generated
Normal file
12
frontend/src/__generated__/models/HiddenEntityCreate.ts
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
import type { PermEntity } from './PermEntity';
|
||||
export type HiddenEntityCreate = {
|
||||
entity: PermEntity;
|
||||
entity_id: number;
|
||||
user_id?: (number | null);
|
||||
group_id?: (number | null);
|
||||
};
|
||||
|
||||
10
frontend/src/__generated__/models/HiddenEntitySchema.ts
generated
Normal file
10
frontend/src/__generated__/models/HiddenEntitySchema.ts
generated
Normal file
@@ -0,0 +1,10 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
import type { PermEntity } from './PermEntity';
|
||||
export type HiddenEntitySchema = {
|
||||
entity: PermEntity;
|
||||
entity_id: number;
|
||||
};
|
||||
|
||||
13
frontend/src/__generated__/models/OverrideSchemaIO.ts
generated
Normal file
13
frontend/src/__generated__/models/OverrideSchemaIO.ts
generated
Normal file
@@ -0,0 +1,13 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
import type { PermAction } from './PermAction';
|
||||
import type { PermEntity } from './PermEntity';
|
||||
export type OverrideSchemaIO = {
|
||||
entity: PermEntity;
|
||||
action: PermAction;
|
||||
granted: boolean;
|
||||
own_only?: boolean;
|
||||
};
|
||||
|
||||
5
frontend/src/__generated__/models/PermAction.ts
generated
Normal file
5
frontend/src/__generated__/models/PermAction.ts
generated
Normal file
@@ -0,0 +1,5 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export type PermAction = 'read' | 'write' | 'delete';
|
||||
12
frontend/src/__generated__/models/PermEntity.ts
generated
Normal file
12
frontend/src/__generated__/models/PermEntity.ts
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
/**
|
||||
* Entity-type vocabulary for granular permissions.
|
||||
*
|
||||
* Mirrors the coarse scope domains (see ``handler/auth/constants.py``) so the
|
||||
* grant matrix can be projected back onto the legacy ``Scope`` set without
|
||||
* drift (see ``handler/auth/permissions_map.py``).
|
||||
*/
|
||||
export type PermEntity = 'platforms' | 'roms' | 'collections' | 'firmware' | 'assets' | 'devices' | 'users' | 'tasks' | 'logs';
|
||||
14
frontend/src/__generated__/models/PermissionCatalogSchema.ts
generated
Normal file
14
frontend/src/__generated__/models/PermissionCatalogSchema.ts
generated
Normal file
@@ -0,0 +1,14 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
import type { PermAction } from './PermAction';
|
||||
import type { PermEntity } from './PermEntity';
|
||||
/**
|
||||
* The vocabulary the admin UI renders the group/override matrix from.
|
||||
*/
|
||||
export type PermissionCatalogSchema = {
|
||||
entities: Array<PermEntity>;
|
||||
actions: Array<PermAction>;
|
||||
};
|
||||
|
||||
13
frontend/src/__generated__/models/PermissionGroupCreate.ts
generated
Normal file
13
frontend/src/__generated__/models/PermissionGroupCreate.ts
generated
Normal file
@@ -0,0 +1,13 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
import type { GrantSchemaIO } from './GrantSchemaIO';
|
||||
export type PermissionGroupCreate = {
|
||||
name: string;
|
||||
description?: string;
|
||||
is_default?: boolean;
|
||||
color?: (string | null);
|
||||
grants?: Array<GrantSchemaIO>;
|
||||
};
|
||||
|
||||
18
frontend/src/__generated__/models/PermissionGroupSchema.ts
generated
Normal file
18
frontend/src/__generated__/models/PermissionGroupSchema.ts
generated
Normal file
@@ -0,0 +1,18 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
import type { GrantSchemaIO } from './GrantSchemaIO';
|
||||
import type { HiddenEntitySchema } from './HiddenEntitySchema';
|
||||
export type PermissionGroupSchema = {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string;
|
||||
is_default: boolean;
|
||||
is_system: boolean;
|
||||
color: (string | null);
|
||||
grants: Array<GrantSchemaIO>;
|
||||
member_count: number;
|
||||
hidden?: Array<HiddenEntitySchema>;
|
||||
};
|
||||
|
||||
13
frontend/src/__generated__/models/PermissionGroupUpdate.ts
generated
Normal file
13
frontend/src/__generated__/models/PermissionGroupUpdate.ts
generated
Normal file
@@ -0,0 +1,13 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
import type { GrantSchemaIO } from './GrantSchemaIO';
|
||||
export type PermissionGroupUpdate = {
|
||||
name?: (string | null);
|
||||
description?: (string | null);
|
||||
is_default?: (boolean | null);
|
||||
color?: (string | null);
|
||||
grants?: (Array<GrantSchemaIO> | null);
|
||||
};
|
||||
|
||||
9
frontend/src/__generated__/models/PermissionScopeSchema.ts
generated
Normal file
9
frontend/src/__generated__/models/PermissionScopeSchema.ts
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export type PermissionScopeSchema = {
|
||||
kind?: 'global' | 'platform' | 'collection' | 'rom';
|
||||
id?: (number | null);
|
||||
};
|
||||
|
||||
12
frontend/src/__generated__/models/PermissionsResponse.ts
generated
Normal file
12
frontend/src/__generated__/models/PermissionsResponse.ts
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
import type { GrantSchema } from './GrantSchema';
|
||||
import type { HiddenEntitiesSchema } from './HiddenEntitiesSchema';
|
||||
export type PermissionsResponse = {
|
||||
is_admin: boolean;
|
||||
grants: Array<GrantSchema>;
|
||||
hidden: HiddenEntitiesSchema;
|
||||
};
|
||||
|
||||
2
frontend/src/__generated__/models/Role.ts
generated
2
frontend/src/__generated__/models/Role.ts
generated
@@ -2,4 +2,4 @@
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export type Role = 'viewer' | 'editor' | 'admin';
|
||||
export type Role = 'user' | 'admin';
|
||||
|
||||
16
frontend/src/__generated__/models/UserPermissionsSchema.ts
generated
Normal file
16
frontend/src/__generated__/models/UserPermissionsSchema.ts
generated
Normal file
@@ -0,0 +1,16 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
import type { HiddenEntitySchema } from './HiddenEntitySchema';
|
||||
import type { OverrideSchemaIO } from './OverrideSchemaIO';
|
||||
/**
|
||||
* Admin view of one user's permission assignment.
|
||||
*/
|
||||
export type UserPermissionsSchema = {
|
||||
user_id: number;
|
||||
permission_group_id: (number | null);
|
||||
overrides: Array<OverrideSchemaIO>;
|
||||
hidden: Array<HiddenEntitySchema>;
|
||||
};
|
||||
|
||||
11
frontend/src/__generated__/models/UserPermissionsUpdate.ts
generated
Normal file
11
frontend/src/__generated__/models/UserPermissionsUpdate.ts
generated
Normal file
@@ -0,0 +1,11 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
import type { OverrideSchemaIO } from './OverrideSchemaIO';
|
||||
export type UserPermissionsUpdate = {
|
||||
permission_group_id?: (number | null);
|
||||
set_group?: boolean;
|
||||
overrides?: (Array<OverrideSchemaIO> | null);
|
||||
};
|
||||
|
||||
1
frontend/src/__generated__/models/UserSchema.ts
generated
1
frontend/src/__generated__/models/UserSchema.ts
generated
@@ -10,6 +10,7 @@ export type UserSchema = {
|
||||
email: (string | null);
|
||||
enabled: boolean;
|
||||
role: Role;
|
||||
permission_group_id?: (number | null);
|
||||
oauth_scopes: Array<string>;
|
||||
avatar_path: string;
|
||||
last_login: (string | null);
|
||||
|
||||
@@ -18,7 +18,7 @@ const user = ref({
|
||||
username: "",
|
||||
password: "",
|
||||
email: "",
|
||||
role: "viewer",
|
||||
role: "user",
|
||||
});
|
||||
const { lgAndUp } = useDisplay();
|
||||
const show = ref(false);
|
||||
@@ -49,7 +49,7 @@ function closeDialog() {
|
||||
username: "",
|
||||
password: "",
|
||||
email: "",
|
||||
role: "viewer",
|
||||
role: "user",
|
||||
};
|
||||
}
|
||||
</script>
|
||||
@@ -95,7 +95,7 @@ function closeDialog() {
|
||||
<v-select
|
||||
v-model="user.role"
|
||||
variant="outlined"
|
||||
:items="['viewer', 'editor', 'admin']"
|
||||
:items="['admin', 'user']"
|
||||
:label="t('settings.role')"
|
||||
required
|
||||
hide-details
|
||||
|
||||
@@ -128,7 +128,7 @@ function closeDialog() {
|
||||
<v-select
|
||||
v-model="user.role"
|
||||
variant="outlined"
|
||||
:items="['viewer', 'editor', 'admin']"
|
||||
:items="['admin', 'user']"
|
||||
:label="t('settings.role')"
|
||||
required
|
||||
class="ma-2"
|
||||
|
||||
@@ -12,7 +12,7 @@ const show = ref(false);
|
||||
const fullInviteLink = ref("");
|
||||
const selectedRole = ref("");
|
||||
const selectedExpiration = ref<number>(86400);
|
||||
const roles = ["viewer", "editor", "admin"];
|
||||
const roles = ["admin", "user"];
|
||||
const expirationOptions = [
|
||||
{ label: "1 hour", value: 3600 },
|
||||
{ label: "6 hours", value: 21600 },
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"revoke-token-confirm": "Отмяна на токена \"{name}\" за {username}?",
|
||||
"role": "Роля",
|
||||
"role-admin": "Администратор",
|
||||
"role-user": "User",
|
||||
"role-editor": "Редактор",
|
||||
"role-viewer": "Наблюдател",
|
||||
"romm-platform": "RomM платформа",
|
||||
@@ -359,5 +360,65 @@
|
||||
"widget-library-stats-mode": "Подробности за статистиката на библиотеката",
|
||||
"widget-random-pick": "Случаен избор",
|
||||
"widget-random-pick-desc": "Предлага случайна ROM от библиотеката ви, с бутон за нов избор.",
|
||||
"widget-reorder-drag": "Плъзнете за пренареждане"
|
||||
"widget-reorder-drag": "Плъзнете за пренареждане",
|
||||
"description": "Description",
|
||||
"permission-groups": "Permission Groups",
|
||||
"new-group": "New group",
|
||||
"edit-group": "Edit group",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-members": "Members",
|
||||
"group-default-tag": "Default",
|
||||
"group-system-tag": "System",
|
||||
"group-default-option": "Default group",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"search-groups": "Search groups",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"perm-entity": {
|
||||
"platforms": "Platforms",
|
||||
"roms": "Games",
|
||||
"collections": "Collections",
|
||||
"firmware": "Firmware",
|
||||
"assets": "Saves & states",
|
||||
"devices": "Devices",
|
||||
"users": "Users",
|
||||
"tasks": "Tasks",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"perm-action": {
|
||||
"read": "Read",
|
||||
"write": "Write",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"grant-none": "Not granted",
|
||||
"grant-full": "Full access",
|
||||
"grant-own": "Own items only",
|
||||
"access": "Access",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"group-color": "Color",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-revoke": "Revoked",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide"
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"revoke-token-confirm": "Zrušit token „{name}“ pro {username}?",
|
||||
"role": "Role",
|
||||
"role-admin": "Admin",
|
||||
"role-user": "User",
|
||||
"role-editor": "Editor",
|
||||
"role-viewer": "Pozorovatel",
|
||||
"romm-platform": "Platforma RomM",
|
||||
@@ -359,5 +360,65 @@
|
||||
"widget-library-stats-mode": "Podrobnosti statistik knihovny",
|
||||
"widget-random-pick": "Náhodný výběr",
|
||||
"widget-random-pick-desc": "Navrhne náhodnou ROM z vaší knihovny s tlačítkem pro nový výběr.",
|
||||
"widget-reorder-drag": "Přetažením změníte pořadí"
|
||||
"widget-reorder-drag": "Přetažením změníte pořadí",
|
||||
"description": "Description",
|
||||
"permission-groups": "Permission Groups",
|
||||
"new-group": "New group",
|
||||
"edit-group": "Edit group",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-members": "Members",
|
||||
"group-default-tag": "Default",
|
||||
"group-system-tag": "System",
|
||||
"group-default-option": "Default group",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"search-groups": "Search groups",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"perm-entity": {
|
||||
"platforms": "Platforms",
|
||||
"roms": "Games",
|
||||
"collections": "Collections",
|
||||
"firmware": "Firmware",
|
||||
"assets": "Saves & states",
|
||||
"devices": "Devices",
|
||||
"users": "Users",
|
||||
"tasks": "Tasks",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"perm-action": {
|
||||
"read": "Read",
|
||||
"write": "Write",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"grant-none": "Not granted",
|
||||
"grant-full": "Full access",
|
||||
"grant-own": "Own items only",
|
||||
"access": "Access",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"group-color": "Color",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-revoke": "Revoked",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide"
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"revoke-token-confirm": "Token \"{name}\" für {username} widerrufen?",
|
||||
"role": "Rolle",
|
||||
"role-admin": "Admin",
|
||||
"role-user": "User",
|
||||
"role-editor": "Editor",
|
||||
"role-viewer": "Betrachter",
|
||||
"romm-platform": "RomM Plattform",
|
||||
@@ -359,5 +360,65 @@
|
||||
"widget-library-stats-mode": "Bibliotheksstatistik-Details",
|
||||
"widget-random-pick": "Zufallsauswahl",
|
||||
"widget-random-pick-desc": "Schlägt eine zufällige ROM aus deiner Bibliothek vor, mit einer Schaltfläche zum neuen Würfeln.",
|
||||
"widget-reorder-drag": "Zum Umsortieren ziehen"
|
||||
"widget-reorder-drag": "Zum Umsortieren ziehen",
|
||||
"description": "Description",
|
||||
"permission-groups": "Permission Groups",
|
||||
"new-group": "New group",
|
||||
"edit-group": "Edit group",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-members": "Members",
|
||||
"group-default-tag": "Default",
|
||||
"group-system-tag": "System",
|
||||
"group-default-option": "Default group",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"search-groups": "Search groups",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"perm-entity": {
|
||||
"platforms": "Platforms",
|
||||
"roms": "Games",
|
||||
"collections": "Collections",
|
||||
"firmware": "Firmware",
|
||||
"assets": "Saves & states",
|
||||
"devices": "Devices",
|
||||
"users": "Users",
|
||||
"tasks": "Tasks",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"perm-action": {
|
||||
"read": "Read",
|
||||
"write": "Write",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"grant-none": "Not granted",
|
||||
"grant-full": "Full access",
|
||||
"grant-own": "Own items only",
|
||||
"access": "Access",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"group-color": "Color",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-revoke": "Revoked",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide"
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"revoke-token-confirm": "Revoke token \"{name}\" for {username}?",
|
||||
"role": "Role",
|
||||
"role-admin": "Admin",
|
||||
"role-user": "User",
|
||||
"role-editor": "Editor",
|
||||
"role-viewer": "Viewer",
|
||||
"romm-platform": "RomM platform",
|
||||
@@ -359,5 +360,65 @@
|
||||
"widget-library-stats-mode": "Library stats detail",
|
||||
"widget-random-pick": "Random pick",
|
||||
"widget-random-pick-desc": "Suggest a random ROM from your library, with a reroll button to shuffle again.",
|
||||
"widget-reorder-drag": "Drag to reorder"
|
||||
"widget-reorder-drag": "Drag to reorder",
|
||||
"description": "Description",
|
||||
"permission-groups": "Permission Groups",
|
||||
"new-group": "New group",
|
||||
"edit-group": "Edit group",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-members": "Members",
|
||||
"group-default-tag": "Default",
|
||||
"group-system-tag": "System",
|
||||
"group-default-option": "Default group",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"search-groups": "Search groups",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"perm-entity": {
|
||||
"platforms": "Platforms",
|
||||
"roms": "Games",
|
||||
"collections": "Collections",
|
||||
"firmware": "Firmware",
|
||||
"assets": "Saves & states",
|
||||
"devices": "Devices",
|
||||
"users": "Users",
|
||||
"tasks": "Tasks",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"perm-action": {
|
||||
"read": "Read",
|
||||
"write": "Write",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"grant-none": "Not granted",
|
||||
"grant-full": "Full access",
|
||||
"grant-own": "Own items only",
|
||||
"access": "Access",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"group-color": "Color",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-revoke": "Revoked",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide"
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"revoke-token-confirm": "Revoke token \"{name}\" for {username}?",
|
||||
"role": "Role",
|
||||
"role-admin": "Admin",
|
||||
"role-user": "User",
|
||||
"role-editor": "Editor",
|
||||
"role-viewer": "Viewer",
|
||||
"romm-platform": "RomM platform",
|
||||
@@ -359,5 +360,65 @@
|
||||
"widget-library-stats-mode": "Library stats detail",
|
||||
"widget-random-pick": "Random pick",
|
||||
"widget-random-pick-desc": "Suggest a random ROM from your library, with a reroll button to shuffle again.",
|
||||
"widget-reorder-drag": "Drag to reorder"
|
||||
"widget-reorder-drag": "Drag to reorder",
|
||||
"description": "Description",
|
||||
"permission-groups": "Permission Groups",
|
||||
"new-group": "New group",
|
||||
"edit-group": "Edit group",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-members": "Members",
|
||||
"group-default-tag": "Default",
|
||||
"group-system-tag": "System",
|
||||
"group-default-option": "Default group",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"search-groups": "Search groups",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"perm-entity": {
|
||||
"platforms": "Platforms",
|
||||
"roms": "Games",
|
||||
"collections": "Collections",
|
||||
"firmware": "Firmware",
|
||||
"assets": "Saves & states",
|
||||
"devices": "Devices",
|
||||
"users": "Users",
|
||||
"tasks": "Tasks",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"perm-action": {
|
||||
"read": "Read",
|
||||
"write": "Write",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"grant-none": "Not granted",
|
||||
"grant-full": "Full access",
|
||||
"grant-own": "Own items only",
|
||||
"access": "Access",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"group-color": "Color",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-revoke": "Revoked",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide"
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"revoke-token-confirm": "Esto revocará el token. Cualquier dispositivo que lo use perderá el acceso.",
|
||||
"role": "Rol",
|
||||
"role-admin": "Administrador",
|
||||
"role-user": "User",
|
||||
"role-editor": "Editor",
|
||||
"role-viewer": "Espectador",
|
||||
"romm-platform": "Plataforma en RomM",
|
||||
@@ -359,5 +360,65 @@
|
||||
"widget-library-stats-mode": "Detalle de estadísticas de la biblioteca",
|
||||
"widget-random-pick": "Selección aleatoria",
|
||||
"widget-random-pick-desc": "Sugiere una ROM aleatoria de tu biblioteca, con un botón para volver a sortear.",
|
||||
"widget-reorder-drag": "Arrastra para reordenar"
|
||||
"widget-reorder-drag": "Arrastra para reordenar",
|
||||
"description": "Description",
|
||||
"permission-groups": "Permission Groups",
|
||||
"new-group": "New group",
|
||||
"edit-group": "Edit group",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-members": "Members",
|
||||
"group-default-tag": "Default",
|
||||
"group-system-tag": "System",
|
||||
"group-default-option": "Default group",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"search-groups": "Search groups",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"perm-entity": {
|
||||
"platforms": "Platforms",
|
||||
"roms": "Games",
|
||||
"collections": "Collections",
|
||||
"firmware": "Firmware",
|
||||
"assets": "Saves & states",
|
||||
"devices": "Devices",
|
||||
"users": "Users",
|
||||
"tasks": "Tasks",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"perm-action": {
|
||||
"read": "Read",
|
||||
"write": "Write",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"grant-none": "Not granted",
|
||||
"grant-full": "Full access",
|
||||
"grant-own": "Own items only",
|
||||
"access": "Access",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"group-color": "Color",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-revoke": "Revoked",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide"
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"revoke-token-confirm": "Révoquer le token « {name} » pour {username} ?",
|
||||
"role": "Rôle",
|
||||
"role-admin": "Administrateur",
|
||||
"role-user": "User",
|
||||
"role-editor": "Éditeur",
|
||||
"role-viewer": "Lecteur",
|
||||
"romm-platform": "Plateforme RomM",
|
||||
@@ -359,5 +360,65 @@
|
||||
"widget-library-stats-mode": "Détail des statistiques de la bibliothèque",
|
||||
"widget-random-pick": "Choix aléatoire",
|
||||
"widget-random-pick-desc": "Suggère une ROM aléatoire de votre bibliothèque, avec un bouton pour relancer.",
|
||||
"widget-reorder-drag": "Glissez pour réorganiser"
|
||||
"widget-reorder-drag": "Glissez pour réorganiser",
|
||||
"description": "Description",
|
||||
"permission-groups": "Permission Groups",
|
||||
"new-group": "New group",
|
||||
"edit-group": "Edit group",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-members": "Members",
|
||||
"group-default-tag": "Default",
|
||||
"group-system-tag": "System",
|
||||
"group-default-option": "Default group",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"search-groups": "Search groups",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"perm-entity": {
|
||||
"platforms": "Platforms",
|
||||
"roms": "Games",
|
||||
"collections": "Collections",
|
||||
"firmware": "Firmware",
|
||||
"assets": "Saves & states",
|
||||
"devices": "Devices",
|
||||
"users": "Users",
|
||||
"tasks": "Tasks",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"perm-action": {
|
||||
"read": "Read",
|
||||
"write": "Write",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"grant-none": "Not granted",
|
||||
"grant-full": "Full access",
|
||||
"grant-own": "Own items only",
|
||||
"access": "Access",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"group-color": "Color",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-revoke": "Revoked",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide"
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"revoke-token-confirm": "Visszavonod a(z) „{name}” tokent {username} felhasználótól?",
|
||||
"role": "Szerepkör",
|
||||
"role-admin": "Admin",
|
||||
"role-user": "User",
|
||||
"role-editor": "Szerkesztő",
|
||||
"role-viewer": "Megtekintő",
|
||||
"romm-platform": "RomM platform",
|
||||
@@ -359,5 +360,65 @@
|
||||
"widget-library-stats-mode": "Könyvtárstatisztika részletei",
|
||||
"widget-random-pick": "Véletlen választás",
|
||||
"widget-random-pick-desc": "Véletlenszerű ROM-ot ajánl a könyvtáradból, újradobás gombbal.",
|
||||
"widget-reorder-drag": "Húzd az átrendezéshez"
|
||||
"widget-reorder-drag": "Húzd az átrendezéshez",
|
||||
"description": "Description",
|
||||
"permission-groups": "Permission Groups",
|
||||
"new-group": "New group",
|
||||
"edit-group": "Edit group",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-members": "Members",
|
||||
"group-default-tag": "Default",
|
||||
"group-system-tag": "System",
|
||||
"group-default-option": "Default group",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"search-groups": "Search groups",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"perm-entity": {
|
||||
"platforms": "Platforms",
|
||||
"roms": "Games",
|
||||
"collections": "Collections",
|
||||
"firmware": "Firmware",
|
||||
"assets": "Saves & states",
|
||||
"devices": "Devices",
|
||||
"users": "Users",
|
||||
"tasks": "Tasks",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"perm-action": {
|
||||
"read": "Read",
|
||||
"write": "Write",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"grant-none": "Not granted",
|
||||
"grant-full": "Full access",
|
||||
"grant-own": "Own items only",
|
||||
"access": "Access",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"group-color": "Color",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-revoke": "Revoked",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide"
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"revoke-token-confirm": "Revocare il token \"{name}\" per {username}?",
|
||||
"role": "Ruolo",
|
||||
"role-admin": "Amministratore",
|
||||
"role-user": "User",
|
||||
"role-editor": "Editor",
|
||||
"role-viewer": "Visualizzatore",
|
||||
"romm-platform": "Piattaforma RomM",
|
||||
@@ -359,5 +360,65 @@
|
||||
"widget-library-stats-mode": "Dettaglio statistiche della libreria",
|
||||
"widget-random-pick": "Scelta casuale",
|
||||
"widget-random-pick-desc": "Suggerisce una ROM casuale dalla tua libreria, con un pulsante per rilanciare.",
|
||||
"widget-reorder-drag": "Trascina per riordinare"
|
||||
"widget-reorder-drag": "Trascina per riordinare",
|
||||
"description": "Description",
|
||||
"permission-groups": "Permission Groups",
|
||||
"new-group": "New group",
|
||||
"edit-group": "Edit group",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-members": "Members",
|
||||
"group-default-tag": "Default",
|
||||
"group-system-tag": "System",
|
||||
"group-default-option": "Default group",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"search-groups": "Search groups",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"perm-entity": {
|
||||
"platforms": "Platforms",
|
||||
"roms": "Games",
|
||||
"collections": "Collections",
|
||||
"firmware": "Firmware",
|
||||
"assets": "Saves & states",
|
||||
"devices": "Devices",
|
||||
"users": "Users",
|
||||
"tasks": "Tasks",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"perm-action": {
|
||||
"read": "Read",
|
||||
"write": "Write",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"grant-none": "Not granted",
|
||||
"grant-full": "Full access",
|
||||
"grant-own": "Own items only",
|
||||
"access": "Access",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"group-color": "Color",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-revoke": "Revoked",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide"
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"revoke-token-confirm": "{username}のトークン「{name}」を取り消しますか?",
|
||||
"role": "役割",
|
||||
"role-admin": "管理者",
|
||||
"role-user": "User",
|
||||
"role-editor": "編集者",
|
||||
"role-viewer": "閲覧者",
|
||||
"romm-platform": "RomM プラットフォーム",
|
||||
@@ -359,5 +360,65 @@
|
||||
"widget-library-stats-mode": "ライブラリ統計の詳細",
|
||||
"widget-random-pick": "ランダムピック",
|
||||
"widget-random-pick-desc": "ライブラリからランダムな ROM を提案します。引き直しボタンで再抽選できます。",
|
||||
"widget-reorder-drag": "ドラッグして並べ替え"
|
||||
"widget-reorder-drag": "ドラッグして並べ替え",
|
||||
"description": "Description",
|
||||
"permission-groups": "Permission Groups",
|
||||
"new-group": "New group",
|
||||
"edit-group": "Edit group",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-members": "Members",
|
||||
"group-default-tag": "Default",
|
||||
"group-system-tag": "System",
|
||||
"group-default-option": "Default group",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"search-groups": "Search groups",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"perm-entity": {
|
||||
"platforms": "Platforms",
|
||||
"roms": "Games",
|
||||
"collections": "Collections",
|
||||
"firmware": "Firmware",
|
||||
"assets": "Saves & states",
|
||||
"devices": "Devices",
|
||||
"users": "Users",
|
||||
"tasks": "Tasks",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"perm-action": {
|
||||
"read": "Read",
|
||||
"write": "Write",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"grant-none": "Not granted",
|
||||
"grant-full": "Full access",
|
||||
"grant-own": "Own items only",
|
||||
"access": "Access",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"group-color": "Color",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-revoke": "Revoked",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide"
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"revoke-token-confirm": "{username}의 토큰 \"{name}\"을(를) 폐기하시겠습니까?",
|
||||
"role": "역할",
|
||||
"role-admin": "관리자",
|
||||
"role-user": "User",
|
||||
"role-editor": "편집자",
|
||||
"role-viewer": "뷰어",
|
||||
"romm-platform": "RomM 플랫폼",
|
||||
@@ -359,5 +360,65 @@
|
||||
"widget-library-stats-mode": "라이브러리 통계 세부 정보",
|
||||
"widget-random-pick": "랜덤 선택",
|
||||
"widget-random-pick-desc": "라이브러리에서 무작위 ROM을 추천하며, 다시 뽑기 버튼으로 다시 섞을 수 있습니다.",
|
||||
"widget-reorder-drag": "드래그하여 순서 변경"
|
||||
"widget-reorder-drag": "드래그하여 순서 변경",
|
||||
"description": "Description",
|
||||
"permission-groups": "Permission Groups",
|
||||
"new-group": "New group",
|
||||
"edit-group": "Edit group",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-members": "Members",
|
||||
"group-default-tag": "Default",
|
||||
"group-system-tag": "System",
|
||||
"group-default-option": "Default group",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"search-groups": "Search groups",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"perm-entity": {
|
||||
"platforms": "Platforms",
|
||||
"roms": "Games",
|
||||
"collections": "Collections",
|
||||
"firmware": "Firmware",
|
||||
"assets": "Saves & states",
|
||||
"devices": "Devices",
|
||||
"users": "Users",
|
||||
"tasks": "Tasks",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"perm-action": {
|
||||
"read": "Read",
|
||||
"write": "Write",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"grant-none": "Not granted",
|
||||
"grant-full": "Full access",
|
||||
"grant-own": "Own items only",
|
||||
"access": "Access",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"group-color": "Color",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-revoke": "Revoked",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide"
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"revoke-token-confirm": "Unieważnić token \"{name}\" dla {username}?",
|
||||
"role": "Rola",
|
||||
"role-admin": "Administrator",
|
||||
"role-user": "User",
|
||||
"role-editor": "Edytor",
|
||||
"role-viewer": "Obserwator",
|
||||
"romm-platform": "Platforma RomM",
|
||||
@@ -359,5 +360,65 @@
|
||||
"widget-library-stats-mode": "Szczegóły statystyk biblioteki",
|
||||
"widget-random-pick": "Losowy wybór",
|
||||
"widget-random-pick-desc": "Proponuje losową ROM z Twojej biblioteki, z przyciskiem ponownego losowania.",
|
||||
"widget-reorder-drag": "Przeciągnij, aby zmienić kolejność"
|
||||
"widget-reorder-drag": "Przeciągnij, aby zmienić kolejność",
|
||||
"description": "Description",
|
||||
"permission-groups": "Permission Groups",
|
||||
"new-group": "New group",
|
||||
"edit-group": "Edit group",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-members": "Members",
|
||||
"group-default-tag": "Default",
|
||||
"group-system-tag": "System",
|
||||
"group-default-option": "Default group",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"search-groups": "Search groups",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"perm-entity": {
|
||||
"platforms": "Platforms",
|
||||
"roms": "Games",
|
||||
"collections": "Collections",
|
||||
"firmware": "Firmware",
|
||||
"assets": "Saves & states",
|
||||
"devices": "Devices",
|
||||
"users": "Users",
|
||||
"tasks": "Tasks",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"perm-action": {
|
||||
"read": "Read",
|
||||
"write": "Write",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"grant-none": "Not granted",
|
||||
"grant-full": "Full access",
|
||||
"grant-own": "Own items only",
|
||||
"access": "Access",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"group-color": "Color",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-revoke": "Revoked",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide"
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"revoke-token-confirm": "Revogar o token \"{name}\" de {username}?",
|
||||
"role": "Papel",
|
||||
"role-admin": "Administrador",
|
||||
"role-user": "User",
|
||||
"role-editor": "Editor",
|
||||
"role-viewer": "Visualizador",
|
||||
"romm-platform": "Plataforma RomM",
|
||||
@@ -359,5 +360,65 @@
|
||||
"widget-library-stats-mode": "Detalhes das estatísticas da biblioteca",
|
||||
"widget-random-pick": "Escolha aleatória",
|
||||
"widget-random-pick-desc": "Sugere uma ROM aleatória da sua biblioteca, com um botão para sortear novamente.",
|
||||
"widget-reorder-drag": "Arraste para reordenar"
|
||||
"widget-reorder-drag": "Arraste para reordenar",
|
||||
"description": "Description",
|
||||
"permission-groups": "Permission Groups",
|
||||
"new-group": "New group",
|
||||
"edit-group": "Edit group",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-members": "Members",
|
||||
"group-default-tag": "Default",
|
||||
"group-system-tag": "System",
|
||||
"group-default-option": "Default group",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"search-groups": "Search groups",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"perm-entity": {
|
||||
"platforms": "Platforms",
|
||||
"roms": "Games",
|
||||
"collections": "Collections",
|
||||
"firmware": "Firmware",
|
||||
"assets": "Saves & states",
|
||||
"devices": "Devices",
|
||||
"users": "Users",
|
||||
"tasks": "Tasks",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"perm-action": {
|
||||
"read": "Read",
|
||||
"write": "Write",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"grant-none": "Not granted",
|
||||
"grant-full": "Full access",
|
||||
"grant-own": "Own items only",
|
||||
"access": "Access",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"group-color": "Color",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-revoke": "Revoked",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide"
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"revoke-token-confirm": "Revoci token-ul „{name}” pentru {username}?",
|
||||
"role": "Rol",
|
||||
"role-admin": "Administrator",
|
||||
"role-user": "User",
|
||||
"role-editor": "Editor",
|
||||
"role-viewer": "Vizualizator",
|
||||
"romm-platform": "Platformă RomM",
|
||||
@@ -359,5 +360,65 @@
|
||||
"widget-library-stats-mode": "Detalii statistici bibliotecă",
|
||||
"widget-random-pick": "Alegere aleatorie",
|
||||
"widget-random-pick-desc": "Sugerează o ROM aleatorie din biblioteca ta, cu un buton pentru a alege din nou.",
|
||||
"widget-reorder-drag": "Trage pentru a reordona"
|
||||
"widget-reorder-drag": "Trage pentru a reordona",
|
||||
"description": "Description",
|
||||
"permission-groups": "Permission Groups",
|
||||
"new-group": "New group",
|
||||
"edit-group": "Edit group",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-members": "Members",
|
||||
"group-default-tag": "Default",
|
||||
"group-system-tag": "System",
|
||||
"group-default-option": "Default group",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"search-groups": "Search groups",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"perm-entity": {
|
||||
"platforms": "Platforms",
|
||||
"roms": "Games",
|
||||
"collections": "Collections",
|
||||
"firmware": "Firmware",
|
||||
"assets": "Saves & states",
|
||||
"devices": "Devices",
|
||||
"users": "Users",
|
||||
"tasks": "Tasks",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"perm-action": {
|
||||
"read": "Read",
|
||||
"write": "Write",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"grant-none": "Not granted",
|
||||
"grant-full": "Full access",
|
||||
"grant-own": "Own items only",
|
||||
"access": "Access",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"group-color": "Color",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-revoke": "Revoked",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide"
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"revoke-token-confirm": "Отозвать токен \"{name}\" у {username}?",
|
||||
"role": "Роль",
|
||||
"role-admin": "Администратор",
|
||||
"role-user": "User",
|
||||
"role-editor": "Редактор",
|
||||
"role-viewer": "Наблюдатель",
|
||||
"romm-platform": "Платформа RomM",
|
||||
@@ -359,5 +360,65 @@
|
||||
"widget-library-stats-mode": "Подробности статистики библиотеки",
|
||||
"widget-random-pick": "Случайный выбор",
|
||||
"widget-random-pick-desc": "Предлагает случайную ROM из вашей библиотеки с кнопкой повторного выбора.",
|
||||
"widget-reorder-drag": "Перетащите для изменения порядка"
|
||||
"widget-reorder-drag": "Перетащите для изменения порядка",
|
||||
"description": "Description",
|
||||
"permission-groups": "Permission Groups",
|
||||
"new-group": "New group",
|
||||
"edit-group": "Edit group",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-members": "Members",
|
||||
"group-default-tag": "Default",
|
||||
"group-system-tag": "System",
|
||||
"group-default-option": "Default group",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"search-groups": "Search groups",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"perm-entity": {
|
||||
"platforms": "Platforms",
|
||||
"roms": "Games",
|
||||
"collections": "Collections",
|
||||
"firmware": "Firmware",
|
||||
"assets": "Saves & states",
|
||||
"devices": "Devices",
|
||||
"users": "Users",
|
||||
"tasks": "Tasks",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"perm-action": {
|
||||
"read": "Read",
|
||||
"write": "Write",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"grant-none": "Not granted",
|
||||
"grant-full": "Full access",
|
||||
"grant-own": "Own items only",
|
||||
"access": "Access",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"group-color": "Color",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-revoke": "Revoked",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide"
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"revoke-token-confirm": "{username} için \"{name}\" tokenı iptal edilsin mi?",
|
||||
"role": "Rol",
|
||||
"role-admin": "Yönetici",
|
||||
"role-user": "User",
|
||||
"role-editor": "Editör",
|
||||
"role-viewer": "İzleyici",
|
||||
"romm-platform": "RomM platformu",
|
||||
@@ -359,5 +360,65 @@
|
||||
"widget-library-stats-mode": "Kütüphane istatistikleri detayı",
|
||||
"widget-random-pick": "Rastgele seçim",
|
||||
"widget-random-pick-desc": "Kütüphanenizden rastgele bir ROM öner, yeniden çevirmek için düğmeye basın.",
|
||||
"widget-reorder-drag": "Yeniden sıralamak için sürükleyin"
|
||||
"widget-reorder-drag": "Yeniden sıralamak için sürükleyin",
|
||||
"description": "Description",
|
||||
"permission-groups": "Permission Groups",
|
||||
"new-group": "New group",
|
||||
"edit-group": "Edit group",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-members": "Members",
|
||||
"group-default-tag": "Default",
|
||||
"group-system-tag": "System",
|
||||
"group-default-option": "Default group",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"search-groups": "Search groups",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"perm-entity": {
|
||||
"platforms": "Platforms",
|
||||
"roms": "Games",
|
||||
"collections": "Collections",
|
||||
"firmware": "Firmware",
|
||||
"assets": "Saves & states",
|
||||
"devices": "Devices",
|
||||
"users": "Users",
|
||||
"tasks": "Tasks",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"perm-action": {
|
||||
"read": "Read",
|
||||
"write": "Write",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"grant-none": "Not granted",
|
||||
"grant-full": "Full access",
|
||||
"grant-own": "Own items only",
|
||||
"access": "Access",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"group-color": "Color",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-revoke": "Revoked",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide"
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"revoke-token-confirm": "确定要吊销 {username} 的令牌 \"{name}\" 吗?",
|
||||
"role": "角色",
|
||||
"role-admin": "管理员",
|
||||
"role-user": "User",
|
||||
"role-editor": "编辑者",
|
||||
"role-viewer": "查看者",
|
||||
"romm-platform": "RomM 平台",
|
||||
@@ -359,5 +360,65 @@
|
||||
"widget-library-stats-mode": "库统计详情",
|
||||
"widget-random-pick": "随机推荐",
|
||||
"widget-random-pick-desc": "从你的库中随机推荐一个 ROM,并提供重新抽取按钮。",
|
||||
"widget-reorder-drag": "拖动以重新排序"
|
||||
"widget-reorder-drag": "拖动以重新排序",
|
||||
"description": "Description",
|
||||
"permission-groups": "Permission Groups",
|
||||
"new-group": "New group",
|
||||
"edit-group": "Edit group",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-members": "Members",
|
||||
"group-default-tag": "Default",
|
||||
"group-system-tag": "System",
|
||||
"group-default-option": "Default group",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"search-groups": "Search groups",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"perm-entity": {
|
||||
"platforms": "Platforms",
|
||||
"roms": "Games",
|
||||
"collections": "Collections",
|
||||
"firmware": "Firmware",
|
||||
"assets": "Saves & states",
|
||||
"devices": "Devices",
|
||||
"users": "Users",
|
||||
"tasks": "Tasks",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"perm-action": {
|
||||
"read": "Read",
|
||||
"write": "Write",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"grant-none": "Not granted",
|
||||
"grant-full": "Full access",
|
||||
"grant-own": "Own items only",
|
||||
"access": "Access",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"group-color": "Color",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-revoke": "Revoked",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide"
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@
|
||||
"revoke-token-confirm": "為 {username} 撤銷權杖「{name}」?",
|
||||
"role": "角色",
|
||||
"role-admin": "管理員",
|
||||
"role-user": "User",
|
||||
"role-editor": "編輯者",
|
||||
"role-viewer": "檢視者",
|
||||
"romm-platform": "RomM 平台",
|
||||
@@ -359,5 +360,65 @@
|
||||
"widget-library-stats-mode": "庫統計詳情",
|
||||
"widget-random-pick": "隨機推薦",
|
||||
"widget-random-pick-desc": "從你的庫中隨機推薦一個 ROM,並提供重新抽取按鈕。",
|
||||
"widget-reorder-drag": "拖曳以重新排序"
|
||||
"widget-reorder-drag": "拖曳以重新排序",
|
||||
"description": "Description",
|
||||
"permission-groups": "Permission Groups",
|
||||
"new-group": "New group",
|
||||
"edit-group": "Edit group",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-members": "Members",
|
||||
"group-default-tag": "Default",
|
||||
"group-system-tag": "System",
|
||||
"group-default-option": "Default group",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"search-groups": "Search groups",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"perm-entity": {
|
||||
"platforms": "Platforms",
|
||||
"roms": "Games",
|
||||
"collections": "Collections",
|
||||
"firmware": "Firmware",
|
||||
"assets": "Saves & states",
|
||||
"devices": "Devices",
|
||||
"users": "Users",
|
||||
"tasks": "Tasks",
|
||||
"logs": "Logs"
|
||||
},
|
||||
"perm-action": {
|
||||
"read": "Read",
|
||||
"write": "Write",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"grant-none": "Not granted",
|
||||
"grant-full": "Full access",
|
||||
"grant-own": "Own items only",
|
||||
"access": "Access",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"group-color": "Color",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-revoke": "Revoked",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide"
|
||||
}
|
||||
|
||||
75
frontend/src/services/api/permissions.ts
Normal file
75
frontend/src/services/api/permissions.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import type {
|
||||
Body_remove_hidden_entity_api_permissions_hidden_delete as RemoveHiddenBody,
|
||||
HiddenEntityCreate,
|
||||
HiddenEntitySchema,
|
||||
PermissionCatalogSchema,
|
||||
PermissionGroupCreate,
|
||||
PermissionGroupSchema,
|
||||
PermissionGroupUpdate,
|
||||
PermissionsResponse,
|
||||
UserPermissionsSchema,
|
||||
UserPermissionsUpdate,
|
||||
} from "@/__generated__";
|
||||
import api from "@/services/api";
|
||||
|
||||
// The caller's effective permissions (granted action keys + hidden ids). The
|
||||
// backend is the source of truth; the UI uses this only to gate what it shows.
|
||||
async function fetchMyPermissions() {
|
||||
return api.get<PermissionsResponse>("/permissions/me");
|
||||
}
|
||||
|
||||
// --- Admin: catalog + groups -------------------------------------------------
|
||||
|
||||
async function fetchCatalog() {
|
||||
return api.get<PermissionCatalogSchema>("/permissions/catalog");
|
||||
}
|
||||
|
||||
async function fetchGroups() {
|
||||
return api.get<PermissionGroupSchema[]>("/permissions/groups");
|
||||
}
|
||||
|
||||
async function createGroup(body: PermissionGroupCreate) {
|
||||
return api.post<PermissionGroupSchema>("/permissions/groups", body);
|
||||
}
|
||||
|
||||
async function updateGroup(id: number, body: PermissionGroupUpdate) {
|
||||
return api.put<PermissionGroupSchema>(`/permissions/groups/${id}`, body);
|
||||
}
|
||||
|
||||
async function deleteGroup(id: number) {
|
||||
return api.delete(`/permissions/groups/${id}`);
|
||||
}
|
||||
|
||||
// --- Admin: per-user assignment + hiding -------------------------------------
|
||||
|
||||
async function fetchUserPermissions(userId: number) {
|
||||
return api.get<UserPermissionsSchema>(`/permissions/users/${userId}`);
|
||||
}
|
||||
|
||||
async function updateUserPermissions(
|
||||
userId: number,
|
||||
body: UserPermissionsUpdate,
|
||||
) {
|
||||
return api.put<UserPermissionsSchema>(`/permissions/users/${userId}`, body);
|
||||
}
|
||||
|
||||
async function addHiddenEntity(body: HiddenEntityCreate) {
|
||||
return api.post<HiddenEntitySchema>("/permissions/hidden", body);
|
||||
}
|
||||
|
||||
async function removeHiddenEntity(body: RemoveHiddenBody) {
|
||||
return api.delete("/permissions/hidden", { data: body });
|
||||
}
|
||||
|
||||
export default {
|
||||
fetchMyPermissions,
|
||||
fetchCatalog,
|
||||
fetchGroups,
|
||||
createGroup,
|
||||
updateGroup,
|
||||
deleteGroup,
|
||||
fetchUserPermissions,
|
||||
updateUserPermissions,
|
||||
addHiddenEntity,
|
||||
removeHiddenEntity,
|
||||
};
|
||||
73
frontend/src/stores/permissionGroups.ts
Normal file
73
frontend/src/stores/permissionGroups.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
// permissionGroups — Pinia store holding the admin list of permission groups.
|
||||
//
|
||||
// Single source of truth shared by the groups table, the user create/edit
|
||||
// dialogs and the users table, so creating or deleting a group is reflected
|
||||
// everywhere immediately (no manual refetch / page refresh). Mutations go
|
||||
// through `upsert` / `remove` after the API call returns.
|
||||
import { defineStore } from "pinia";
|
||||
import type { PermissionGroupSchema } from "@/__generated__";
|
||||
import permissionsApi from "@/services/api/permissions";
|
||||
|
||||
// Shared in-flight fetch so concurrent `ensureLoaded()` callers await the same
|
||||
// request instead of racing past it with an empty list. Kept out of reactive
|
||||
// state (a Promise has no business being reactive).
|
||||
let inflight: Promise<void> | null = null;
|
||||
|
||||
export default defineStore("permissionGroups", {
|
||||
state: () => ({
|
||||
groups: [] as PermissionGroupSchema[],
|
||||
loaded: false,
|
||||
loading: false,
|
||||
}),
|
||||
|
||||
getters: {
|
||||
defaultGroup: (state) => state.groups.find((g) => g.is_default),
|
||||
},
|
||||
|
||||
actions: {
|
||||
/** Fetch the canonical list and replace the store. */
|
||||
async fetch() {
|
||||
this.loading = true;
|
||||
try {
|
||||
const { data } = await permissionsApi.fetchGroups();
|
||||
this.groups = data;
|
||||
this.loaded = true;
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/** Fetch once; concurrent callers await the same in-flight request. */
|
||||
async ensureLoaded() {
|
||||
if (this.loaded) return;
|
||||
if (!inflight) {
|
||||
inflight = this.fetch().finally(() => {
|
||||
inflight = null;
|
||||
});
|
||||
}
|
||||
await inflight;
|
||||
},
|
||||
|
||||
set(groups: PermissionGroupSchema[]) {
|
||||
this.groups = groups;
|
||||
this.loaded = true;
|
||||
},
|
||||
|
||||
/** Insert a new group or replace an existing one (by id). */
|
||||
upsert(group: PermissionGroupSchema) {
|
||||
const i = this.groups.findIndex((g) => g.id === group.id);
|
||||
if (i >= 0) this.groups[i] = group;
|
||||
else this.groups = this.groups.concat(group);
|
||||
},
|
||||
|
||||
remove(id: number) {
|
||||
this.groups = this.groups.filter((g) => g.id !== id);
|
||||
},
|
||||
|
||||
reset() {
|
||||
this.groups = [];
|
||||
this.loaded = false;
|
||||
inflight = null;
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -1,59 +1,65 @@
|
||||
// permissions — Pinia store holding the current user's effective grants.
|
||||
//
|
||||
// Today the grants are derived from `user.role` via a hardcoded role-map
|
||||
// in src/v2/composables/useCan/role-map.ts. When the backend ships
|
||||
// `/permissions/me` returning normalised grants, that response replaces
|
||||
// the role-derived hydration here and the role-map disappears.
|
||||
//
|
||||
// v2 features consume this store via `useCan(action, scope?)`. v1 does
|
||||
// not import from here — its existing inline role checks keep working.
|
||||
// Hydrated from the backend's `/permissions/me` (the source of truth) via
|
||||
// `installPermissionsHydration()` in AppLayout, and refreshed live on the
|
||||
// `permissions:changed` socket event. v2 features consume this store via
|
||||
// `useCan(action, scope?)`. v1 does not import from here — its existing inline
|
||||
// scope checks keep working.
|
||||
import { defineStore } from "pinia";
|
||||
import type { Role } from "@/__generated__";
|
||||
import { type ActionKey, type Grant } from "@/v2/composables/useCan/actions";
|
||||
import { actionsForRole } from "@/v2/composables/useCan/role-map";
|
||||
import type {
|
||||
PermissionScopeSchema,
|
||||
PermissionsResponse,
|
||||
} from "@/__generated__";
|
||||
import {
|
||||
type ActionKey,
|
||||
type Grant,
|
||||
type PermissionScope,
|
||||
} from "@/v2/composables/useCan/actions";
|
||||
|
||||
interface State {
|
||||
grants: Grant[];
|
||||
hydratedFromRole: Role | null;
|
||||
isAdmin: boolean;
|
||||
hidden: { platforms: number[]; roms: number[] };
|
||||
}
|
||||
|
||||
function normalizeScope(scope: PermissionScopeSchema): PermissionScope {
|
||||
if (!scope.kind || scope.kind === "global") return { kind: "global" };
|
||||
return { kind: scope.kind, id: scope.id ?? 0 };
|
||||
}
|
||||
|
||||
export default defineStore("permissions", {
|
||||
state: (): State => ({
|
||||
grants: [],
|
||||
hydratedFromRole: null,
|
||||
isAdmin: false,
|
||||
hidden: { platforms: [], roms: [] },
|
||||
}),
|
||||
|
||||
actions: {
|
||||
/** Replace the stored grants with the role's blanket global grants.
|
||||
* Temporary; replaced by setGrants once /permissions/me lands. */
|
||||
hydrateFromRole(role: Role | null) {
|
||||
if (!role) {
|
||||
this.grants = [];
|
||||
this.hydratedFromRole = null;
|
||||
return;
|
||||
}
|
||||
const actions = actionsForRole(role);
|
||||
this.grants = actions.map((action) => ({
|
||||
action,
|
||||
scope: { kind: "global" },
|
||||
/** Replace the stored permissions with the `/permissions/me` response. */
|
||||
hydrateFromResponse(payload: PermissionsResponse) {
|
||||
this.grants = payload.grants.map((g) => ({
|
||||
action: g.action,
|
||||
scope: normalizeScope(g.scope),
|
||||
}));
|
||||
this.hydratedFromRole = role;
|
||||
this.isAdmin = payload.is_admin;
|
||||
this.hidden = {
|
||||
platforms: [...payload.hidden.platforms],
|
||||
roms: [...payload.hidden.roms],
|
||||
};
|
||||
},
|
||||
|
||||
/** Replace the stored grants with a normalised list from the backend. */
|
||||
/** Seed a clean non-admin state with the given grants (tests/stories).
|
||||
* Resets isAdmin/hidden too so a prior hydration can't leak through. */
|
||||
setGrants(grants: Grant[]) {
|
||||
this.grants = grants;
|
||||
this.hydratedFromRole = null;
|
||||
},
|
||||
|
||||
/** Add a single grant — useful for tests and per-resource updates. */
|
||||
addGrant(grant: Grant) {
|
||||
this.grants.push(grant);
|
||||
this.isAdmin = false;
|
||||
this.hidden = { platforms: [], roms: [] };
|
||||
},
|
||||
|
||||
reset() {
|
||||
this.grants = [];
|
||||
this.hydratedFromRole = null;
|
||||
this.isAdmin = false;
|
||||
this.hidden = { platforms: [], roms: [] };
|
||||
},
|
||||
},
|
||||
|
||||
|
||||
8
frontend/src/types/emitter.d.ts
vendored
8
frontend/src/types/emitter.d.ts
vendored
@@ -1,4 +1,8 @@
|
||||
import type { SaveSchema, StateSchema } from "@/__generated__";
|
||||
import type {
|
||||
PermissionGroupSchema,
|
||||
SaveSchema,
|
||||
StateSchema,
|
||||
} from "@/__generated__";
|
||||
import type { ClientTokenSchema } from "@/services/api/client-token";
|
||||
import type { Collection, SmartCollection } from "@/stores/collections";
|
||||
import type { Platform } from "@/stores/platforms";
|
||||
@@ -68,6 +72,8 @@ export type Events = {
|
||||
showCreateInviteLinkDialog: void;
|
||||
showEditUserDialog: User;
|
||||
showDeleteUserDialog: User;
|
||||
// v2 permission administration. `null` opens the group form in create mode.
|
||||
showGroupFormDialog: PermissionGroupSchema | null;
|
||||
showDeleteSavesDialog: {
|
||||
rom: DetailedRom;
|
||||
saves: SaveSchema[];
|
||||
|
||||
@@ -63,6 +63,9 @@ export function getRoleIcon(role: string) {
|
||||
switch (role) {
|
||||
case "admin":
|
||||
return "mdi-shield-crown-outline";
|
||||
case "user":
|
||||
return "mdi-account-outline";
|
||||
// Legacy roles, kept so any lingering value still renders an icon.
|
||||
case "editor":
|
||||
return "mdi-file-edit-outline";
|
||||
case "viewer":
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
// CreateUserDialog — v2-native rebuild of v1
|
||||
// `Settings/Administration/Users/Dialog/CreateUser.vue`. Single dialog
|
||||
// with username + password + email + role select; validates against
|
||||
// the existing `usersStore` rule arrays.
|
||||
import { RBtn, RIcon, RSelect, RTextField } from "@v2/lib";
|
||||
// CreateUserDialog — create a user with profile fields plus access: an Admin
|
||||
// toggle and, for non-admins, an initial permission group. Replaces the old
|
||||
// role select (roles are superseded by admin-vs-user + groups).
|
||||
import { RBtn, RIcon, RSelect, RSwitch, RTextField } from "@v2/lib";
|
||||
import type { Emitter } from "mitt";
|
||||
import { computed, inject, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import permissionsApi from "@/services/api/permissions";
|
||||
import userApi from "@/services/api/user";
|
||||
import storePermissionGroups from "@/stores/permissionGroups";
|
||||
import storeUsers from "@/stores/users";
|
||||
import type { Events } from "@/types/emitter";
|
||||
import { getRoleIcon } from "@/utils";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
import RDialog from "@/v2/lib/overlays/RDialog/RDialog.vue";
|
||||
|
||||
@@ -19,31 +19,31 @@ defineOptions({ inheritAttrs: false });
|
||||
const { t } = useI18n();
|
||||
const emitter = inject<Emitter<Events>>("emitter");
|
||||
const usersStore = storeUsers();
|
||||
const groupsStore = storePermissionGroups();
|
||||
const snackbar = useSnackbar();
|
||||
|
||||
const show = ref(false);
|
||||
const submitting = ref(false);
|
||||
|
||||
const user = ref({
|
||||
username: "",
|
||||
password: "",
|
||||
email: "",
|
||||
role: "viewer",
|
||||
});
|
||||
const user = ref({ username: "", password: "", email: "", role: "user" });
|
||||
const confirmPassword = ref("");
|
||||
const isAdmin = ref(false);
|
||||
const groupId = ref<number | null>(null);
|
||||
|
||||
emitter?.on("showCreateUserDialog", () => {
|
||||
const groupItems = computed(() =>
|
||||
groupsStore.groups.map((g) => ({ title: g.name, value: g.id })),
|
||||
);
|
||||
|
||||
const defaultGroupId = computed(() => groupsStore.defaultGroup?.id ?? null);
|
||||
|
||||
emitter?.on("showCreateUserDialog", async () => {
|
||||
reset();
|
||||
show.value = true;
|
||||
await groupsStore.ensureLoaded();
|
||||
// Pre-select the server default group so new users start where they land.
|
||||
groupId.value = defaultGroupId.value;
|
||||
});
|
||||
|
||||
const roleItems = computed(() =>
|
||||
["viewer", "editor", "admin"].map((role) => ({
|
||||
title: t(`settings.role-${role}`),
|
||||
value: role,
|
||||
})),
|
||||
);
|
||||
|
||||
const confirmPasswordRules = computed(() => [
|
||||
(v: string) => !!v || t("settings.repeat-password-required"),
|
||||
(v: string) =>
|
||||
@@ -59,15 +59,49 @@ const formValid = computed(
|
||||
);
|
||||
|
||||
function reset() {
|
||||
user.value = { username: "", password: "", email: "", role: "viewer" };
|
||||
user.value = { username: "", password: "", email: "", role: "user" };
|
||||
confirmPassword.value = "";
|
||||
isAdmin.value = false;
|
||||
groupId.value = null;
|
||||
}
|
||||
|
||||
async function createUser() {
|
||||
if (!formValid.value) return;
|
||||
submitting.value = true;
|
||||
try {
|
||||
user.value.role = isAdmin.value ? "admin" : "user";
|
||||
const { data } = await userApi.createUser(user.value);
|
||||
// The user now exists. Pinning a non-default group is a follow-up call, so
|
||||
// its failure must not discard the already-created user (orphan); surface
|
||||
// it as a non-fatal warning instead. Leaving the default selected lets the
|
||||
// user follow the server default.
|
||||
if (
|
||||
!isAdmin.value &&
|
||||
groupId.value !== null &&
|
||||
groupId.value !== defaultGroupId.value
|
||||
) {
|
||||
try {
|
||||
await permissionsApi.updateUserPermissions(data.id, {
|
||||
set_group: true,
|
||||
permission_group_id: groupId.value,
|
||||
});
|
||||
data.permission_group_id = groupId.value;
|
||||
} catch (groupErr) {
|
||||
const ge = groupErr as {
|
||||
response?: { data?: { detail?: string }; statusText?: string };
|
||||
message?: string;
|
||||
};
|
||||
snackbar.warning(
|
||||
t("settings.group-save-failed", {
|
||||
detail:
|
||||
ge?.response?.data?.detail ||
|
||||
ge?.response?.statusText ||
|
||||
ge?.message,
|
||||
}),
|
||||
{ icon: "mdi-alert" },
|
||||
);
|
||||
}
|
||||
}
|
||||
usersStore.add(data);
|
||||
snackbar.success(t("settings.user-created", { username: data.username }), {
|
||||
icon: "mdi-check-bold",
|
||||
@@ -156,27 +190,26 @@ function close() {
|
||||
{{ t("settings.email") }}
|
||||
</template>
|
||||
</RTextField>
|
||||
<RSelect
|
||||
v-model="user.role"
|
||||
variant="outlined"
|
||||
:items="roleItems"
|
||||
:label="t('settings.role')"
|
||||
required
|
||||
hide-details
|
||||
>
|
||||
<template #selection="{ item }">
|
||||
<div class="r-v2-user-dialog__role-line">
|
||||
<RIcon :icon="getRoleIcon(item.value)" size="16" />
|
||||
{{ item.title }}
|
||||
</div>
|
||||
</template>
|
||||
<template #item="{ props: itemProps, item }">
|
||||
<li v-bind="itemProps">
|
||||
<RIcon :icon="getRoleIcon(item.value)" size="16" />
|
||||
<span class="r-select__item-title">{{ item.title }}</span>
|
||||
</li>
|
||||
</template>
|
||||
</RSelect>
|
||||
|
||||
<div class="r-v2-user-dialog__admin">
|
||||
<RSwitch v-model="isAdmin" :label="t('settings.administrator')" />
|
||||
<span class="r-v2-user-dialog__hint">
|
||||
{{ t("settings.administrator-hint") }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="!isAdmin" class="r-v2-user-dialog__field">
|
||||
<span class="r-v2-user-dialog__field-label">
|
||||
{{ t("settings.permission-group") }}
|
||||
</span>
|
||||
<RSelect
|
||||
v-model="groupId"
|
||||
variant="outlined"
|
||||
:items="groupItems"
|
||||
item-title="title"
|
||||
item-value="value"
|
||||
hide-details
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<template #footer>
|
||||
<RBtn variant="text" @click="close">
|
||||
@@ -200,10 +233,24 @@ function close() {
|
||||
.r-v2-user-dialog__title {
|
||||
font-weight: var(--r-font-weight-semibold);
|
||||
}
|
||||
.r-v2-user-dialog__role-line {
|
||||
display: inline-flex;
|
||||
.r-v2-user-dialog__admin {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.r-v2-user-dialog__field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
text-transform: capitalize;
|
||||
}
|
||||
.r-v2-user-dialog__field-label {
|
||||
font-size: 12px;
|
||||
font-weight: var(--r-font-weight-semibold);
|
||||
color: var(--r-color-fg-secondary);
|
||||
}
|
||||
.r-v2-user-dialog__hint {
|
||||
font-size: 12px;
|
||||
color: var(--r-color-fg-muted);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,27 +1,36 @@
|
||||
<script setup lang="ts">
|
||||
// EditUserDialog — v2-native rebuild of v1
|
||||
// `Settings/Administration/Users/Dialog/EditUser.vue`. Form + avatar
|
||||
// upload. Listens for `showEditUserDialog` so the v2 UsersSection can
|
||||
// open it via the existing emitter contract.
|
||||
import { RBtn, RIcon, RSelect, RTextField } from "@v2/lib";
|
||||
// EditUserDialog — edit a user's profile AND access in one place. Profile
|
||||
// fields (username/password/email/avatar) plus an Access section that replaces
|
||||
// the old role picker: an Admin toggle, and for non-admins the permission
|
||||
// group and the platforms hidden from them. Emitter-driven
|
||||
// (`showEditUserDialog`).
|
||||
import { RBtn, RIcon, RSelect, RSwitch, RTextField } from "@v2/lib";
|
||||
import type { Emitter } from "mitt";
|
||||
import { computed, inject, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { OverrideSchemaIO, PermAction, PermEntity } from "@/__generated__";
|
||||
import permissionsApi from "@/services/api/permissions";
|
||||
import platformApi from "@/services/api/platform";
|
||||
import userApi from "@/services/api/user";
|
||||
import storeAuth from "@/stores/auth";
|
||||
import storePermissionGroups from "@/stores/permissionGroups";
|
||||
import type { Platform } from "@/stores/platforms";
|
||||
import storeUsers from "@/stores/users";
|
||||
import type { Events } from "@/types/emitter";
|
||||
import type { UserItem } from "@/types/user";
|
||||
import { getRoleIcon } from "@/utils";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
import RDialog from "@/v2/lib/overlays/RDialog/RDialog.vue";
|
||||
import { userAvatarUrl } from "@/v2/utils/userAvatar";
|
||||
import HiddenGamesPicker from "./HiddenGamesPicker.vue";
|
||||
import HiddenPlatformsPicker from "./HiddenPlatformsPicker.vue";
|
||||
import OverridesMatrix from "./OverridesMatrix.vue";
|
||||
|
||||
defineOptions({ inheritAttrs: false });
|
||||
|
||||
const { t } = useI18n();
|
||||
const auth = storeAuth();
|
||||
const usersStore = storeUsers();
|
||||
const groupsStore = storePermissionGroups();
|
||||
const emitter = inject<Emitter<Events>>("emitter");
|
||||
const snackbar = useSnackbar();
|
||||
|
||||
@@ -32,11 +41,95 @@ const confirmPassword = ref("");
|
||||
const imagePreviewUrl = ref<string | undefined>(undefined);
|
||||
const fileInputRef = ref<HTMLInputElement | null>(null);
|
||||
|
||||
emitter?.on("showEditUserDialog", (toEdit) => {
|
||||
// Access section.
|
||||
const isAdmin = ref(false);
|
||||
const platforms = ref<Platform[]>([]);
|
||||
const groupId = ref<number | null>(null);
|
||||
const originalGroupId = ref<number | null>(null);
|
||||
const hiddenPlatformIds = ref<number[]>([]);
|
||||
const originalHiddenPlatformIds = ref<number[]>([]);
|
||||
|
||||
// Advanced: per-user overrides + per-game hiding.
|
||||
const showAdvanced = ref(false);
|
||||
const entities = ref<PermEntity[]>([]);
|
||||
const actions = ref<PermAction[]>([]);
|
||||
const overrides = ref<OverrideSchemaIO[]>([]);
|
||||
const originalOverrides = ref<OverrideSchemaIO[]>([]);
|
||||
const hiddenRomIds = ref<number[]>([]);
|
||||
const originalHiddenRomIds = ref<number[]>([]);
|
||||
|
||||
function overridesKey(list: OverrideSchemaIO[]): string {
|
||||
return JSON.stringify(
|
||||
[...list].sort((a, b) =>
|
||||
`${a.entity}.${a.action}`.localeCompare(`${b.entity}.${b.action}`),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function ensureCatalog() {
|
||||
if (entities.value.length) return;
|
||||
try {
|
||||
const { data } = await permissionsApi.fetchCatalog();
|
||||
entities.value = data.entities;
|
||||
actions.value = data.actions;
|
||||
} catch (err) {
|
||||
console.error("Failed to load permission catalog", err);
|
||||
}
|
||||
}
|
||||
|
||||
const editingSelf = computed(() => user.value?.id === auth.user?.id);
|
||||
|
||||
const groupItems = computed(() =>
|
||||
groupsStore.groups.map((g) => ({ title: g.name, value: g.id })),
|
||||
);
|
||||
|
||||
const sortedPlatforms = computed(() =>
|
||||
[...platforms.value].sort((a, b) =>
|
||||
a.display_name.localeCompare(b.display_name),
|
||||
),
|
||||
);
|
||||
|
||||
emitter?.on("showEditUserDialog", async (toEdit) => {
|
||||
user.value = { ...toEdit, password: "", avatar: undefined };
|
||||
confirmPassword.value = "";
|
||||
imagePreviewUrl.value = undefined;
|
||||
isAdmin.value = toEdit.role === "admin";
|
||||
showAdvanced.value = false;
|
||||
show.value = true;
|
||||
|
||||
try {
|
||||
const [perms, , platformsResp] = await Promise.all([
|
||||
permissionsApi.fetchUserPermissions(toEdit.id),
|
||||
groupsStore.ensureLoaded(),
|
||||
platforms.value.length
|
||||
? Promise.resolve(null)
|
||||
: platformApi.getPlatforms(),
|
||||
ensureCatalog(),
|
||||
]);
|
||||
if (platformsResp) platforms.value = platformsResp.data;
|
||||
// A null group means the user follows the server default group; show it
|
||||
// as selected so the picker never displays a meaningless empty option.
|
||||
const defaultGroupId = groupsStore.defaultGroup?.id ?? null;
|
||||
groupId.value = perms.data.permission_group_id ?? defaultGroupId;
|
||||
originalGroupId.value = groupId.value;
|
||||
|
||||
const hiddenPlatforms = perms.data.hidden
|
||||
.filter((h) => h.entity === "platforms")
|
||||
.map((h) => h.entity_id);
|
||||
hiddenPlatformIds.value = [...hiddenPlatforms];
|
||||
originalHiddenPlatformIds.value = [...hiddenPlatforms];
|
||||
|
||||
const hiddenRoms = perms.data.hidden
|
||||
.filter((h) => h.entity === "roms")
|
||||
.map((h) => h.entity_id);
|
||||
hiddenRomIds.value = [...hiddenRoms];
|
||||
originalHiddenRomIds.value = [...hiddenRoms];
|
||||
|
||||
overrides.value = perms.data.overrides.map((o) => ({ ...o }));
|
||||
originalOverrides.value = perms.data.overrides.map((o) => ({ ...o }));
|
||||
} catch (err) {
|
||||
console.error("Failed to load user permissions", err);
|
||||
}
|
||||
});
|
||||
|
||||
const avatarSrc = computed(() => {
|
||||
@@ -44,16 +137,6 @@ const avatarSrc = computed(() => {
|
||||
return userAvatarUrl(user.value?.avatar_path, user.value?.updated_at);
|
||||
});
|
||||
|
||||
const roleItems = computed(() =>
|
||||
["viewer", "editor", "admin"].map((role) => ({
|
||||
title: t(`settings.role-${role}`),
|
||||
value: role,
|
||||
})),
|
||||
);
|
||||
|
||||
// On edit, password is optional — empty fields leave the existing
|
||||
// password untouched. As soon as the admin types a new password we
|
||||
// demand the repeat field is filled in and matches.
|
||||
const confirmPasswordRules = computed(() => [
|
||||
(v: string) =>
|
||||
!user.value?.password || !!v || t("settings.repeat-password-required"),
|
||||
@@ -63,7 +146,7 @@ const confirmPasswordRules = computed(() => [
|
||||
|
||||
const passwordChangeValid = computed(() => {
|
||||
const pw = user.value?.password ?? "";
|
||||
if (!pw) return true; // not changing the password
|
||||
if (!pw) return true;
|
||||
return pw.length >= 6 && pw === confirmPassword.value;
|
||||
});
|
||||
|
||||
@@ -83,15 +166,79 @@ function previewImage(event: Event) {
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
|
||||
async function editUser() {
|
||||
function diffHidden(
|
||||
entity: PermEntity,
|
||||
current: number[],
|
||||
original: number[],
|
||||
userId: number,
|
||||
): Promise<unknown>[] {
|
||||
const added = current.filter((id) => !original.includes(id));
|
||||
const removed = original.filter((id) => !current.includes(id));
|
||||
return [
|
||||
...added.map((id) =>
|
||||
permissionsApi.addHiddenEntity({
|
||||
entity,
|
||||
entity_id: id,
|
||||
user_id: userId,
|
||||
}),
|
||||
),
|
||||
...removed.map((id) =>
|
||||
permissionsApi.removeHiddenEntity({
|
||||
entity,
|
||||
entity_id: id,
|
||||
user_id: userId,
|
||||
}),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!user.value) return;
|
||||
submitting.value = true;
|
||||
const userId = user.value.id;
|
||||
try {
|
||||
// Role is derived from the Admin toggle (admin vs plain user). Self-role
|
||||
// changes are ignored by the backend, so leave it untouched when editing
|
||||
// yourself.
|
||||
if (!editingSelf.value) {
|
||||
user.value.role = isAdmin.value ? "admin" : "user";
|
||||
}
|
||||
const { data } = await userApi.updateUser(user.value);
|
||||
|
||||
// Group, overrides and hidden entities apply to non-admins (admins bypass).
|
||||
let nextGroupId = data.permission_group_id;
|
||||
if (!isAdmin.value) {
|
||||
const groupChanged = groupId.value !== originalGroupId.value;
|
||||
const overridesChanged =
|
||||
overridesKey(overrides.value) !== overridesKey(originalOverrides.value);
|
||||
if (groupChanged || overridesChanged) {
|
||||
await permissionsApi.updateUserPermissions(userId, {
|
||||
set_group: groupChanged,
|
||||
permission_group_id: groupId.value,
|
||||
overrides: overridesChanged ? overrides.value : undefined,
|
||||
});
|
||||
if (groupChanged) nextGroupId = groupId.value;
|
||||
}
|
||||
await Promise.all([
|
||||
...diffHidden(
|
||||
"platforms",
|
||||
hiddenPlatformIds.value,
|
||||
originalHiddenPlatformIds.value,
|
||||
userId,
|
||||
),
|
||||
...diffHidden(
|
||||
"roms",
|
||||
hiddenRomIds.value,
|
||||
originalHiddenRomIds.value,
|
||||
userId,
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
snackbar.success(t("settings.user-updated", { username: data.username }), {
|
||||
icon: "mdi-check-bold",
|
||||
});
|
||||
usersStore.update(data);
|
||||
usersStore.update({ ...data, permission_group_id: nextGroupId });
|
||||
if (data.id === auth.user?.id) auth.setCurrentUser(data);
|
||||
emitter?.emit("refreshDrawer", null);
|
||||
show.value = false;
|
||||
@@ -124,6 +271,7 @@ function close() {
|
||||
v-model="show"
|
||||
icon="mdi-account-edit"
|
||||
:width="640"
|
||||
scroll-content
|
||||
@close="close"
|
||||
>
|
||||
<template #header>
|
||||
@@ -185,28 +333,9 @@ function close() {
|
||||
{{ t("settings.email") }}
|
||||
</template>
|
||||
</RTextField>
|
||||
<RSelect
|
||||
v-model="user.role"
|
||||
variant="outlined"
|
||||
:items="roleItems"
|
||||
:label="t('settings.role')"
|
||||
required
|
||||
hide-details
|
||||
>
|
||||
<template #selection="{ item }">
|
||||
<div class="r-v2-user-dialog__role-line">
|
||||
<RIcon :icon="getRoleIcon(item.value)" size="16" />
|
||||
{{ item.title }}
|
||||
</div>
|
||||
</template>
|
||||
<template #item="{ props: itemProps, item }">
|
||||
<li v-bind="itemProps">
|
||||
<RIcon :icon="getRoleIcon(item.value)" size="16" />
|
||||
<span class="r-select__item-title">{{ item.title }}</span>
|
||||
</li>
|
||||
</template>
|
||||
</RSelect>
|
||||
</div>
|
||||
<!-- Avatar is an image-upload control, not a text/icon button: it keeps
|
||||
a native <button> (matches v2's raw-<img> avatar convention). -->
|
||||
<button
|
||||
type="button"
|
||||
class="r-v2-user-dialog__avatar"
|
||||
@@ -227,6 +356,88 @@ function close() {
|
||||
@change="previewImage"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="r-v2-user-dialog__access">
|
||||
<span class="r-v2-user-dialog__access-label">
|
||||
<RIcon icon="mdi-shield-account-outline" size="14" />
|
||||
{{ t("settings.access") }}
|
||||
</span>
|
||||
|
||||
<div class="r-v2-user-dialog__admin">
|
||||
<RSwitch
|
||||
v-model="isAdmin"
|
||||
:disabled="editingSelf"
|
||||
:label="t('settings.administrator')"
|
||||
/>
|
||||
<span class="r-v2-user-dialog__hint">
|
||||
{{
|
||||
editingSelf
|
||||
? t("settings.cannot-change-own-role")
|
||||
: t("settings.administrator-hint")
|
||||
}}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<template v-if="!isAdmin">
|
||||
<div class="r-v2-user-dialog__field">
|
||||
<span class="r-v2-user-dialog__field-label">
|
||||
{{ t("settings.permission-group") }}
|
||||
</span>
|
||||
<RSelect
|
||||
v-model="groupId"
|
||||
variant="outlined"
|
||||
:items="groupItems"
|
||||
item-title="title"
|
||||
item-value="value"
|
||||
hide-details
|
||||
/>
|
||||
</div>
|
||||
<div class="r-v2-user-dialog__field">
|
||||
<span class="r-v2-user-dialog__field-label">
|
||||
{{ t("settings.hidden-platforms") }}
|
||||
</span>
|
||||
<HiddenPlatformsPicker
|
||||
v-model="hiddenPlatformIds"
|
||||
:platforms="sortedPlatforms"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<RBtn
|
||||
variant="text"
|
||||
size="small"
|
||||
:prepend-icon="
|
||||
showAdvanced ? 'mdi-chevron-down' : 'mdi-chevron-right'
|
||||
"
|
||||
:aria-expanded="showAdvanced"
|
||||
class="r-v2-user-dialog__advanced-toggle"
|
||||
@click="showAdvanced = !showAdvanced"
|
||||
>
|
||||
{{ t("settings.advanced-permissions") }}
|
||||
</RBtn>
|
||||
|
||||
<template v-if="showAdvanced">
|
||||
<div class="r-v2-user-dialog__field">
|
||||
<span class="r-v2-user-dialog__field-label">
|
||||
{{ t("settings.permission-overrides") }}
|
||||
</span>
|
||||
<span class="r-v2-user-dialog__hint">
|
||||
{{ t("settings.permission-overrides-hint") }}
|
||||
</span>
|
||||
<OverridesMatrix
|
||||
v-model="overrides"
|
||||
:entities="entities"
|
||||
:actions="actions"
|
||||
/>
|
||||
</div>
|
||||
<div class="r-v2-user-dialog__field">
|
||||
<span class="r-v2-user-dialog__field-label">
|
||||
{{ t("settings.hidden-games") }}
|
||||
</span>
|
||||
<HiddenGamesPicker v-model="hiddenRomIds" />
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
<template #footer>
|
||||
<RBtn variant="text" @click="close">
|
||||
@@ -238,7 +449,7 @@ function close() {
|
||||
color="primary"
|
||||
:loading="submitting"
|
||||
:disabled="!user.username || !passwordChangeValid"
|
||||
@click="editUser"
|
||||
@click="save"
|
||||
>
|
||||
{{ t("common.apply") }}
|
||||
</RBtn>
|
||||
@@ -307,10 +518,46 @@ html[data-bp~="xs"] .r-v2-user-dialog__edit-grid {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
.r-v2-user-dialog__role-line {
|
||||
|
||||
.r-v2-user-dialog__access {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
margin-top: 20px;
|
||||
padding-top: 20px;
|
||||
border-top: 1px solid var(--r-color-border);
|
||||
}
|
||||
.r-v2-user-dialog__access-label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
text-transform: capitalize;
|
||||
font-size: 11px;
|
||||
font-weight: var(--r-font-weight-bold);
|
||||
letter-spacing: 0.1em;
|
||||
text-transform: uppercase;
|
||||
color: var(--r-color-fg-secondary);
|
||||
}
|
||||
.r-v2-user-dialog__admin {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.r-v2-user-dialog__field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.r-v2-user-dialog__field-label {
|
||||
font-size: 12px;
|
||||
font-weight: var(--r-font-weight-semibold);
|
||||
color: var(--r-color-fg-secondary);
|
||||
}
|
||||
.r-v2-user-dialog__hint {
|
||||
font-size: 12px;
|
||||
color: var(--r-color-fg-muted);
|
||||
}
|
||||
.r-v2-user-dialog__advanced-toggle {
|
||||
align-self: flex-start;
|
||||
}
|
||||
</style>
|
||||
|
||||
388
frontend/src/v2/components/Settings/GroupFormDialog.vue
Normal file
388
frontend/src/v2/components/Settings/GroupFormDialog.vue
Normal file
@@ -0,0 +1,388 @@
|
||||
<script setup lang="ts">
|
||||
// GroupFormDialog — create/edit a permission group. Emitter-driven
|
||||
// (`showGroupFormDialog` with the group to edit, or null to create), mounted
|
||||
// alongside the groups table in Administration. On save it refetches the
|
||||
// shared permissionGroups store so every consumer (table, user dialogs)
|
||||
// reflects the change immediately.
|
||||
import { RBtn, RIcon, RSwitch, RTextField } from "@v2/lib";
|
||||
import type { Emitter } from "mitt";
|
||||
import { computed, inject, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { GrantSchemaIO, PermAction, PermEntity } from "@/__generated__";
|
||||
import permissionsApi from "@/services/api/permissions";
|
||||
import platformApi from "@/services/api/platform";
|
||||
import storePermissionGroups from "@/stores/permissionGroups";
|
||||
import type { Platform } from "@/stores/platforms";
|
||||
import type { Events } from "@/types/emitter";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
import RDialog from "@/v2/lib/overlays/RDialog/RDialog.vue";
|
||||
import { GROUP_COLOR_PALETTE } from "@/v2/utils/groupColor";
|
||||
import HiddenGamesPicker from "./HiddenGamesPicker.vue";
|
||||
import HiddenPlatformsPicker from "./HiddenPlatformsPicker.vue";
|
||||
import PermissionsMatrix from "./PermissionsMatrix.vue";
|
||||
|
||||
defineOptions({ inheritAttrs: false });
|
||||
|
||||
const { t } = useI18n();
|
||||
const emitter = inject<Emitter<Events>>("emitter");
|
||||
const snackbar = useSnackbar();
|
||||
const groupsStore = storePermissionGroups();
|
||||
|
||||
const show = ref(false);
|
||||
const submitting = ref(false);
|
||||
const editingId = ref<number | null>(null);
|
||||
const isSystem = ref(false);
|
||||
|
||||
const name = ref("");
|
||||
const description = ref("");
|
||||
const isDefault = ref(false);
|
||||
const color = ref<string>(GROUP_COLOR_PALETTE[0]);
|
||||
const palette = GROUP_COLOR_PALETTE;
|
||||
const grants = ref<GrantSchemaIO[]>([]);
|
||||
|
||||
// Group-level hidden entities (members inherit these; per-user overrides on
|
||||
// top still apply). Diffed against the originals on save.
|
||||
const platforms = ref<Platform[]>([]);
|
||||
const hiddenPlatformIds = ref<number[]>([]);
|
||||
const originalHiddenPlatformIds = ref<number[]>([]);
|
||||
const hiddenRomIds = ref<number[]>([]);
|
||||
const originalHiddenRomIds = ref<number[]>([]);
|
||||
|
||||
const sortedPlatforms = computed(() =>
|
||||
[...platforms.value].sort((a, b) =>
|
||||
a.display_name.localeCompare(b.display_name),
|
||||
),
|
||||
);
|
||||
|
||||
const entities = ref<PermEntity[]>([]);
|
||||
const actions = ref<PermAction[]>([]);
|
||||
|
||||
async function ensureCatalog() {
|
||||
if (entities.value.length) return;
|
||||
try {
|
||||
const { data } = await permissionsApi.fetchCatalog();
|
||||
entities.value = data.entities;
|
||||
actions.value = data.actions;
|
||||
} catch (err) {
|
||||
console.error("Failed to load permission catalog", err);
|
||||
}
|
||||
}
|
||||
|
||||
async function ensurePlatforms() {
|
||||
if (platforms.value.length) return;
|
||||
try {
|
||||
const { data } = await platformApi.getPlatforms();
|
||||
platforms.value = data;
|
||||
} catch (err) {
|
||||
console.error("Failed to load platforms", err);
|
||||
}
|
||||
}
|
||||
|
||||
function diffHidden(
|
||||
entity: PermEntity,
|
||||
current: number[],
|
||||
original: number[],
|
||||
groupId: number,
|
||||
): Promise<unknown>[] {
|
||||
const added = current.filter((id) => !original.includes(id));
|
||||
const removed = original.filter((id) => !current.includes(id));
|
||||
return [
|
||||
...added.map((id) =>
|
||||
permissionsApi.addHiddenEntity({
|
||||
entity,
|
||||
entity_id: id,
|
||||
group_id: groupId,
|
||||
}),
|
||||
),
|
||||
...removed.map((id) =>
|
||||
permissionsApi.removeHiddenEntity({
|
||||
entity,
|
||||
entity_id: id,
|
||||
group_id: groupId,
|
||||
}),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
emitter?.on("showGroupFormDialog", async (group) => {
|
||||
editingId.value = group?.id ?? null;
|
||||
isSystem.value = group?.is_system ?? false;
|
||||
name.value = group?.name ?? "";
|
||||
description.value = group?.description ?? "";
|
||||
isDefault.value = group?.is_default ?? false;
|
||||
color.value = group?.color ?? GROUP_COLOR_PALETTE[0];
|
||||
grants.value = group ? group.grants.map((g) => ({ ...g })) : [];
|
||||
|
||||
const hidden = group?.hidden ?? [];
|
||||
const hiddenPlatforms = hidden
|
||||
.filter((h) => h.entity === "platforms")
|
||||
.map((h) => h.entity_id);
|
||||
const hiddenRoms = hidden
|
||||
.filter((h) => h.entity === "roms")
|
||||
.map((h) => h.entity_id);
|
||||
hiddenPlatformIds.value = [...hiddenPlatforms];
|
||||
originalHiddenPlatformIds.value = [...hiddenPlatforms];
|
||||
hiddenRomIds.value = [...hiddenRoms];
|
||||
originalHiddenRomIds.value = [...hiddenRoms];
|
||||
|
||||
await Promise.all([ensureCatalog(), ensurePlatforms()]);
|
||||
show.value = true;
|
||||
});
|
||||
|
||||
async function save() {
|
||||
if (!name.value.trim()) return;
|
||||
submitting.value = true;
|
||||
const body = {
|
||||
name: name.value.trim(),
|
||||
description: description.value,
|
||||
is_default: isDefault.value,
|
||||
color: color.value,
|
||||
grants: grants.value,
|
||||
};
|
||||
try {
|
||||
const { data: saved } =
|
||||
editingId.value !== null
|
||||
? await permissionsApi.updateGroup(editingId.value, body)
|
||||
: await permissionsApi.createGroup(body);
|
||||
// Apply hidden-entity diffs against the (now-known) group id.
|
||||
await Promise.all([
|
||||
...diffHidden(
|
||||
"platforms",
|
||||
hiddenPlatformIds.value,
|
||||
originalHiddenPlatformIds.value,
|
||||
saved.id,
|
||||
),
|
||||
...diffHidden(
|
||||
"roms",
|
||||
hiddenRomIds.value,
|
||||
originalHiddenRomIds.value,
|
||||
saved.id,
|
||||
),
|
||||
]);
|
||||
snackbar.success(t("settings.group-saved", { name: body.name }), {
|
||||
icon: "mdi-check-bold",
|
||||
});
|
||||
// Refetch (not upsert): toggling `is_default` reassigns it server-side,
|
||||
// so the previous default's flag must be refreshed too.
|
||||
await groupsStore.fetch();
|
||||
show.value = false;
|
||||
} catch (err) {
|
||||
const e = err as {
|
||||
response?: { data?: { detail?: string }; statusText?: string };
|
||||
message?: string;
|
||||
};
|
||||
snackbar.error(
|
||||
t("settings.group-save-failed", {
|
||||
detail:
|
||||
e?.response?.data?.detail || e?.response?.statusText || e?.message,
|
||||
}),
|
||||
{ icon: "mdi-close-circle" },
|
||||
);
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<RDialog
|
||||
v-model="show"
|
||||
icon="mdi-shield-lock-outline"
|
||||
:width="720"
|
||||
scroll-content
|
||||
>
|
||||
<template #header>
|
||||
<span class="r-v2-group-dialog__title">
|
||||
{{
|
||||
editingId !== null
|
||||
? t("settings.edit-group")
|
||||
: t("settings.new-group")
|
||||
}}
|
||||
</span>
|
||||
</template>
|
||||
<template #content>
|
||||
<div class="r-v2-group-dialog__form">
|
||||
<p v-if="isSystem" class="r-v2-group-dialog__sys-warn">
|
||||
<RIcon icon="mdi-alert-outline" size="14" />
|
||||
{{ t("settings.group-system-warning") }}
|
||||
</p>
|
||||
|
||||
<RTextField v-model="name" prefix-label="stacked" required clearable>
|
||||
<template #prefix-label>
|
||||
<RIcon icon="mdi-label-outline" size="14" />
|
||||
{{ t("common.name") }}
|
||||
</template>
|
||||
</RTextField>
|
||||
|
||||
<RTextField
|
||||
v-model="description"
|
||||
prefix-label="stacked"
|
||||
multiline
|
||||
:rows="2"
|
||||
>
|
||||
<template #prefix-label>
|
||||
<RIcon icon="mdi-text" size="14" />
|
||||
{{ t("settings.description") }}
|
||||
</template>
|
||||
</RTextField>
|
||||
|
||||
<div class="r-v2-group-dialog__default">
|
||||
<RSwitch
|
||||
v-model="isDefault"
|
||||
:label="t('settings.group-is-default')"
|
||||
/>
|
||||
<span class="r-v2-group-dialog__default-hint">
|
||||
{{ t("settings.group-is-default-hint") }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="r-v2-group-dialog__color">
|
||||
<span class="r-v2-group-dialog__color-label">
|
||||
{{ t("settings.group-color") }}
|
||||
</span>
|
||||
<div class="r-v2-group-dialog__swatches">
|
||||
<RBtn
|
||||
v-for="(swatch, i) in palette"
|
||||
:key="swatch"
|
||||
variant="text"
|
||||
class="r-v2-group-dialog__swatch"
|
||||
:class="{
|
||||
'r-v2-group-dialog__swatch--active': color === swatch,
|
||||
}"
|
||||
:style="{ '--swatch': swatch }"
|
||||
:aria-label="`${t('settings.group-color')} ${i + 1}`"
|
||||
:aria-pressed="color === swatch"
|
||||
@click="color = swatch"
|
||||
>
|
||||
<RIcon
|
||||
v-if="color === swatch"
|
||||
icon="mdi-check"
|
||||
size="14"
|
||||
class="r-v2-group-dialog__swatch-check"
|
||||
/>
|
||||
</RBtn>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="r-v2-group-dialog__matrix">
|
||||
<span class="r-v2-group-dialog__matrix-label">
|
||||
{{ t("settings.group-grants") }}
|
||||
</span>
|
||||
<PermissionsMatrix
|
||||
v-model="grants"
|
||||
:entities="entities"
|
||||
:actions="actions"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="r-v2-group-dialog__matrix">
|
||||
<span class="r-v2-group-dialog__matrix-label">
|
||||
{{ t("settings.hidden-platforms") }}
|
||||
</span>
|
||||
<HiddenPlatformsPicker
|
||||
v-model="hiddenPlatformIds"
|
||||
:platforms="sortedPlatforms"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="r-v2-group-dialog__matrix">
|
||||
<span class="r-v2-group-dialog__matrix-label">
|
||||
{{ t("settings.hidden-games") }}
|
||||
</span>
|
||||
<HiddenGamesPicker v-model="hiddenRomIds" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template #footer>
|
||||
<RBtn variant="text" @click="show = false">{{ t("common.cancel") }}</RBtn>
|
||||
<div style="flex: 1" />
|
||||
<RBtn
|
||||
variant="flat"
|
||||
color="primary"
|
||||
:loading="submitting"
|
||||
:disabled="!name.trim()"
|
||||
@click="save"
|
||||
>
|
||||
{{ t("common.apply") }}
|
||||
</RBtn>
|
||||
</template>
|
||||
</RDialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.r-v2-group-dialog__title {
|
||||
font-weight: var(--r-font-weight-semibold);
|
||||
}
|
||||
.r-v2-group-dialog__form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
min-width: 0;
|
||||
}
|
||||
.r-v2-group-dialog__sys-warn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: var(--r-color-warning, var(--r-color-fg-muted));
|
||||
}
|
||||
.r-v2-group-dialog__default {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.r-v2-group-dialog__default-hint {
|
||||
font-size: 12px;
|
||||
color: var(--r-color-fg-muted);
|
||||
}
|
||||
.r-v2-group-dialog__color {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.r-v2-group-dialog__color-label {
|
||||
font-size: 11px;
|
||||
font-weight: var(--r-font-weight-bold);
|
||||
letter-spacing: 0.1em;
|
||||
text-transform: uppercase;
|
||||
color: var(--r-color-fg-secondary);
|
||||
}
|
||||
.r-v2-group-dialog__swatches {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
.r-v2-group-dialog__swatch {
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
min-width: 26px;
|
||||
padding: 0;
|
||||
border-radius: 50%;
|
||||
border: 2px solid transparent;
|
||||
background: var(--swatch) !important;
|
||||
transition: transform var(--r-motion-fast) var(--r-motion-ease-out);
|
||||
}
|
||||
.r-v2-group-dialog__swatch:hover {
|
||||
transform: scale(1.12);
|
||||
}
|
||||
.r-v2-group-dialog__swatch--active {
|
||||
border-color: var(--r-color-fg);
|
||||
}
|
||||
.r-v2-group-dialog__swatch-check {
|
||||
color: var(--r-color-overlay-fg);
|
||||
}
|
||||
.r-v2-group-dialog__matrix {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.r-v2-group-dialog__matrix-label {
|
||||
font-size: 11px;
|
||||
font-weight: var(--r-font-weight-bold);
|
||||
letter-spacing: 0.1em;
|
||||
text-transform: uppercase;
|
||||
color: var(--r-color-fg-secondary);
|
||||
}
|
||||
</style>
|
||||
227
frontend/src/v2/components/Settings/HiddenGamesPicker.vue
Normal file
227
frontend/src/v2/components/Settings/HiddenGamesPicker.vue
Normal file
@@ -0,0 +1,227 @@
|
||||
<script setup lang="ts">
|
||||
// HiddenGamesPicker — search the library and pick individual games to hide
|
||||
// from a user. Model is the list of hidden rom ids. A debounced search shows
|
||||
// matching games (cover + name); picked games render below as a removable
|
||||
// list (cover + name), with their full rom cached so covers resolve even for
|
||||
// ids that were hidden before this session.
|
||||
import { RBtn, RIcon, RSpinner, RTextField } from "@v2/lib";
|
||||
import { debounce } from "lodash";
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import romApi from "@/services/api/rom";
|
||||
import type { SimpleRom } from "@/stores/roms";
|
||||
import GameCover from "@/v2/components/shared/GameCover.vue";
|
||||
|
||||
defineOptions({ inheritAttrs: false });
|
||||
|
||||
const props = defineProps<{ modelValue: number[] }>();
|
||||
const emit = defineEmits<{ "update:modelValue": [number[]] }>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const query = ref("");
|
||||
const results = ref<SimpleRom[]>([]);
|
||||
const loading = ref(false);
|
||||
// Full rom objects keyed by id so both the results and the selected list can
|
||||
// render covers (selected ids hidden in a past session are fetched on demand).
|
||||
const romCache = ref<Record<number, SimpleRom>>({});
|
||||
|
||||
function romName(rom: SimpleRom): string {
|
||||
return rom.name || rom.fs_name || `#${rom.id}`;
|
||||
}
|
||||
|
||||
function nameFor(id: number): string {
|
||||
const rom = romCache.value[id];
|
||||
return rom ? romName(rom) : `#${id}`;
|
||||
}
|
||||
|
||||
const runSearch = debounce(async (term: string) => {
|
||||
if (!term.trim()) {
|
||||
results.value = [];
|
||||
loading.value = false;
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
try {
|
||||
const { data } = await romApi.getRoms({ searchTerm: term, limit: 15 });
|
||||
results.value = data.items;
|
||||
for (const rom of data.items) romCache.value[rom.id] = rom;
|
||||
} catch (err) {
|
||||
console.error("Game search failed", err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}, 300);
|
||||
|
||||
watch(query, (q) => {
|
||||
loading.value = !!q.trim();
|
||||
runSearch(q);
|
||||
});
|
||||
|
||||
// Resolve full roms for already-hidden ids so their covers and names render.
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
async (ids) => {
|
||||
const missing = ids.filter((id) => !(id in romCache.value));
|
||||
await Promise.all(
|
||||
missing.map(async (id) => {
|
||||
try {
|
||||
const { data } = await romApi.getRomSimple({ romId: id });
|
||||
romCache.value[id] = data;
|
||||
} catch {
|
||||
/* leave uncached — the row falls back to a placeholder cover */
|
||||
}
|
||||
}),
|
||||
);
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const selected = computed(() =>
|
||||
props.modelValue.map((id) => ({
|
||||
id,
|
||||
rom: romCache.value[id] ?? null,
|
||||
name: nameFor(id),
|
||||
})),
|
||||
);
|
||||
const addable = computed(() =>
|
||||
results.value.filter((rom) => !props.modelValue.includes(rom.id)),
|
||||
);
|
||||
|
||||
function add(rom: SimpleRom) {
|
||||
if (!props.modelValue.includes(rom.id)) {
|
||||
romCache.value[rom.id] = rom;
|
||||
emit("update:modelValue", [...props.modelValue, rom.id]);
|
||||
}
|
||||
// Keep the results open so several games can be added in one go — the added
|
||||
// rom drops out of `addable`, the rest of the matches stay visible.
|
||||
}
|
||||
|
||||
function remove(id: number) {
|
||||
emit(
|
||||
"update:modelValue",
|
||||
props.modelValue.filter((x) => x !== id),
|
||||
);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="r-v2-hgames">
|
||||
<RTextField
|
||||
v-model="query"
|
||||
prefix-label="inline"
|
||||
density="compact"
|
||||
hide-details
|
||||
:placeholder="t('settings.hidden-games-search')"
|
||||
>
|
||||
<template #prefix-label>
|
||||
<RIcon icon="mdi-magnify" size="15" />
|
||||
</template>
|
||||
</RTextField>
|
||||
|
||||
<div v-if="loading" class="r-v2-hgames__status">
|
||||
<RSpinner :size="16" />
|
||||
</div>
|
||||
<ul v-else-if="addable.length" class="r-v2-hgames__results">
|
||||
<li v-for="rom in addable" :key="rom.id">
|
||||
<button
|
||||
type="button"
|
||||
class="r-v2-hgames__row r-v2-hgames__row--add"
|
||||
@click="add(rom)"
|
||||
>
|
||||
<span class="r-v2-hgames__thumb">
|
||||
<GameCover :rom="rom" :title="romName(rom)" />
|
||||
</span>
|
||||
<span class="r-v2-hgames__name">{{ romName(rom) }}</span>
|
||||
<RIcon icon="mdi-plus" size="18" class="r-v2-hgames__add-icon" />
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<ul v-if="selected.length" class="r-v2-hgames__selected">
|
||||
<li v-for="s in selected" :key="s.id" class="r-v2-hgames__row">
|
||||
<span class="r-v2-hgames__thumb">
|
||||
<GameCover :rom="s.rom" :title="s.name" />
|
||||
</span>
|
||||
<span class="r-v2-hgames__name">{{ s.name }}</span>
|
||||
<RBtn
|
||||
variant="text"
|
||||
icon="mdi-close"
|
||||
size="small"
|
||||
class="r-v2-hgames__remove"
|
||||
:aria-label="t('common.remove')"
|
||||
@click="remove(s.id)"
|
||||
/>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.r-v2-hgames {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
.r-v2-hgames__status {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 8px;
|
||||
}
|
||||
.r-v2-hgames__results {
|
||||
border: 1px solid var(--r-color-border);
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
max-height: 240px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.r-v2-hgames__selected {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
.r-v2-hgames__row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 6px 8px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.r-v2-hgames__selected .r-v2-hgames__row {
|
||||
background: var(--r-color-surface);
|
||||
}
|
||||
.r-v2-hgames__row--add {
|
||||
cursor: pointer;
|
||||
/* Native <button> reset so it reads as a plain row. */
|
||||
width: 100%;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
}
|
||||
.r-v2-hgames__row--add:hover {
|
||||
background: var(--r-color-surface);
|
||||
}
|
||||
.r-v2-hgames__results li:not(:last-child) {
|
||||
border-bottom: 1px solid var(--r-color-border);
|
||||
}
|
||||
.r-v2-hgames__thumb {
|
||||
flex: none;
|
||||
width: 30px;
|
||||
}
|
||||
.r-v2-hgames__name {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.r-v2-hgames__add-icon {
|
||||
flex: none;
|
||||
color: var(--r-color-fg-muted);
|
||||
}
|
||||
.r-v2-hgames__remove {
|
||||
flex: none;
|
||||
}
|
||||
</style>
|
||||
130
frontend/src/v2/components/Settings/HiddenPlatformsPicker.vue
Normal file
130
frontend/src/v2/components/Settings/HiddenPlatformsPicker.vue
Normal file
@@ -0,0 +1,130 @@
|
||||
<script setup lang="ts">
|
||||
// HiddenPlatformsPicker — pick platforms to hide from a user or group. Model
|
||||
// is the list of hidden platform ids. The dropdown is the shared
|
||||
// PlatformSelect (the same icon + name rows used by Scan), in multi-select
|
||||
// mode so several platforms can be toggled without the menu closing each
|
||||
// time; the activator shows a count and the picked platforms render below as
|
||||
// a removable list (icon + name), not pills.
|
||||
import { RBtn, RPlatformIcon } from "@v2/lib";
|
||||
import { computed } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { Platform } from "@/stores/platforms";
|
||||
import PlatformSelect from "@/v2/components/shared/PlatformSelect.vue";
|
||||
|
||||
defineOptions({ inheritAttrs: false });
|
||||
|
||||
const props = defineProps<{ modelValue: number[]; platforms: Platform[] }>();
|
||||
const emit = defineEmits<{ "update:modelValue": [number[]] }>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const byId = computed(() => {
|
||||
const m = new Map<number, Platform>();
|
||||
for (const p of props.platforms) m.set(p.id, p);
|
||||
return m;
|
||||
});
|
||||
|
||||
const selected = computed(() =>
|
||||
props.modelValue
|
||||
.map((id) => byId.value.get(id))
|
||||
.filter((p): p is Platform => p !== undefined),
|
||||
);
|
||||
|
||||
function onUpdate(value: number | string | number[] | string[] | null) {
|
||||
if (!Array.isArray(value)) return;
|
||||
emit(
|
||||
"update:modelValue",
|
||||
value.filter((v): v is number => typeof v === "number"),
|
||||
);
|
||||
}
|
||||
|
||||
function remove(id: number) {
|
||||
emit(
|
||||
"update:modelValue",
|
||||
props.modelValue.filter((x) => x !== id),
|
||||
);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="r-v2-hidplat">
|
||||
<PlatformSelect
|
||||
:model-value="modelValue"
|
||||
:items="platforms"
|
||||
item-key="id"
|
||||
multiple
|
||||
:chips="false"
|
||||
prepend-inner-icon="mdi-controller"
|
||||
searchable
|
||||
show-meta
|
||||
hide-details
|
||||
:placeholder="t('settings.hidden-platforms-placeholder')"
|
||||
@update:model-value="onUpdate"
|
||||
>
|
||||
<!-- One count summary for the whole selection; an empty node for the
|
||||
rest suppresses RSelect's per-item default (which would otherwise
|
||||
reprint every platform's icon + name next to the count). -->
|
||||
<template #selection="{ index }">
|
||||
<span v-if="index === 0" class="r-v2-hidplat__count">
|
||||
{{ t("common.platforms-n", modelValue.length) }}
|
||||
</span>
|
||||
<span v-else aria-hidden="true" />
|
||||
</template>
|
||||
</PlatformSelect>
|
||||
|
||||
<ul v-if="selected.length" class="r-v2-hidplat__list">
|
||||
<li v-for="p in selected" :key="p.id" class="r-v2-hidplat__row">
|
||||
<RPlatformIcon
|
||||
:slug="p.slug"
|
||||
:fs-slug="p.fs_slug"
|
||||
:name="p.display_name"
|
||||
:size="24"
|
||||
:show-tooltip="false"
|
||||
/>
|
||||
<span class="r-v2-hidplat__name">{{ p.display_name }}</span>
|
||||
<RBtn
|
||||
variant="text"
|
||||
icon="mdi-close"
|
||||
size="small"
|
||||
class="r-v2-hidplat__remove"
|
||||
:aria-label="t('common.remove')"
|
||||
@click="remove(p.id)"
|
||||
/>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.r-v2-hidplat {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
.r-v2-hidplat__count {
|
||||
color: var(--r-color-fg-secondary);
|
||||
}
|
||||
.r-v2-hidplat__list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
.r-v2-hidplat__row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 6px 8px;
|
||||
border-radius: 8px;
|
||||
background: var(--r-color-surface);
|
||||
}
|
||||
.r-v2-hidplat__name {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.r-v2-hidplat__remove {
|
||||
flex: none;
|
||||
}
|
||||
</style>
|
||||
@@ -24,7 +24,7 @@ const fullInviteLink = ref("");
|
||||
const selectedRole = ref<string | null>(null);
|
||||
const selectedExpiration = ref<number>(86400);
|
||||
|
||||
const roles = ["viewer", "editor", "admin"];
|
||||
const roles = ["admin", "user"];
|
||||
const expirationOptions = computed(() => [
|
||||
{ title: t("settings.expiry-1h"), value: 3600 },
|
||||
{ title: t("settings.expiry-6h"), value: 21600 },
|
||||
@@ -106,7 +106,7 @@ function close() {
|
||||
@click="selectedRole = role"
|
||||
>
|
||||
<RIcon :icon="getRoleIcon(role)" size="14" />
|
||||
{{ role.charAt(0).toUpperCase() + role.slice(1) }}
|
||||
{{ t(`settings.role-${role}`) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
200
frontend/src/v2/components/Settings/OverridesMatrix.vue
Normal file
200
frontend/src/v2/components/Settings/OverridesMatrix.vue
Normal file
@@ -0,0 +1,200 @@
|
||||
<script setup lang="ts">
|
||||
// OverridesMatrix — per-user permission overrides on top of the user's
|
||||
// group. Each (entity, action) cell is a multi-state checkbox cycling
|
||||
// inherit (defer to group) -> grant (force-allow, primary) -> grant-own
|
||||
// (force-allow own items, accent) -> revoke (force-deny, danger). The
|
||||
// model is the list of explicit overrides (absence of a cell = inherit).
|
||||
import { RCheckbox, type RCheckboxState, RTooltip } from "@v2/lib";
|
||||
import { computed } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { OverrideSchemaIO, PermAction, PermEntity } from "@/__generated__";
|
||||
|
||||
defineOptions({ inheritAttrs: false });
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: OverrideSchemaIO[];
|
||||
entities: PermEntity[];
|
||||
actions: PermAction[];
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{ "update:modelValue": [OverrideSchemaIO[]] }>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
type CellState = "inherit" | "grant" | "grant_own" | "revoke";
|
||||
|
||||
const gridStyle = computed(() => ({
|
||||
gridTemplateColumns: `minmax(110px, 1.4fr) repeat(${props.actions.length}, minmax(60px, 1fr))`,
|
||||
}));
|
||||
|
||||
function stateOf(entity: PermEntity, action: PermAction): CellState {
|
||||
const o = props.modelValue.find(
|
||||
(x) => x.entity === entity && x.action === action,
|
||||
);
|
||||
if (!o) return "inherit";
|
||||
if (!o.granted) return "revoke";
|
||||
return o.own_only ? "grant_own" : "grant";
|
||||
}
|
||||
|
||||
// Cycle: inherit (empty) -> grant (primary check) -> grant-own (accent
|
||||
// person) -> revoke (danger cross).
|
||||
const OVR_STATES: RCheckboxState[] = [
|
||||
{ value: "inherit" },
|
||||
{ value: "grant", color: "primary" },
|
||||
{ value: "grant_own", color: "accent", icon: "mdi-account" },
|
||||
{ value: "revoke", color: "danger", icon: "mdi-close" },
|
||||
];
|
||||
|
||||
function onState(entity: PermEntity, action: PermAction, value: string) {
|
||||
const without = props.modelValue.filter(
|
||||
(x) => !(x.entity === entity && x.action === action),
|
||||
);
|
||||
if (value === "inherit") {
|
||||
emit("update:modelValue", without);
|
||||
return;
|
||||
}
|
||||
emit("update:modelValue", [
|
||||
...without,
|
||||
{
|
||||
entity,
|
||||
action,
|
||||
granted: value !== "revoke",
|
||||
own_only: value === "grant_own",
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
function stateLabel(state: CellState): string {
|
||||
return t(`settings.override-${state.replace("_", "-")}`);
|
||||
}
|
||||
|
||||
// Only "grant-own" needs spelling out beyond its label.
|
||||
function stateHint(state: CellState): string {
|
||||
return state === "grant_own" ? t("settings.perm-own-only-hint") : "";
|
||||
}
|
||||
|
||||
const entityLabel = (e: PermEntity) => t(`settings.perm-entity.${e}`);
|
||||
const actionLabel = (a: PermAction) => t(`settings.perm-action.${a}`);
|
||||
|
||||
// Per-column select-all: "set" = any non-"inherit" override for the action.
|
||||
// Selecting all applies a plain grant; clearing returns the column to inherit.
|
||||
function columnAllSet(a: PermAction): boolean {
|
||||
return (
|
||||
props.entities.length > 0 &&
|
||||
props.entities.every((e) => stateOf(e, a) !== "inherit")
|
||||
);
|
||||
}
|
||||
function columnSomeSet(a: PermAction): boolean {
|
||||
return props.entities.some((e) => stateOf(e, a) !== "inherit");
|
||||
}
|
||||
function toggleColumn(a: PermAction, value: boolean) {
|
||||
const without = props.modelValue.filter((x) => x.action !== a);
|
||||
if (value) {
|
||||
emit("update:modelValue", [
|
||||
...without,
|
||||
...props.entities.map((e) => ({
|
||||
entity: e,
|
||||
action: a,
|
||||
granted: true,
|
||||
own_only: false,
|
||||
})),
|
||||
]);
|
||||
} else {
|
||||
emit("update:modelValue", without);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="r-v2-ovr-matrix">
|
||||
<div class="r-v2-ovr-matrix__head" :style="gridStyle">
|
||||
<span class="r-v2-ovr-matrix__corner">
|
||||
{{ t("settings.perm-entity-label") }}
|
||||
</span>
|
||||
<div v-for="a in actions" :key="a" class="r-v2-ovr-matrix__col">
|
||||
<span class="r-v2-ovr-matrix__col-label">{{ actionLabel(a) }}</span>
|
||||
<RCheckbox
|
||||
bare
|
||||
size="sm"
|
||||
color="primary"
|
||||
:model-value="columnAllSet(a)"
|
||||
:indeterminate="columnSomeSet(a) && !columnAllSet(a)"
|
||||
:aria-label="`${t('rom.select-all')} ${actionLabel(a)}`"
|
||||
@update:model-value="(v) => toggleColumn(a, v)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-for="e in entities"
|
||||
:key="e"
|
||||
class="r-v2-ovr-matrix__row"
|
||||
:style="gridStyle"
|
||||
>
|
||||
<span class="r-v2-ovr-matrix__entity">{{ entityLabel(e) }}</span>
|
||||
<div v-for="a in actions" :key="a" class="r-v2-ovr-matrix__cell">
|
||||
<RTooltip
|
||||
activator="parent"
|
||||
location="top"
|
||||
:text="stateLabel(stateOf(e, a))"
|
||||
:hint="stateHint(stateOf(e, a))"
|
||||
/>
|
||||
<RCheckbox
|
||||
bare
|
||||
size="sm"
|
||||
:states="OVR_STATES"
|
||||
:state-value="stateOf(e, a)"
|
||||
:aria-label="`${entityLabel(e)} ${actionLabel(a)} ${stateLabel(stateOf(e, a))}`"
|
||||
@update:state-value="(v) => onState(e, a, v)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.r-v2-ovr-matrix {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border: 1px solid var(--r-color-border);
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.r-v2-ovr-matrix__head,
|
||||
.r-v2-ovr-matrix__row {
|
||||
display: grid;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 14px;
|
||||
}
|
||||
.r-v2-ovr-matrix__head {
|
||||
background: var(--r-color-surface);
|
||||
border-bottom: 1px solid var(--r-color-border);
|
||||
}
|
||||
.r-v2-ovr-matrix__row:not(:last-child) {
|
||||
border-bottom: 1px solid var(--r-color-border);
|
||||
}
|
||||
.r-v2-ovr-matrix__corner,
|
||||
.r-v2-ovr-matrix__col-label {
|
||||
font-size: 11px;
|
||||
font-weight: var(--r-font-weight-bold);
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: var(--r-color-fg-secondary);
|
||||
}
|
||||
.r-v2-ovr-matrix__col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
text-align: center;
|
||||
}
|
||||
.r-v2-ovr-matrix__entity {
|
||||
font-weight: var(--r-font-weight-semibold);
|
||||
text-transform: capitalize;
|
||||
}
|
||||
.r-v2-ovr-matrix__cell {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
</style>
|
||||
289
frontend/src/v2/components/Settings/PermissionGroupsSection.vue
Normal file
289
frontend/src/v2/components/Settings/PermissionGroupsSection.vue
Normal file
@@ -0,0 +1,289 @@
|
||||
<script setup lang="ts">
|
||||
// PermissionGroupsSection — v2 admin table of permission groups. Mirrors
|
||||
// UsersSection's layout (table + bottom action button). Reads the shared
|
||||
// permissionGroups store; create/edit go through GroupFormDialog (which
|
||||
// refetches the store), delete removes from the store via useConfirm.
|
||||
import {
|
||||
RBtn,
|
||||
RIcon,
|
||||
RTable,
|
||||
RTag,
|
||||
RTextField,
|
||||
RTooltip,
|
||||
type RTableColumn,
|
||||
type RTableSortPayload,
|
||||
} from "@v2/lib";
|
||||
import type { Emitter } from "mitt";
|
||||
import { computed, inject, onMounted, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { PermissionGroupSchema } from "@/__generated__";
|
||||
import permissionsApi from "@/services/api/permissions";
|
||||
import storePermissionGroups from "@/stores/permissionGroups";
|
||||
import type { Events } from "@/types/emitter";
|
||||
import { useConfirm } from "@/v2/composables/useConfirm";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
import { groupColor } from "@/v2/utils/groupColor";
|
||||
|
||||
defineOptions({ inheritAttrs: false });
|
||||
|
||||
const { t } = useI18n();
|
||||
const emitter = inject<Emitter<Events>>("emitter");
|
||||
const snackbar = useSnackbar();
|
||||
const confirm = useConfirm();
|
||||
const groupsStore = storePermissionGroups();
|
||||
|
||||
const search = ref("");
|
||||
|
||||
const sortKey = ref<"name" | "member_count">("name");
|
||||
const sortDir = ref<"asc" | "desc">("asc");
|
||||
|
||||
const sorted = computed(() => {
|
||||
const list = [...groupsStore.groups];
|
||||
const asc = sortDir.value === "asc";
|
||||
list.sort((a, b) => {
|
||||
if (sortKey.value === "member_count") {
|
||||
return asc
|
||||
? a.member_count - b.member_count
|
||||
: b.member_count - a.member_count;
|
||||
}
|
||||
return asc ? a.name.localeCompare(b.name) : b.name.localeCompare(a.name);
|
||||
});
|
||||
return list;
|
||||
});
|
||||
|
||||
const filtered = computed(() => {
|
||||
const q = search.value.trim().toLowerCase();
|
||||
if (!q) return sorted.value;
|
||||
return sorted.value.filter(
|
||||
(g) =>
|
||||
g.name.toLowerCase().includes(q) ||
|
||||
g.description.toLowerCase().includes(q),
|
||||
);
|
||||
});
|
||||
|
||||
const columns = computed<RTableColumn[]>(() => [
|
||||
{
|
||||
key: "name",
|
||||
label: t("common.name"),
|
||||
sortable: true,
|
||||
width: "minmax(0, 1.4fr)",
|
||||
skeletonWidth: 160,
|
||||
},
|
||||
{
|
||||
key: "description",
|
||||
label: t("settings.description"),
|
||||
width: "minmax(0, 2fr)",
|
||||
skeletonWidth: 220,
|
||||
},
|
||||
{
|
||||
key: "member_count",
|
||||
label: t("settings.group-members"),
|
||||
sortable: true,
|
||||
width: "minmax(0, 0.8fr)",
|
||||
align: "center",
|
||||
skeletonWidth: 60,
|
||||
},
|
||||
{
|
||||
key: "actions",
|
||||
label: "",
|
||||
width: "96px",
|
||||
align: "end",
|
||||
skeletonWidth: 0,
|
||||
},
|
||||
]);
|
||||
|
||||
function onSort({ key, dir }: RTableSortPayload) {
|
||||
if (key !== "name" && key !== "member_count") return;
|
||||
sortKey.value = key;
|
||||
sortDir.value = dir;
|
||||
}
|
||||
|
||||
async function fetchGroups() {
|
||||
try {
|
||||
await groupsStore.fetch();
|
||||
} catch (err) {
|
||||
console.error("Failed to load permission groups", err);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteGroup(group: PermissionGroupSchema) {
|
||||
const ok = await confirm({
|
||||
title: t("common.confirm-deletion"),
|
||||
body: t("settings.group-delete-confirm", { name: group.name }),
|
||||
confirmText: t("common.delete"),
|
||||
tone: "danger",
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await permissionsApi.deleteGroup(group.id);
|
||||
snackbar.success(t("settings.group-removed", { name: group.name }), {
|
||||
icon: "mdi-check-bold",
|
||||
});
|
||||
groupsStore.remove(group.id);
|
||||
} catch (err) {
|
||||
const e = err as {
|
||||
response?: { data?: { detail?: string }; statusText?: string };
|
||||
message?: string;
|
||||
};
|
||||
snackbar.error(
|
||||
t("settings.group-delete-failed", {
|
||||
detail:
|
||||
e?.response?.data?.detail || e?.response?.statusText || e?.message,
|
||||
}),
|
||||
{ icon: "mdi-close-circle" },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(fetchGroups);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="r-v2-groups">
|
||||
<RTextField
|
||||
v-model="search"
|
||||
prefix-label="inline"
|
||||
:placeholder="t('common.search')"
|
||||
hide-details
|
||||
density="compact"
|
||||
:aria-label="t('settings.search-groups')"
|
||||
>
|
||||
<template #prefix-label>
|
||||
<RIcon icon="mdi-magnify" size="15" />
|
||||
</template>
|
||||
</RTextField>
|
||||
|
||||
<RTable
|
||||
:columns="columns"
|
||||
:items="filtered"
|
||||
:item-key="(r) => (r as PermissionGroupSchema).id"
|
||||
:sort-key="sortKey"
|
||||
:sort-dir="sortDir"
|
||||
:loading="groupsStore.loading"
|
||||
empty-icon="mdi-shield-off-outline"
|
||||
:empty-message="t('settings.groups-empty')"
|
||||
@update:sort="onSort"
|
||||
>
|
||||
<template #cell.name="{ row }">
|
||||
<div class="r-v2-groups__name">
|
||||
<span
|
||||
class="r-v2-groups__dot"
|
||||
:style="{
|
||||
background: groupColor((row as PermissionGroupSchema).color),
|
||||
}"
|
||||
/>
|
||||
<span>{{ (row as PermissionGroupSchema).name }}</span>
|
||||
<RTag
|
||||
v-if="(row as PermissionGroupSchema).is_default"
|
||||
tone="brand"
|
||||
:text="t('settings.group-default-tag')"
|
||||
size="x-small"
|
||||
/>
|
||||
<RTag
|
||||
v-if="(row as PermissionGroupSchema).is_system"
|
||||
tone="info"
|
||||
:text="t('settings.group-system-tag')"
|
||||
size="x-small"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<template #cell.description="{ row }">
|
||||
<span class="r-v2-groups__desc">
|
||||
{{ (row as PermissionGroupSchema).description || "—" }}
|
||||
</span>
|
||||
</template>
|
||||
<template #cell.member_count="{ row }">
|
||||
{{ (row as PermissionGroupSchema).member_count }}
|
||||
</template>
|
||||
<template #cell.actions="{ row }">
|
||||
<div class="r-v2-groups__actions">
|
||||
<RTooltip>
|
||||
<template #activator="{ props: tipProps }">
|
||||
<RBtn
|
||||
v-bind="tipProps"
|
||||
variant="text"
|
||||
size="small"
|
||||
icon="mdi-pencil"
|
||||
:aria-label="t('settings.edit-group')"
|
||||
@click="
|
||||
emitter?.emit(
|
||||
'showGroupFormDialog',
|
||||
row as PermissionGroupSchema,
|
||||
)
|
||||
"
|
||||
/>
|
||||
</template>
|
||||
<span>{{ t("settings.edit-group") }}</span>
|
||||
</RTooltip>
|
||||
<RTooltip>
|
||||
<template #activator="{ props: tipProps }">
|
||||
<RBtn
|
||||
v-bind="tipProps"
|
||||
variant="text"
|
||||
size="small"
|
||||
color="danger"
|
||||
icon="mdi-trash-can-outline"
|
||||
:disabled="(row as PermissionGroupSchema).is_default"
|
||||
:aria-label="t('common.delete')"
|
||||
@click="deleteGroup(row as PermissionGroupSchema)"
|
||||
/>
|
||||
</template>
|
||||
<span>{{ t("common.delete") }}</span>
|
||||
</RTooltip>
|
||||
</div>
|
||||
</template>
|
||||
</RTable>
|
||||
|
||||
<div class="r-v2-groups__footer">
|
||||
<RBtn
|
||||
variant="flat"
|
||||
color="primary"
|
||||
prepend-icon="mdi-plus"
|
||||
@click="emitter?.emit('showGroupFormDialog', null)"
|
||||
>
|
||||
{{ t("settings.new-group") }}
|
||||
</RBtn>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.r-v2-groups {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
/* A touch more breathing room before the colour dot (and matching header). */
|
||||
.r-v2-groups :deep(.r-table__header-cell:first-child),
|
||||
.r-v2-groups :deep(.r-table__cell:first-child) {
|
||||
padding-inline-start: 6px;
|
||||
}
|
||||
.r-v2-groups__name {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-weight: var(--r-font-weight-semibold);
|
||||
min-width: 0;
|
||||
}
|
||||
.r-v2-groups__dot {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 50%;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.r-v2-groups__desc {
|
||||
color: var(--r-color-fg-muted);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.r-v2-groups__actions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
.r-v2-groups__footer {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
</style>
|
||||
208
frontend/src/v2/components/Settings/PermissionsMatrix.vue
Normal file
208
frontend/src/v2/components/Settings/PermissionsMatrix.vue
Normal file
@@ -0,0 +1,208 @@
|
||||
<script setup lang="ts">
|
||||
// PermissionsMatrix — entity (rows) x action (columns) grid of tri-state
|
||||
// checkboxes for the group editor. Each cell cycles none -> full -> own ->
|
||||
// none: "none" is no grant, "full" is library-wide (primary), "own" limits
|
||||
// the grant to the user's own items (accent, own_only). The model is the list
|
||||
// of granted (entity, action) pairs; cycling rewrites the touched cell only.
|
||||
import { RCheckbox, type RCheckboxState, RTooltip } from "@v2/lib";
|
||||
import { computed } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { GrantSchemaIO, PermAction, PermEntity } from "@/__generated__";
|
||||
|
||||
defineOptions({ inheritAttrs: false });
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: GrantSchemaIO[];
|
||||
entities: PermEntity[];
|
||||
actions: PermAction[];
|
||||
readonly?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{ "update:modelValue": [GrantSchemaIO[]] }>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
type CellState = "none" | "full" | "own";
|
||||
|
||||
const gridStyle = computed(() => ({
|
||||
gridTemplateColumns: `minmax(110px, 1.4fr) repeat(${props.actions.length}, minmax(60px, 1fr))`,
|
||||
}));
|
||||
|
||||
function grantOf(
|
||||
entity: PermEntity,
|
||||
action: PermAction,
|
||||
): GrantSchemaIO | undefined {
|
||||
return props.modelValue.find(
|
||||
(g) => g.entity === entity && g.action === action,
|
||||
);
|
||||
}
|
||||
|
||||
function stateOf(entity: PermEntity, action: PermAction): CellState {
|
||||
const g = grantOf(entity, action);
|
||||
if (!g) return "none";
|
||||
return g.own_only ? "own" : "full";
|
||||
}
|
||||
|
||||
// Cycle: none (empty) -> full (primary check) -> own (accent person).
|
||||
const PERM_STATES: RCheckboxState[] = [
|
||||
{ value: "none" },
|
||||
{ value: "full", color: "primary" },
|
||||
{ value: "own", color: "accent", icon: "mdi-account" },
|
||||
];
|
||||
|
||||
function onState(entity: PermEntity, action: PermAction, value: string) {
|
||||
if (props.readonly) return;
|
||||
const without = props.modelValue.filter(
|
||||
(g) => !(g.entity === entity && g.action === action),
|
||||
);
|
||||
if (value === "none") {
|
||||
emit("update:modelValue", without);
|
||||
} else {
|
||||
emit("update:modelValue", [
|
||||
...without,
|
||||
{ entity, action, own_only: value === "own" },
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
function stateLabel(state: CellState): string {
|
||||
return t(`settings.grant-${state}`);
|
||||
}
|
||||
|
||||
// Extra explanation shown under the state label in the tooltip; only "own"
|
||||
// needs spelling out (the others are self-evident from their label).
|
||||
function stateHint(state: CellState): string {
|
||||
return state === "own" ? t("settings.perm-own-only-hint") : "";
|
||||
}
|
||||
|
||||
const entityLabel = (e: PermEntity) => t(`settings.perm-entity.${e}`);
|
||||
const actionLabel = (a: PermAction) => t(`settings.perm-action.${a}`);
|
||||
|
||||
// Per-column select-all: granted = any non-"none" state for the action.
|
||||
function columnAllGranted(a: PermAction): boolean {
|
||||
return (
|
||||
props.entities.length > 0 &&
|
||||
props.entities.every((e) => stateOf(e, a) !== "none")
|
||||
);
|
||||
}
|
||||
function columnSomeGranted(a: PermAction): boolean {
|
||||
return props.entities.some((e) => stateOf(e, a) !== "none");
|
||||
}
|
||||
function toggleColumn(a: PermAction, value: boolean) {
|
||||
if (props.readonly) return;
|
||||
const without = props.modelValue.filter((g) => g.action !== a);
|
||||
if (value) {
|
||||
emit("update:modelValue", [
|
||||
...without,
|
||||
...props.entities.map((e) => ({ entity: e, action: a, own_only: false })),
|
||||
]);
|
||||
} else {
|
||||
emit("update:modelValue", without);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="r-v2-perm-matrix">
|
||||
<div class="r-v2-perm-matrix__head" :style="gridStyle">
|
||||
<span class="r-v2-perm-matrix__corner">
|
||||
{{ t("settings.perm-entity-label") }}
|
||||
</span>
|
||||
<div v-for="a in actions" :key="a" class="r-v2-perm-matrix__col">
|
||||
<span class="r-v2-perm-matrix__col-label" :title="actionLabel(a)">
|
||||
{{ actionLabel(a) }}
|
||||
</span>
|
||||
<RCheckbox
|
||||
bare
|
||||
size="sm"
|
||||
color="primary"
|
||||
:model-value="columnAllGranted(a)"
|
||||
:indeterminate="columnSomeGranted(a) && !columnAllGranted(a)"
|
||||
:disabled="readonly"
|
||||
:aria-label="`${t('rom.select-all')} ${actionLabel(a)}`"
|
||||
@update:model-value="(v) => toggleColumn(a, v)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-for="e in entities"
|
||||
:key="e"
|
||||
class="r-v2-perm-matrix__row"
|
||||
:style="gridStyle"
|
||||
>
|
||||
<span class="r-v2-perm-matrix__entity">{{ entityLabel(e) }}</span>
|
||||
<div v-for="a in actions" :key="a" class="r-v2-perm-matrix__cell">
|
||||
<RTooltip
|
||||
activator="parent"
|
||||
location="top"
|
||||
:text="stateLabel(stateOf(e, a))"
|
||||
:hint="stateHint(stateOf(e, a))"
|
||||
/>
|
||||
<RCheckbox
|
||||
bare
|
||||
size="sm"
|
||||
:states="PERM_STATES"
|
||||
:state-value="stateOf(e, a)"
|
||||
:disabled="readonly"
|
||||
:aria-label="`${entityLabel(e)} ${actionLabel(a)} ${stateLabel(stateOf(e, a))}`"
|
||||
@update:state-value="(v) => onState(e, a, v)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.r-v2-perm-matrix {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border: 1px solid var(--r-color-border);
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.r-v2-perm-matrix__head,
|
||||
.r-v2-perm-matrix__row {
|
||||
display: grid;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 14px;
|
||||
}
|
||||
|
||||
.r-v2-perm-matrix__head {
|
||||
background: var(--r-color-surface);
|
||||
border-bottom: 1px solid var(--r-color-border);
|
||||
}
|
||||
|
||||
.r-v2-perm-matrix__row:not(:last-child) {
|
||||
border-bottom: 1px solid var(--r-color-border);
|
||||
}
|
||||
|
||||
.r-v2-perm-matrix__corner,
|
||||
.r-v2-perm-matrix__col-label {
|
||||
font-size: 11px;
|
||||
font-weight: var(--r-font-weight-bold);
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: var(--r-color-fg-secondary);
|
||||
}
|
||||
|
||||
.r-v2-perm-matrix__col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.r-v2-perm-matrix__entity {
|
||||
font-weight: var(--r-font-weight-semibold);
|
||||
text-transform: capitalize;
|
||||
}
|
||||
|
||||
.r-v2-perm-matrix__cell {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
</style>
|
||||
@@ -24,13 +24,16 @@ import type { Emitter } from "mitt";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { computed, inject, onMounted, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { PermissionGroupSchema } from "@/__generated__";
|
||||
import userApi from "@/services/api/user";
|
||||
import storeAuth from "@/stores/auth";
|
||||
import storePermissionGroups from "@/stores/permissionGroups";
|
||||
import storeUsers, { type User } from "@/stores/users";
|
||||
import type { Events } from "@/types/emitter";
|
||||
import { formatTimestamp, getRoleIcon } from "@/utils";
|
||||
import { formatTimestamp } from "@/utils";
|
||||
import { useConfirm } from "@/v2/composables/useConfirm";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
import { groupColor } from "@/v2/utils/groupColor";
|
||||
import { userAvatarUrl } from "@/v2/utils/userAvatar";
|
||||
|
||||
defineOptions({ inheritAttrs: false });
|
||||
@@ -42,13 +45,49 @@ const auth = storeAuth();
|
||||
const emitter = inject<Emitter<Events>>("emitter");
|
||||
const snackbar = useSnackbar();
|
||||
const confirm = useConfirm();
|
||||
const groupsStore = storePermissionGroups();
|
||||
|
||||
const search = ref("");
|
||||
|
||||
type SortKey = "username" | "email" | "role" | "last_active";
|
||||
type SortKey = "username" | "email" | "last_active" | "access";
|
||||
const sortKey = ref<SortKey>("username");
|
||||
const sortDir = ref<"asc" | "desc">("asc");
|
||||
|
||||
// Admins bypass groups; everyone else shows their group name. A user with no
|
||||
// explicit group follows the server default group, so resolve to that.
|
||||
function resolveGroup(user: User): PermissionGroupSchema | undefined {
|
||||
return (
|
||||
groupsStore.groups.find((x) => x.id === user.permission_group_id) ??
|
||||
groupsStore.defaultGroup
|
||||
);
|
||||
}
|
||||
|
||||
function groupLabel(user: User): string {
|
||||
const g = resolveGroup(user);
|
||||
return g ? g.name : t("settings.group-default-option");
|
||||
}
|
||||
|
||||
function groupPillColor(user: User): string {
|
||||
return groupColor(resolveGroup(user)?.color);
|
||||
}
|
||||
|
||||
// The pill mirrors the admin RTag chrome (same shape/size) but tinted with
|
||||
// the group's colour — override RTag's tone vars with the group hue.
|
||||
function groupPillStyle(user: User) {
|
||||
const c = groupPillColor(user);
|
||||
return {
|
||||
"--r-tag-fg": `color-mix(in srgb, ${c} 90%, transparent)`,
|
||||
"--r-tag-border": `color-mix(in srgb, ${c} 40%, transparent)`,
|
||||
"--r-tag-bg": `color-mix(in srgb, ${c} 14%, transparent)`,
|
||||
};
|
||||
}
|
||||
|
||||
// Sort key for the Access column: admins grouped under their label, others
|
||||
// by their (resolved) group name.
|
||||
function accessText(user: User): string {
|
||||
return user.role === "admin" ? t("settings.administrator") : groupLabel(user);
|
||||
}
|
||||
|
||||
// Same nullable-string compare we use in ClientApiTokens — keeps users
|
||||
// with no email / no last-active timestamp at the end on `asc`.
|
||||
function compareNullable(
|
||||
@@ -71,8 +110,10 @@ const sortedUsers = computed(() => {
|
||||
? a.username.localeCompare(b.username)
|
||||
: b.username.localeCompare(a.username);
|
||||
}
|
||||
if (sortKey.value === "role") {
|
||||
return asc ? a.role.localeCompare(b.role) : b.role.localeCompare(a.role);
|
||||
if (sortKey.value === "access") {
|
||||
return asc
|
||||
? accessText(a).localeCompare(accessText(b))
|
||||
: accessText(b).localeCompare(accessText(a));
|
||||
}
|
||||
return compareNullable(a[sortKey.value], b[sortKey.value], asc);
|
||||
});
|
||||
@@ -105,11 +146,11 @@ const columns = computed<RTableColumn[]>(() => [
|
||||
skeletonWidth: 180,
|
||||
},
|
||||
{
|
||||
key: "role",
|
||||
label: t("settings.role"),
|
||||
key: "access",
|
||||
label: t("settings.access"),
|
||||
sortable: true,
|
||||
width: "minmax(0, 0.8fr)",
|
||||
skeletonWidth: 80,
|
||||
width: "minmax(0, 1fr)",
|
||||
skeletonWidth: 110,
|
||||
},
|
||||
{
|
||||
key: "last_active",
|
||||
@@ -138,8 +179,8 @@ function onSort({ key, dir }: RTableSortPayload) {
|
||||
if (
|
||||
key !== "username" &&
|
||||
key !== "email" &&
|
||||
key !== "role" &&
|
||||
key !== "last_active"
|
||||
key !== "last_active" &&
|
||||
key !== "access"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
@@ -147,17 +188,6 @@ function onSort({ key, dir }: RTableSortPayload) {
|
||||
sortDir.value = dir;
|
||||
}
|
||||
|
||||
type RoleTone = "brand" | "warning" | "info";
|
||||
const ROLE_TONE: Record<string, RoleTone> = {
|
||||
admin: "brand",
|
||||
editor: "warning",
|
||||
viewer: "info",
|
||||
};
|
||||
function roleToneFor(role: string | undefined): RoleTone {
|
||||
if (role && role in ROLE_TONE) return ROLE_TONE[role];
|
||||
return "info";
|
||||
}
|
||||
|
||||
function avatarSrc(user: User) {
|
||||
return userAvatarUrl(user.avatar_path, user.updated_at);
|
||||
}
|
||||
@@ -219,8 +249,11 @@ const loading = ref(true);
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const { data } = await userApi.fetchUsers();
|
||||
usersStore.set(data);
|
||||
const [usersResp] = await Promise.all([
|
||||
userApi.fetchUsers(),
|
||||
groupsStore.ensureLoaded(),
|
||||
]);
|
||||
usersStore.set(usersResp.data);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} finally {
|
||||
@@ -269,13 +302,19 @@ onMounted(async () => {
|
||||
<template #cell.email="{ row }">
|
||||
<span class="r-v2-users__meta">{{ (row as User).email || "—" }}</span>
|
||||
</template>
|
||||
<template #cell.role="{ row }">
|
||||
<template #cell.access="{ row }">
|
||||
<RTag
|
||||
:tone="roleToneFor((row as User).role)"
|
||||
:prepend-icon="getRoleIcon((row as User).role)"
|
||||
:text="(row as User).role"
|
||||
size="x-small"
|
||||
class="r-v2-users__role-tag"
|
||||
v-if="(row as User).role === 'admin'"
|
||||
tone="brand"
|
||||
prepend-icon="mdi-shield-crown-outline"
|
||||
:text="t('settings.administrator')"
|
||||
class="r-v2-users__access-pill"
|
||||
/>
|
||||
<RTag
|
||||
v-else
|
||||
:style="groupPillStyle(row as User)"
|
||||
:text="groupLabel(row as User)"
|
||||
class="r-v2-users__access-pill"
|
||||
/>
|
||||
</template>
|
||||
<template #cell.last_active="{ row }">
|
||||
@@ -375,10 +414,6 @@ onMounted(async () => {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.r-v2-users__role-tag {
|
||||
text-transform: capitalize;
|
||||
}
|
||||
|
||||
.r-v2-users__meta {
|
||||
color: var(--r-color-fg-muted);
|
||||
white-space: nowrap;
|
||||
@@ -386,6 +421,18 @@ onMounted(async () => {
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
/* A touch more breathing room before the avatar (and matching header). */
|
||||
.r-v2-users :deep(.r-table__header-cell:first-child),
|
||||
.r-v2-users :deep(.r-table__cell:first-child) {
|
||||
padding-inline-start: 6px;
|
||||
}
|
||||
|
||||
/* Keep the admin pill the same height as the icon-less group pills — the
|
||||
prepend icon's vertical margin would otherwise make it a touch taller. */
|
||||
.r-v2-users :deep(.r-v2-users__access-pill .r-tag__icon) {
|
||||
margin-block: 0;
|
||||
}
|
||||
|
||||
.r-v2-users__actions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user