Source code for app.domain.accounts.controllers._profile

"""User profile SecureController."""

from typing import Annotated, Any, ClassVar, cast

from litestar import Request, Response, delete, get, patch, post
from litestar.di import NamedDependency, Provide
from litestar.enums import RequestEncodingType
from litestar.exceptions import NotFoundException, ServiceUnavailableException
from litestar.params import Body
from litestar_security import (
    AuthenticationPolicy,
    CurrentUser,
    SecureController,
    SecurityContext,
    SecurityPlugin,
    any_of,
    required,
)

from app.db import models as m
from app.domain.accounts.deps import provide_users_service
from app.domain.accounts.schemas import AvatarUpload, PasswordConfirmation, PasswordUpdate, ProfileUpdate, User
from app.domain.accounts.security import confirm_authentication
from app.domain.accounts.services import AVATAR_MAX_BYTES, AVATAR_UNAVAILABLE_DETAIL, UserService
from app.lib.schema import Message
from app.lib.storage import storage_available

AVATAR_REQUEST_MAX_BODY_SIZE = AVATAR_MAX_BYTES + 64 * 1024
"""Request body limit for avatar uploads: the image limit plus room for the multipart envelope."""
_NO_AVATAR_DETAIL = "No avatar is set."


[docs] class ProfileController(SecureController): """Handles self-service profile inspection, updates, password rotation, and account deletion.""" path = "/api/me" tags = ["Access"] auth: ClassVar[AuthenticationPolicy] = required("session") dependencies = { "users_service": Provide(provide_users_service), } @get( operation_id="AccountProfile", path="", summary="User Profile", description="Return the authenticated user's profile.", opt={"auth": any_of("session", "api-key")}, mcp_resource="user_profile", ) async def get_profile( self, users_service: UserService, current_user: CurrentUser[m.User], security_context: NamedDependency[SecurityContext], ) -> User: """Return the authenticated user's profile.""" _ = security_context user = await users_service.get(current_user.id) return users_service.to_schema(user, schema_type=User) @patch(operation_id="AccountProfileUpdate", path="") async def update_profile( self, current_user: CurrentUser[m.User], data: ProfileUpdate, users_service: UserService, ) -> User: """Update editable profile attributes for the authenticated user. Returns: Updated user profile payload. """ user = await users_service.update(data.to_dict(), item_id=current_user.id, auto_commit=True) return users_service.to_schema(user, schema_type=User) @patch(operation_id="AccountPasswordUpdate", path="/password") async def update_password( self, request: Request[Any, Any, Any], current_user: CurrentUser[m.User], data: PasswordUpdate, users_service: UserService, ) -> Message: """Replace the authenticated user's password after verifying the current one. Returns: Confirmation message for the password change. """ await confirm_authentication(request, current_user, data.current_password) await users_service.update_password( current_user, current_password=data.current_password, new_password=data.new_password, ) return Message(message="Your password was successfully modified.") @delete(operation_id="AccountDelete", path="") async def remove_account( self, request: Request[Any, Any, Any], current_user: CurrentUser[m.User], users_service: UserService, data: PasswordConfirmation | None = None, ) -> None: """Delete the authenticated user's account after a recent sign-in or password confirmation.""" await confirm_authentication(request, current_user, data.current_password if data else None) plugin = cast("SecurityPlugin[m.User]", request.app.plugins.get(SecurityPlugin)) if plugin.config.local_auth is not None and plugin.config.local_auth.session_auth is not None: await plugin.config.local_auth.session_auth.logout(request) _ = await users_service.delete(current_user.id, auto_commit=True) @post( operation_id="AccountAvatarUpload", path="/avatar", summary="Upload Avatar", description="Upload or replace the authenticated user's profile picture (JPEG, PNG, GIF, or WebP, up to 5 MB).", request_max_body_size=AVATAR_REQUEST_MAX_BODY_SIZE, ) async def upload_avatar( self, current_user: CurrentUser[m.User], users_service: UserService, data: Annotated[AvatarUpload, Body(media_type=RequestEncodingType.MULTI_PART)], ) -> User: """Store the uploaded image as the authenticated user's avatar. Returns: Updated user profile payload. Raises: ServiceUnavailableException: If object storage is not configured. """ if not storage_available(): raise ServiceUnavailableException(detail=AVATAR_UNAVAILABLE_DETAIL) user = await users_service.get(current_user.id) user = await users_service.upload_avatar(user, await data.file.read()) return users_service.to_schema(user, schema_type=User) @get( operation_id="AccountAvatar", path="/avatar", summary="Get Avatar", description="Return the authenticated user's profile picture.", media_type="application/octet-stream", ) async def get_avatar(self, current_user: CurrentUser[m.User], users_service: UserService) -> Response[bytes]: """Return the authenticated user's avatar image bytes with the stored content type. Returns: Image response that browsers revalidate on every use and never sniff. Raises: ServiceUnavailableException: If object storage is not configured. NotFoundException: If no avatar is set or its stored image is missing. """ if not storage_available(): raise ServiceUnavailableException(detail=AVATAR_UNAVAILABLE_DETAIL) user = await users_service.get(current_user.id) if user.avatar is None: raise NotFoundException(detail=_NO_AVATAR_DETAIL) try: content = await user.avatar.get_content_async() except FileNotFoundError as exc: raise NotFoundException(detail=_NO_AVATAR_DETAIL) from exc return Response( content=content, media_type=user.avatar.content_type, headers={ "Cache-Control": "private, no-cache", "X-Content-Type-Options": "nosniff", "Content-Disposition": "inline", }, ) @delete( operation_id="AccountAvatarDelete", path="/avatar", summary="Delete Avatar", description="Remove the authenticated user's profile picture.", ) async def delete_avatar(self, current_user: CurrentUser[m.User], users_service: UserService) -> None: """Remove the authenticated user's avatar and its stored image. Raises: ServiceUnavailableException: If object storage is not configured. NotFoundException: If no avatar is set. """ if not storage_available(): raise ServiceUnavailableException(detail=AVATAR_UNAVAILABLE_DETAIL) user = await users_service.get(current_user.id) if user.avatar is None: raise NotFoundException(detail=_NO_AVATAR_DETAIL) await users_service.remove_avatar(user)