mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
* feat(auth): use the OIDC picture claim as the user's avatar On each OIDC sign-in, a user with no avatar, or one synced from the provider earlier, gets the picture claim stored as their avatar. An uploaded avatar is never replaced. The download goes through the SSRF-guarded client (the configured provider's origin may reach a LAN address), is capped at 5 MB, must sniff as a supported image, and any failure is logged without blocking the sign-in. Closes #4297 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(auth): address review on the OIDC avatar sync Addresses Greptile's review on #5730: - ask the UserInfo endpoint when the ID token has no picture claim - keep an avatar uploaded while the picture downloaded - allow only the OIDC provider's origins to reach private addresses - trim docstrings and narrow await_args in the callback test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(auth): type the OIDC avatar test helpers for mypy Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: code-review Bound the OIDC picture download with an overall deadline, trust the OIDC CA bundle, catch hostname encoding errors so sign-in never 500s, and set the synced avatar with a conditional update so a concurrent upload wins. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: simplify Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: review-polish Type the pytest fixtures and helpers in the OIDC avatar tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: prose Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(auth): remove the synced OIDC avatar when the user uploads one Once avatar_path points at the uploaded avatar.<ext>, the sync never touches the user's avatar again, so the old oidc-avatar.<ext> file would otherwise stay on disk for good. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
769 lines
25 KiB
Python
769 lines
25 KiB
Python
import asyncio
|
|
import json
|
|
from typing import Annotated, Any, Final
|
|
|
|
from fastapi import Body, Form, HTTPException
|
|
from fastapi import Path as PathVar
|
|
from fastapi import Query, Request, status
|
|
from fastapi.responses import FileResponse
|
|
|
|
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 exceptions.database_exceptions import LastAdminError
|
|
from handler.audit_handler import (
|
|
AuditActor,
|
|
AuditTarget,
|
|
change,
|
|
changed_fields,
|
|
client_ip,
|
|
record,
|
|
)
|
|
from handler.auth.base_handler import auth_handler
|
|
from handler.auth.constants import Scope
|
|
from handler.auth.dependencies import assert_admin_for_admin
|
|
from handler.auth.oidc_avatar import discard_oidc_avatar
|
|
from handler.database import (
|
|
db_client_token_handler,
|
|
db_device_handler,
|
|
db_user_handler,
|
|
)
|
|
from handler.device_install import device_install_handler
|
|
from handler.filesystem import fs_asset_handler
|
|
from handler.filesystem.assets_handler import (
|
|
build_asset_file_response,
|
|
validate_image_upload,
|
|
)
|
|
from handler.notification_handler import notify
|
|
from handler.play_session_handler import queue_ra_progress_sync
|
|
from handler.socket_handler import close_client_token_sockets
|
|
from logger.logger import log
|
|
from models.audit_event import AuditAction
|
|
from models.notification import NotificationKind, NotificationLevel
|
|
from models.user import Role, User
|
|
from utils.router import APIRouter
|
|
from utils.validation import (
|
|
ValidationError,
|
|
validate_email,
|
|
validate_password,
|
|
validate_username,
|
|
)
|
|
|
|
router = APIRouter(
|
|
prefix="/users",
|
|
tags=["users"],
|
|
)
|
|
|
|
|
|
# What a user edit reports; ui_settings and avatars change too often to be news.
|
|
_USER_EDIT_AUDIT_FIELDS: Final = (
|
|
"username",
|
|
"email",
|
|
"hashed_password",
|
|
"role",
|
|
"enabled",
|
|
)
|
|
|
|
|
|
def _record_user_edit(
|
|
request: Request, before: User, after: User, cleaned_data: dict[str, Any]
|
|
) -> None:
|
|
changed = changed_fields(
|
|
before, after, [f for f in _USER_EDIT_AUDIT_FIELDS if f in cleaned_data]
|
|
)
|
|
if not changed:
|
|
return
|
|
data: dict[str, Any] = {
|
|
"changed": ["password" if f == "hashed_password" else f for f in changed]
|
|
}
|
|
for field in ("username", "role", "enabled"):
|
|
if field in changed:
|
|
data[field] = change(before, after, field)
|
|
record(AuditAction.USER_EDIT, request, AuditTarget.of_user(after), data)
|
|
|
|
|
|
async def _submitted_value(
|
|
request: Request, name: str, parsed: str | None
|
|
) -> str | None:
|
|
"""Return a form-model field, keeping a submitted "" the model reads as absent."""
|
|
if parsed is None and (await request.form()).get(name) == "":
|
|
return ""
|
|
return parsed
|
|
|
|
|
|
async def _verify_account_holder(
|
|
request: Request, db_user: User, current_password: str | None
|
|
) -> None:
|
|
"""Require password or session proof for sensitive self-edits."""
|
|
if db_user.has_password:
|
|
if not current_password:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Your current password is required to change your username, password or email",
|
|
)
|
|
# bcrypt takes ~250ms, which would stall the event loop.
|
|
if not await asyncio.to_thread(
|
|
auth_handler.verify_password, current_password, db_user.hashed_password
|
|
):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="Current password is incorrect",
|
|
)
|
|
return
|
|
|
|
# With no password to check, only a sign-in session (OIDC, for these
|
|
# accounts) proves the holder; long-lived tokens are refused.
|
|
if not auth_handler.is_session_authenticated(request, db_user.username):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="Sign in to the web interface to change the username, password or email of this account",
|
|
)
|
|
|
|
|
|
def _assert_can_manage_user(request: Request, target: User) -> None:
|
|
"""Allow acting on yourself, or on another user with USERS_WRITE in the credential."""
|
|
if target.id == request.user.id:
|
|
return
|
|
if Scope.USERS_WRITE not in request.auth.scopes:
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
|
|
assert_admin_for_admin(
|
|
request, target.role, "Only an administrator can manage admin users"
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.post,
|
|
"",
|
|
[],
|
|
status_code=status.HTTP_201_CREATED,
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {
|
|
"description": "A field is invalid, or the username or email is already taken."
|
|
},
|
|
status.HTTP_403_FORBIDDEN: {
|
|
"description": (
|
|
"An admin exists and the caller lacks the `users.write` scope, or"
|
|
" the new user is an admin and the caller is not one."
|
|
)
|
|
},
|
|
},
|
|
)
|
|
def add_user(
|
|
request: Request,
|
|
username: str = Body(..., embed=True),
|
|
email: str = Body(..., embed=True),
|
|
password: str = Body(..., embed=True),
|
|
role: str = Body(..., embed=True),
|
|
) -> UserSchema:
|
|
"""Create a user. Before the first admin exists, any caller can create one."""
|
|
|
|
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 admins_exist:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="Forbidden",
|
|
)
|
|
|
|
coerced_role = Role.coerce(role)
|
|
if admins_exist:
|
|
assert_admin_for_admin(
|
|
request, coerced_role, "Only an administrator can create admin users"
|
|
)
|
|
|
|
try:
|
|
validate_username(username)
|
|
validate_password(password)
|
|
validate_email(email)
|
|
except ValidationError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=exc.message,
|
|
) from exc
|
|
|
|
if db_user_handler.get_user_by_username(username):
|
|
msg = f"Username {username} already exists"
|
|
log.error(msg)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=msg,
|
|
)
|
|
|
|
if email and db_user_handler.get_user_by_email(email):
|
|
msg = f"User with email {email} already exists"
|
|
log.error(msg)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=msg,
|
|
)
|
|
|
|
user = User(
|
|
username=username.lower(),
|
|
hashed_password=auth_handler.get_password_hash(password),
|
|
email=email.lower() or None,
|
|
role=coerced_role,
|
|
)
|
|
|
|
created_user = db_user_handler.add_user(user)
|
|
record(
|
|
AuditAction.USER_CREATE,
|
|
request,
|
|
AuditTarget.of_user(created_user),
|
|
{"role": created_user.role},
|
|
)
|
|
|
|
return UserSchema.model_validate(created_user)
|
|
|
|
|
|
@protected_route(
|
|
router.post,
|
|
"/invite-link",
|
|
[],
|
|
status_code=status.HTTP_201_CREATED,
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {
|
|
"description": "The role is not valid, or the expiration is not a positive number."
|
|
},
|
|
status.HTTP_403_FORBIDDEN: {
|
|
"description": (
|
|
"An admin exists and the caller lacks the `users.write` scope, or"
|
|
" the link is for an admin and the caller is not one."
|
|
)
|
|
},
|
|
},
|
|
)
|
|
def create_invite_link(
|
|
request: Request,
|
|
role: Annotated[
|
|
str,
|
|
Query(
|
|
description=(
|
|
"The role of the invited user: `user` or `admin`. Only an admin"
|
|
" can invite an admin, unless no admin exists yet."
|
|
)
|
|
),
|
|
],
|
|
expiration: Annotated[
|
|
int | None,
|
|
Query(
|
|
description=(
|
|
"The lifetime of the link, in seconds. Defaults to"
|
|
" `INVITE_TOKEN_EXPIRY_SECONDS`, which is 600 unless changed."
|
|
)
|
|
),
|
|
] = None,
|
|
) -> InviteLinkSchema:
|
|
"""Create an invite link that lets someone register a user with the given role."""
|
|
|
|
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",
|
|
)
|
|
|
|
if role not in [r.value for r in Role]:
|
|
msg = f"Role {role} is not valid"
|
|
log.error(msg)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=msg,
|
|
)
|
|
|
|
if admins_exist:
|
|
assert_admin_for_admin(
|
|
request,
|
|
Role.coerce(role),
|
|
"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)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=msg,
|
|
)
|
|
|
|
token = auth_handler.generate_invite_link_token(
|
|
request.user, role=role, expiration=expiration
|
|
)
|
|
return InviteLinkSchema.from_token(token)
|
|
|
|
|
|
@router.post(
|
|
"/register",
|
|
status_code=status.HTTP_201_CREATED,
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {
|
|
"description": (
|
|
"The invite token is not valid or already used, a field is invalid,"
|
|
" or the username or email is already taken."
|
|
)
|
|
}
|
|
},
|
|
)
|
|
def create_user_from_invite(
|
|
request: Request,
|
|
username: str = Body(..., embed=True),
|
|
email: str = Body(..., embed=True),
|
|
password: str = Body(..., embed=True),
|
|
token: str = Body(..., embed=True),
|
|
) -> UserSchema:
|
|
"""Register a user from an invite link. The new user gets the role the link was created for."""
|
|
|
|
# Ahead of the "already exists" checks, which would otherwise enumerate
|
|
# accounts for an invalid token. Not consumed, so a retry keeps the invite.
|
|
auth_handler.assert_invite_link_token_valid(token)
|
|
|
|
try:
|
|
validate_username(username)
|
|
validate_password(password)
|
|
validate_email(email)
|
|
except ValidationError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=exc.message,
|
|
) from exc
|
|
|
|
if db_user_handler.get_user_by_username(username):
|
|
msg = f"Username {username} already exists"
|
|
log.error(msg)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=msg,
|
|
)
|
|
|
|
if email and db_user_handler.get_user_by_email(email):
|
|
msg = f"User with email {email} already exists"
|
|
log.error(msg)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=msg,
|
|
)
|
|
|
|
role = auth_handler.consume_invite_link_token(token)
|
|
user = User(
|
|
username=username.lower(),
|
|
hashed_password=auth_handler.get_password_hash(password),
|
|
email=email.lower() or None,
|
|
role=Role.coerce(role),
|
|
)
|
|
|
|
created_user = db_user_handler.add_user(user)
|
|
record(
|
|
AuditAction.USER_REGISTER,
|
|
AuditActor.for_user(created_user, ip_address=client_ip(request)),
|
|
AuditTarget.of_user(created_user),
|
|
{"role": created_user.role, "via": "invite"},
|
|
)
|
|
|
|
return UserSchema.model_validate(created_user)
|
|
|
|
|
|
@protected_route(router.get, "", [Scope.USERS_READ])
|
|
def get_users(request: Request) -> list[UserSchema]:
|
|
"""List all users."""
|
|
|
|
return [UserSchema.model_validate(u) for u in db_user_handler.get_users()]
|
|
|
|
|
|
@protected_route(router.get, "/identifiers", [Scope.USERS_READ])
|
|
def get_user_identifiers(
|
|
request: Request,
|
|
) -> list[int]:
|
|
"""List the IDs of all users."""
|
|
|
|
users = db_user_handler.get_users(only_fields=[User.id])
|
|
return [u.id for u in users]
|
|
|
|
|
|
@protected_route(router.get, "/me", [Scope.ME_READ])
|
|
def get_current_user(request: Request) -> UserSchema | None:
|
|
"""Get the user making the request."""
|
|
|
|
return UserSchema.from_orm_with_request(request.user, request)
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/{id}",
|
|
[Scope.USERS_READ],
|
|
responses={status.HTTP_404_NOT_FOUND: {"description": "No user has this ID."}},
|
|
)
|
|
def get_user(
|
|
request: Request, id: Annotated[int, PathVar(description="The ID of the user.")]
|
|
) -> UserSchema:
|
|
"""Get a user by ID."""
|
|
|
|
user = db_user_handler.get_user(id)
|
|
if not user:
|
|
raise HTTPException(status_code=404, detail="User not found")
|
|
|
|
return UserSchema.model_validate(user)
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/{id}/avatar",
|
|
[Scope.ASSETS_READ],
|
|
responses={
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "No user has this ID, or the user has no avatar."
|
|
}
|
|
},
|
|
)
|
|
def get_user_avatar(
|
|
request: Request,
|
|
id: Annotated[int, PathVar(description="The ID of the user.", ge=1)],
|
|
) -> FileResponse:
|
|
"""Serve a user's avatar image. Avatars are public to any authenticated
|
|
user (rendered next to community content, activity, and user lists)."""
|
|
user = db_user_handler.get_user(id)
|
|
if not user or not user.avatar_path:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND, detail="Avatar not found"
|
|
)
|
|
|
|
try:
|
|
file_path = fs_asset_handler.validate_path(user.avatar_path)
|
|
except ValueError:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND, detail="Avatar not found"
|
|
) from None
|
|
|
|
if not file_path.exists() or not file_path.is_file():
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND, detail="Avatar not found"
|
|
)
|
|
|
|
return build_asset_file_response(file_path)
|
|
|
|
|
|
@protected_route(
|
|
router.put,
|
|
"/{id}",
|
|
[Scope.ME_WRITE],
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {
|
|
"description": "A field is invalid or already taken, the current password is missing, or the change would demote the last admin."
|
|
},
|
|
status.HTTP_403_FORBIDDEN: {
|
|
"description": "The caller cannot manage this user, the current password is wrong, or the email is managed by the identity provider."
|
|
},
|
|
status.HTTP_404_NOT_FOUND: {"description": "No user has this ID."},
|
|
},
|
|
)
|
|
async def update_user(
|
|
request: Request,
|
|
id: Annotated[int, PathVar(description="The ID of the user.")],
|
|
form_data: Annotated[UserForm, Form()],
|
|
) -> UserSchema:
|
|
"""Update a user. Changing your own username, password or email needs your current password."""
|
|
|
|
db_user = db_user_handler.get_user(id)
|
|
if not db_user:
|
|
msg = f"Username with id {id} not found"
|
|
log.error(msg)
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=msg)
|
|
|
|
_assert_can_manage_user(request, db_user)
|
|
|
|
email = await _submitted_value(request, "email", form_data.email)
|
|
ra_username = await _submitted_value(request, "ra_username", form_data.ra_username)
|
|
|
|
# Usernames and emails match case-insensitively, so a case-only edit is no change.
|
|
new_username = (
|
|
form_data.username
|
|
if form_data.username and form_data.username.lower() != db_user.username.lower()
|
|
else None
|
|
)
|
|
new_email = (
|
|
email
|
|
if email is not None and email.lower() != (db_user.email or "").lower()
|
|
else None
|
|
)
|
|
|
|
if (
|
|
db_user.id == request.user.id
|
|
and new_email is not None
|
|
and db_user.email_managed_by_oidc
|
|
):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="Your email is managed by your identity provider",
|
|
)
|
|
|
|
# Login is by username, so renaming locks the owner out as surely as a new password.
|
|
if db_user.id == request.user.id and (
|
|
new_username or form_data.password or new_email is not None
|
|
):
|
|
await _verify_account_holder(request, db_user, form_data.current_password)
|
|
|
|
cleaned_data: dict[str, Any] = {}
|
|
|
|
if new_username:
|
|
try:
|
|
validate_username(new_username)
|
|
except ValidationError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=exc.message,
|
|
) from exc
|
|
|
|
if db_user_handler.get_user_by_username(new_username):
|
|
msg = f"Username {new_username} already exists"
|
|
log.error(msg)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=msg,
|
|
)
|
|
|
|
cleaned_data["username"] = new_username.lower()
|
|
|
|
if form_data.password:
|
|
try:
|
|
validate_password(form_data.password)
|
|
except ValidationError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=exc.message,
|
|
) from exc
|
|
cleaned_data["hashed_password"] = await asyncio.to_thread(
|
|
auth_handler.get_password_hash, form_data.password
|
|
)
|
|
|
|
if new_email is not None:
|
|
try:
|
|
validate_email(new_email)
|
|
except ValidationError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=exc.message,
|
|
) from exc
|
|
|
|
if new_email and db_user_handler.get_user_by_email(new_email):
|
|
msg = f"User with email {new_email} already exists"
|
|
log.error(msg)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=msg,
|
|
)
|
|
|
|
cleaned_data["email"] = new_email.lower() or None
|
|
|
|
# You can't change your own role
|
|
if form_data.role and request.user.id != id:
|
|
cleaned_data["role"] = Role.coerce(form_data.role)
|
|
assert_admin_for_admin(
|
|
request,
|
|
cleaned_data["role"],
|
|
"Only an administrator can grant the admin role",
|
|
)
|
|
|
|
# You can't disable yourself
|
|
if form_data.enabled is not None and request.user.id != id:
|
|
cleaned_data["enabled"] = form_data.enabled
|
|
|
|
# The synced progression belongs to the previously linked profile.
|
|
if ra_username:
|
|
cleaned_data["ra_username"] = ra_username
|
|
if ra_username != db_user.ra_username:
|
|
cleaned_data["ra_progression"] = {}
|
|
elif ra_username == "" and db_user.ra_username:
|
|
cleaned_data["ra_username"] = None
|
|
cleaned_data["ra_progression"] = {}
|
|
|
|
if form_data.ui_settings is not None:
|
|
try:
|
|
ui_settings = json.loads(form_data.ui_settings)
|
|
if not isinstance(ui_settings, dict):
|
|
msg = f"Invalid ui_settings JSON: {ui_settings}"
|
|
log.error(msg)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=msg,
|
|
)
|
|
cleaned_data["ui_settings"] = ui_settings
|
|
except (json.JSONDecodeError, ValueError) as exc:
|
|
msg = f"Invalid ui_settings JSON: {str(exc)}"
|
|
log.error(msg)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=msg,
|
|
) from exc
|
|
|
|
if form_data.avatar is not None and form_data.avatar.filename is not None:
|
|
safe_extension = validate_image_upload(form_data.avatar, label="Avatar")
|
|
|
|
user_avatar_path = fs_asset_handler.build_avatar_path(user=db_user)
|
|
file_name = f"avatar.{safe_extension}"
|
|
|
|
await fs_asset_handler.write_file(
|
|
file=form_data.avatar.file, path=user_avatar_path, filename=file_name
|
|
)
|
|
file_location = f"{user_avatar_path}/{file_name}"
|
|
cleaned_data["avatar_path"] = file_location
|
|
|
|
if cleaned_data:
|
|
# Sessions are keyed by username, so the old one is what identifies
|
|
# them once the update has renamed the account.
|
|
previous_username = db_user.username
|
|
creds_updated = cleaned_data.get("username") or cleaned_data.get(
|
|
"hashed_password"
|
|
)
|
|
|
|
try:
|
|
await auth_handler.apply_user_update(
|
|
id,
|
|
cleaned_data,
|
|
revoke_sessions_for=previous_username if creds_updated else None,
|
|
keep_an_admin=True,
|
|
)
|
|
except LastAdminError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="You cannot demote the last admin user",
|
|
) from exc
|
|
|
|
if "avatar_path" in cleaned_data:
|
|
await discard_oidc_avatar(db_user.avatar_path)
|
|
|
|
if creds_updated and request.user.id == id:
|
|
request.session.clear()
|
|
|
|
# A role change alters the user's effective permissions; tell their UI.
|
|
if "role" in cleaned_data:
|
|
await emit_permissions_changed(id)
|
|
if cleaned_data["role"] != db_user.role:
|
|
await notify(
|
|
id,
|
|
NotificationKind.ROLE_CHANGED,
|
|
NotificationLevel.INFO,
|
|
{"role": cleaned_data["role"]},
|
|
actor_id=request.user.id,
|
|
)
|
|
|
|
if cleaned_data.get("enabled") is False:
|
|
await close_client_token_sockets(
|
|
db_client_token_handler.get_token_ids_by_users([id])
|
|
)
|
|
|
|
before = db_user
|
|
db_user = db_user_handler.get_user(id)
|
|
if not db_user:
|
|
msg = f"Username with id {id} not found"
|
|
log.error(msg)
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=msg)
|
|
_record_user_edit(request, before, db_user, cleaned_data)
|
|
|
|
return UserSchema.model_validate(db_user)
|
|
|
|
|
|
@protected_route(
|
|
router.delete,
|
|
"/{id}",
|
|
[Scope.USERS_WRITE],
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {
|
|
"description": "The user is the caller, or the last admin."
|
|
},
|
|
status.HTTP_403_FORBIDDEN: {
|
|
"description": "The user is an admin, and the caller is not one."
|
|
},
|
|
status.HTTP_404_NOT_FOUND: {"description": "No user has this ID."},
|
|
},
|
|
)
|
|
async def delete_user(
|
|
request: Request,
|
|
id: Annotated[int, PathVar(description="The ID of the user.", ge=1)],
|
|
) -> None:
|
|
"""Delete a user by ID."""
|
|
|
|
user = db_user_handler.get_user(id)
|
|
if not user:
|
|
raise HTTPException(status_code=404, detail="User not found")
|
|
|
|
# You can't delete the user you're logged in as
|
|
if request.user.id == id:
|
|
raise HTTPException(status_code=400, detail="You cannot delete yourself")
|
|
|
|
_assert_can_manage_user(request, user)
|
|
|
|
token_ids = db_client_token_handler.get_token_ids_by_users([id])
|
|
device_ids = [device.id for device in db_device_handler.get_devices(user_id=id)]
|
|
try:
|
|
db_user_handler.delete_user(id, keep_an_admin=True)
|
|
except LastAdminError as exc:
|
|
raise HTTPException(
|
|
status_code=400, detail="You cannot delete the last admin user"
|
|
) from exc
|
|
await close_client_token_sockets(token_ids)
|
|
# Keyed by username, so they would otherwise pass for whoever takes it next.
|
|
await auth_handler.revoke_committed_credentials(user.username)
|
|
for device_id in device_ids:
|
|
await device_install_handler.discard_for_device(device_id)
|
|
record(
|
|
AuditAction.USER_DELETE,
|
|
request,
|
|
AuditTarget.of_user(user),
|
|
{"role": user.role},
|
|
)
|
|
|
|
# Remove the user's folder
|
|
user_avatar_path = fs_asset_handler.build_avatar_path(user=user)
|
|
try:
|
|
await fs_asset_handler.remove_directory(user_avatar_path)
|
|
except FileNotFoundError:
|
|
log.warning(f"Couldn't find avatar directory to delete for {user.username}")
|
|
|
|
|
|
@protected_route(
|
|
router.post,
|
|
"/{id}/ra/refresh",
|
|
[Scope.ME_WRITE],
|
|
status_code=status.HTTP_202_ACCEPTED,
|
|
summary="Refresh RetroAchievements",
|
|
responses={
|
|
status.HTTP_403_FORBIDDEN: {
|
|
"description": "The user is not the caller, and the caller cannot manage this user."
|
|
},
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "No user has this ID, or the user has no RetroAchievements username."
|
|
},
|
|
status.HTTP_503_SERVICE_UNAVAILABLE: {
|
|
"description": "The sync job could not be added to the task queue."
|
|
},
|
|
},
|
|
)
|
|
async def refresh_retro_achievements(
|
|
request: Request,
|
|
id: Annotated[int, PathVar(description="The ID of the user.", ge=1)],
|
|
incremental: Annotated[
|
|
bool,
|
|
Body(
|
|
description="Whether to only retrieve RetroAchievements progression incrementally.",
|
|
embed=True,
|
|
),
|
|
] = False,
|
|
) -> None:
|
|
"""Queue a refresh of a user's RetroAchievements progression; `ra:synced` reports when it ends."""
|
|
user = db_user_handler.get_user(id)
|
|
if user:
|
|
_assert_can_manage_user(request, user)
|
|
if not user or not user.ra_username:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="User does not have a RetroAchievements username set",
|
|
)
|
|
|
|
if not queue_ra_progress_sync(id, refresh_all=not incremental):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
detail="Couldn't queue the RetroAchievements sync, try again later",
|
|
)
|
|
return None
|