Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

UN-4289 [FEAT] Let users edit their profile name, language and photo (#2362)

Athul54508bd64cc1
diff --git a/backend/account_v2/authentication_controller.py b/backend/account_v2/authentication_controller.py
index bf204321c..ebf4b73dc 100644
--- a/backend/account_v2/authentication_controller.py
+++ b/backend/account_v2/authentication_controller.py
@@ -55,6 +55,7 @@ from account_v2.serializer import (
SetOrganizationsResponseSerializer,
)
from account_v2.user import UserService
+from account_v2.user_profile import with_profile_overrides
logger = logging.getLogger(__name__)
@@ -247,7 +248,9 @@ class AuthenticationController:
user.email,
)
- user_info: UserInfo | None = self.get_user_info(request)
+ user_info: UserInfo | None = self.get_user_info(
+ request, organization_id=organization_id
+ )
serialized_user_info = SetOrganizationsResponseSerializer(user_info).data
organization_info = OrganizationSerializer(organization).data
response: Response = Response(
@@ -273,8 +276,25 @@ class AuthenticationController:
return response
return Response(status=status.HTTP_403_FORBIDDEN)
- def get_user_info(self, request: Request) -> UserInfo | None:
- return self.auth_service.get_user_info(request)
+ def get_user_info(
+ self, request: Request, organization_id: str | None = None
+ ) -> UserInfo | None:
+ """The auth service's user info, with the locally edited name and photo.
+
+ Every auth plugin's result passes through here, so the edits show in the
+ profile and set-organization responses whichever provider signed the
+ user in. `organization_id` scopes the photo URL; it defaults to the
+ session's organization.
+ """
+ user_info = self.auth_service.get_user_info(request)
+ user = getattr(request, "user", None)
+ if not user_info or not isinstance(user, User):
+ return user_info
+ return with_profile_overrides(
+ user_info,
+ user,
+ organization_id or UserSessionUtils.get_organization_id(request),
+ )
def is_admin_by_role(self, role: str) -> bool:
"""Check the role is act as admin in the context of authentication
diff --git a/backend/account_v2/migrations/0010_user_profile_fields.py b/backend/account_v2/migrations/0010_user_profile_fields.py
new file mode 100644
index 000000000..f2a106caf
--- /dev/null
+++ b/backend/account_v2/migrations/0010_user_profile_fields.py
@@ -0,0 +1,53 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("account_v2", "0009_user_product_preference"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="user",
+ name="profile_display_name",
+ field=models.CharField(
+ blank=True,
+ db_comment=(
+ "Name the user set on their profile; empty means the identity "
+ "provider's name is shown"
+ ),
+ default="",
+ max_length=64,
+ ),
+ ),
+ migrations.AddField(
+ model_name="user",
+ name="language",
+ field=models.CharField(
+ db_comment="Preferred UI language (BCP 47)",
+ default="en-US",
+ max_length=16,
+ ),
+ ),
+ migrations.AddField(
+ model_name="user",
+ name="profile_photo_updated_at",
+ field=models.DateTimeField(
+ blank=True,
+ db_comment="When the profile photo was stored; null when there is none",
+ null=True,
+ ),
+ ),
+ # Database defaults too, so pods still on the old code can create users
+ # while a deploy rolls out.
+ migrations.RunSQL(
+ sql=[
+ """ALTER TABLE "user" ALTER COLUMN "profile_display_name" SET DEFAULT ''""",
+ """ALTER TABLE "user" ALTER COLUMN "language" SET DEFAULT 'en-US'""",
+ ],
+ reverse_sql=[
+ """ALTER TABLE "user" ALTER COLUMN "profile_display_name" DROP DEFAULT""",
+ """ALTER TABLE "user" ALTER COLUMN "language" DROP DEFAULT""",
+ ],
+ ),
+ ]
diff --git a/backend/account_v2/models.py b/backend/account_v2/models.py
index 36c3ae954..e2b8e8f4a 100644
--- a/backend/account_v2/models.py
+++ b/backend/account_v2/models.py
@@ -153,6 +153,21 @@ class User(AbstractUser):
default=False,
db_comment="True for service accounts (e.g. platform API key bearer auth sessions)",
)
+ profile_display_name = models.CharField(
+ max_length=NAME_SIZE,
+ blank=True,
+ default="",
+ db_comment="Name the user set on their profile; empty means the identity "
+ "provider's name is shown",
+ )
+ language = models.CharField(
+ max_length=16, default="en-US", db_comment="Preferred UI language (BCP 47)"
+ )
+ profile_photo_updated_at = models.DateTimeField(
+ null=True,
+ blank=True,
+ db_comment="When the profile photo was stored; null when there is none",
+ )
def __str__(self): # type: ignore
return f"User({self.id}, email: {self.email}, userId: {self.user_id})"
diff --git a/backend/account_v2/serializer.py b/backend/account_v2/serializer.py
index 6c3acfb98..fae20fa06 100644
--- a/backend/account_v2/serializer.py
+++ b/backend/account_v2/serializer.py
@@ -92,7 +92,8 @@ class SetOrganizationsResponseSerializer(serializers.Serializer):
email = serializers.CharField()
name = serializers.CharField()
display_name = serializers.CharField()
- family_name = serializers.CharField()
+ # Null when the user has set a name on their profile.
+ family_name = serializers.CharField(allow_null=True)
picture = serializers.CharField()
# Add more fields as needed
diff --git a/backend/account_v2/test_user_profile.py b/backend/account_v2/test_user_profile.py
new file mode 100644
index 000000000..23f43215e
--- /dev/null
+++ b/backend/account_v2/test_user_profile.py
@@ -0,0 +1,389 @@
+"""Tests for the locally edited profile: name, language and photo."""
+
+import dataclasses
+import os
+import secrets
+import struct
+import tempfile
+import zlib
+from dataclasses import dataclass
+from unittest.mock import patch
+
+from django.conf import settings
+from django.core.exceptions import ImproperlyConfigured
+from django.test import TestCase
+
+from account_v2 import user_profile
+from account_v2.dto import UserInfo
+from account_v2.models import User
+
+
+def png_bytes() -> bytes:
+ """A valid 1x1 PNG."""
+
+ def chunk(kind: bytes, data: bytes) -> bytes:
+ body = kind + data
+ return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body))
+
+ ihdr = struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0)
+ idat = zlib.compress(b"\x00\xff\x00\x00")
+ return (
+ b"\x89PNG\r\n\x1a\n"
+ + chunk(b"IHDR", ihdr)
+ + chunk(b"IDAT", idat)
+ + chunk(b"IEND", b"")
+ )
+
+
+JPEG = b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00" + (
+ b"\x00" * 64
+)
+GIF = b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff!\xf9\x04" + (
+ b"\x00" * 32
+)
+
+
+def make_user(email: str = "[email protected]") -> User:
+ return User.objects.create_user(
+ username=email, email=email, password=secrets.token_urlsafe()
+ )
+
+
+class LocalStorageMixin:
+ """Points the permanent storage at a temp dir for the test."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.tmp = tempfile.TemporaryDirectory()
+ env = patch.dict(
+ "os.environ",
+ {
+ "PERMANENT_REMOTE_STORAGE": '{"provider": "local"}',
+ "REMOTE_USER_PROFILE_PHOTO_PATH": self.tmp.name,
+ },
+ )
+ env.start()
+ self.addCleanup(env.stop)
+ self.addCleanup(self.tmp.cleanup)
+
+
+class PhotoStorageTests(LocalStorageMixin, TestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.user = make_user()
+
+ def test_no_photo_reads_none(self) -> None:
+ self.assertIsNone(user_profile.read_photo(self.user))
+
+ def test_png_round_trip(self) -> None:
+ user_profile.save_photo(self.user, png_bytes())
+ self.user.refresh_from_db()
+ self.assertIsNotNone(self.user.profile_photo_updated_at)
+ self.assertEqual(user_profile.read_photo(self.user), (png_bytes(), "image/png"))
+
+ def test_jpeg_round_trip(self) -> None:
+ user_profile.save_photo(self.user, JPEG)
+ self.assertEqual(user_profile.read_photo(self.user), (JPEG, "image/jpeg"))
+
+ def test_new_photo_replaces_old(self) -> None:
+ user_profile.save_photo(self.user, JPEG)
+ user_profile.save_photo(self.user, png_bytes())
+ self.assertEqual(user_profile.read_photo(self.user)[1], "image/png")
+
+ def test_photos_are_per_user(self) -> None:
+ other = make_user("[email protected]")
+ user_profile.save_photo(self.user, png_bytes())
+ user_profile.save_photo(other, JPEG)
+ self.assertEqual(user_profile.read_photo(self.user)[1], "image/png")
+ self.assertEqual(user_profile.read_photo(other)[1], "image/jpeg")
+
+ def test_delete_photo(self) -> None:
+ user_profile.save_photo(self.user, png_bytes())
+ user_profile.delete_photo(self.user)
+ self.user.refresh_from_db()
+ self.assertIsNone(self.user.profile_photo_updated_at)
+ self.assertIsNone(user_profile.read_photo(self.user))
+
+ def test_storage_failure_on_delete_keeps_the_photo_recorded(self) -> None:
+ user_profile.save_photo(self.user, png_bytes())
+ with patch(
+ "unstract.sdk1.file_storage.impl.FileStorage.rm_exact", side_effect=OSError
+ ):
+ with self.assertRaises(OSError):
+ user_profile.delete_photo(self.user)
+ self.user.refresh_from_db()
+ self.assertIsNotNone(self.user.profile_photo_updated_at)
+ user_profile.delete_photo(self.user) # a retry removes it
+ self.assertIsNone(user_profile.read_photo(self.user))
+
+ def test_delete_does_not_use_the_bulk_delete_minio_rejects(self) -> None:
+ # Object-store `rm` sends a bulk delete, which MinIO can refuse with
+ # MissingContentMD5; the SDK only falls back for recursive deletes.
+ user_profile.save_photo(self.user, png_bytes())
+ with patch(
+ "unstract.sdk1.file_storage.impl.FileStorage.rm",
+ side_effect=Exception("MissingContentMD5"),
+ ):
+ user_profile.delete_photo(self.user)
+ self.assertIsNone(user_profile.read_photo(self.user))
+
+ def test_delete_when_object_already_gone(self) -> None:
+ user_profile.save_photo(self.user, png_bytes())
+ os.remove(user_profile.photo_path(self.user))
+ with self.assertLogs("account_v2.user_profile", "WARNING"):
+ user_profile.delete_photo(self.user)
+ self.user.refresh_from_db()
+ self.assertIsNone(self.user.profile_photo_updated_at)
+
+ def test_delete_without_photo_is_a_no_op(self) -> None:
+ user_profile.delete_photo(self.user)
+ self.assertIsNone(user_profile.read_photo(self.user))
+
+ def test_missing_object_is_logged_and_not_served(self) -> None:
+ user_profile.save_photo(self.user, png_bytes())
+ os.remove(user_profile.photo_path(self.user))
+ with self.assertLogs("account_v2.user_profile", "ERROR"):
+ self.assertIsNone(user_profile.read_photo(self.user))
+
+ def test_empty_read_is_logged_and_not_served(self) -> None:
+ # The SDK's stale-cache retry can return None for a file that exists.
+ user_profile.save_photo(self.user, png_bytes())
+ for empty in (None, b""):
+ with (
+ self.subTest(empty=empty),
+ patch(
+ "unstract.sdk1.file_storage.impl.FileStorage.read",
+ return_value=empty,
+ ),
+ self.assertLogs("account_v2.user_profile", "ERROR"),
+ ):
+ self.assertIsNone(user_profile.read_photo(self.user))
+
+ def test_failed_write_records_no_photo(self) -> None:
+ with patch(
+ "unstract.sdk1.file_storage.impl.FileStorage.write", side_effect=OSError
+ ):
+ with self.assertRaises(OSError):
+ user_profile.save_photo(self.user, png_bytes())
+ self.user.refresh_from_db()
+ self.assertIsNone(self.user.profile_photo_updated_at)
+
+ def test_delete_clears_timestamp_even_when_in_memory_copy_is_stale(self) -> None:
+ user_profile.save_photo(self.user, png_bytes())
+ stale = User.objects.get(pk=self.user.pk)
+ stale.profile_photo_updated_at = None
+ user_profile.delete_photo(stale)
+ self.user.refresh_from_db()
+ self.assertIsNone(self.user.profile_photo_updated_at)
+
+ def test_stored_bytes_that_are_not_an_image_are_not_served(self) -> None:
+ user_profile.save_photo(self.user, png_bytes())
+ path = user_profile.photo_path(self.user)
+ with open(path, "wb") as f:
+ f.write(GIF)
+ with self.assertLogs("account_v2.user_profile", "WARNING"):
+ self.assertIsNone(user_profile.read_photo(self.user))
+
+
+class PhotoBasePathTests(TestCase):
+ def test_explicit_env_wins(self) -> None:
+ with patch.dict(
+ "os.environ",
+ {
+ "REMOTE_USER_PROFILE_PHOTO_PATH": "bucket/photos",
+ "REMOTE_PROMPT_STUDIO_FILE_PATH": "other/prompt-studio-data",
+ },
+ ):
+ self.assertEqual(user_profile.photo_base_path(), "bucket/photos")
+
+ def test_defaults_beside_prompt_studio_files(self) -> None:
+ with patch.dict(
+ "os.environ",
+ {
+ "REMOTE_USER_PROFILE_PHOTO_PATH": "",
+ "REMOTE_PROMPT_STUDIO_FILE_PATH": "bucket-x/prompt-studio-data",
+ },
+ ):
+ self.assertEqual(
+ user_profile.photo_base_path(), "bucket-x/user-profile-photos"
+ )
+
+ def test_prompt_studio_path_is_stripped(self) -> None:
+ with patch.dict(
+ "os.environ",
+ {
+ "REMOTE_USER_PROFILE_PHOTO_PATH": "",
+ "REMOTE_PROMPT_STUDIO_FILE_PATH": " bucket-x/prompt-studio-data ",
+ },
+ ):
+ self.assertEqual(
+ user_profile.photo_base_path(), "bucket-x/user-profile-photos"
+ )
+
+ def test_prompt_studio_path_without_a_bucket_is_a_config_error(self) -> None:
+ # A sibling of a bare name would be a bucket of its own.
+ for bare in ("prompt-studio-data", "/prompt-studio-data"):
+ with (
+ self.subTest(bare=bare),
+ patch.dict(
+ "os.environ",
+ {
+ "REMOTE_USER_PROFILE_PHOTO_PATH": "",
+ "REMOTE_PROMPT_STUDIO_FILE_PATH": bare,
+ },
+ ),
+ ):
+ with self.assertRaises(ImproperlyConfigured):
+ user_profile.photo_base_path()
+
+ def test_unset_paths_are_a_config_error(self) -> None:
+ for blank in ("", " "):
+ with (
+ self.subTest(blank=blank),
+ patch.dict(
+ "os.environ",
+ {
+ "REMOTE_USER_PROFILE_PHOTO_PATH": blank,
+ "REMOTE_PROMPT_STUDIO_FILE_PATH": blank,
+ },
+ ),
+ ):
+ with self.assertRaises(ImproperlyConfigured):
+ user_profile.photo_base_path()
+
+
+class DeleteWithoutStorageTests(TestCase):
+ def test_delete_without_photo_needs_no_storage(self) -> None:
+ user = make_user()
+ with patch.object(user_profile, "_storage") as storage:
+ user_profile.delete_photo(user)
+ storage.assert_not_called()
+
+
+class PhotoUrlTests(TestCase):
+ def setUp(self) -> None:
+ self.user = make_user()
+
+ def test_none_without_photo(self) -> None:
+ self.assertIsNone(user_profile.photo_url(self.user, "org-a"))
+
+ def test_none_without_organization(self) -> None:
+ self.user.profile_photo_updated_at = user_profile.timezone.now()
+ self.assertIsNone(user_profile.photo_url(self.user, None))
+
+ def test_org_scoped_and_versioned(self) -> None:
+ self.user.profile_photo_updated_at = user_profile.timezone.now()
+ version = int(self.user.profile_photo_updated_at.timestamp())
+ self.assertEqual(
+ user_profile.photo_url(self.user, "org-a"),
+ f"/{settings.TENANT_SUBFOLDER_PREFIX}/org-a/users/profile/photo/"
+ f"?v={version}",
+ )
+
+
+@dataclass
+class PluginUserInfo(UserInfo):
+ """Stand-in for an auth plugin's own UserInfo with an extra field."""
+
+ email_verified: bool = False
+
+
+class ProfileOverrideTests(TestCase):
+ def setUp(self) -> None:
+ self.user = make_user()
+ self.info = UserInfo(
+ user_id="auth0|1",
+ name="Provider",
+ display_name="Provider Name",
+ picture="https://provider/pic.png",
+ )
+
+ def test_no_edits_keeps_provider_values(self) -> None:
+ result = user_profile.with_profile_overrides(self.info, self.user, "org-a")
+ self.assertEqual(result, self.info)
+
+ def test_edited_name_replaces_the_provider_name(self) -> None:
+ self.user.profile_display_name = "Edited"
+ info = dataclasses.replace(self.info, family_name="Smith")
+ result = user_profile.with_profile_overrides(info, self.user, "org-a")
+ self.assertEqual(
+ (result.name, result.display_name, result.family_name),
+ ("Edited", "Edited", None),
+ )
+ self.assertEqual(self.info.name, "Provider")
+
+ def test_photo_replaces_picture(self) -> None:
+ self.user.profile_photo_updated_at = user_profile.timezone.now()
+ result = user_profile.with_profile_overrides(self.info, self.user, "org-a")
+ self.assertEqual(result.picture, user_profile.photo_url(self.user, "org-a"))
+
+ def test_keeps_plugin_fields(self) -> None:
+ info = PluginUserInfo(
+ email="[email protected]", user_id="auth0|1", email_verified=True
+ )
+ self.user.profile_display_name = "Edited"
+ result = user_profile.with_profile_overrides(info, self.user, "org-a")
+ self.assertIsInstance(result, PluginUserInfo)
+ self.assertTrue(result.email_verified)
+
+
+class LanguageDefaultTests(TestCase):
+ def test_new_user_language_is_en_us(self) -> None:
+ self.assertEqual(make_user().language, "en-US")
+
+
+class ControllerOrganizationTests(TestCase):
+ def setUp(self) -> None:
+ patcher = patch(
+ "account_v2.authentication_controller.AuthenticationPluginRegistry"
+ ".is_plugin_available",
+ return_value=False,
+ )
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def test_photo_url_uses_the_organization_passed_in(self) -> None:
+ from types import SimpleNamespace
+
+ from account_v2.authentication_controller import AuthenticationController
+
+ user = make_user()
+ user.profile_photo_updated_at = user_profile.timezone.now()
+ info = AuthenticationController().get_user_info(
+ SimpleNamespace(user=user), organization_id="org-b"
+ )
+ self.assertEqual(info.picture, user_profile.photo_url(user, "org-b"))
+
+ def test_info_passes_through_without_a_signed_in_user(self) -> None:
+ from types import SimpleNamespace
+
+ from django.contrib.auth.models import AnonymousUser
+
+ from account_v2.authentication_controller import AuthenticationController
+
+ info = UserInfo(email="[email protected]", user_id="x", name="Provider")
+ with patch(
+ "account_v2.authentication_controller.AuthenticationService.get_user_info",
+ return_value=info,
+ ):
+ result = AuthenticationController().get_user_info(
+ SimpleNamespace(user=AnonymousUser()), organization_id="org-a"
+ )
+ self.assertIs(result, info)
+
+ def test_no_info_from_the_auth_service_stays_none(self) -> None:
+ from types import SimpleNamespace
+
+ from account_v2.authentication_controller import AuthenticationController
+
+ user = make_user()
+ user.profile_display_name = "Edited"
+ with patch(
+ "account_v2.authentication_controller.AuthenticationService.get_user_info",
+ return_value=None,
+ ):
+ result = AuthenticationController().get_user_info(
+ SimpleNamespace(user=user), organization_id="org-a"
+ )
+ self.assertIsNone(result)
diff --git a/backend/account_v2/user_profile.py b/backend/account_v2/user_profile.py
new file mode 100644
index 000000000..0f9e93d42
--- /dev/null
+++ b/backend/account_v2/user_profile.py
@@ -0,0 +1,141 @@
+"""The profile a user edits locally: name, language and photo.
+
+The edited name and language live on the User row and the photo in the
+permanent file storage. None of them is written to the identity provider,
+and the edited name and photo are shown in place of the provider's.
+"""
+
+import dataclasses
+import logging
+import os
+from pathlib import PurePosixPath
+from typing import TypeVar
+
+import magic
+from django.conf import settings
+from django.core.exceptions import ImproperlyConfigured
+from django.utils import timezone
+from utils.file_storage.constants import FileStorageConstants, FileStorageKeys
+
+from account_v2.dto import UserInfo
+from account_v2.models import User
+from unstract.sdk1.file_storage.constants import StorageType
+from unstract.sdk1.file_storage.env_helper import EnvHelper
+
+PHOTO_TYPES = ("image/png", "image/jpeg")
+MAX_PHOTO_BYTES = 2 * 1024 * 1024
+LANGUAGES = ("en-US",)
+PHOTO_PATH_ENV = "REMOTE_USER_PROFILE_PHOTO_PATH"
+
+T = TypeVar("T", bound=UserInfo)
+
+logger = logging.getLogger(__name__)
+
+
+def photo_base_path() -> str:
+ """Where photos are kept: the env if set, else beside Prompt Studio files.
+
+ The default is a sibling of the Prompt Studio path, so it shares that
+ path's bucket. A Prompt Studio path with no bucket prefix is refused,
+ since its sibling would be a bucket of its own.
+ """
+ explicit = os.environ.get(PHOTO_PATH_ENV, "").strip()
+ if explicit:
+ return explicit
+ prompt_studio_env = FileStorageConstants.REMOTE_PROMPT_STUDIO_FILE_PATH
+ prompt_studio = os.environ.get(prompt_studio_env, "").strip()
+ if not prompt_studio:
+ raise ImproperlyConfigured(
+ f"Set {PHOTO_PATH_ENV} or {prompt_studio_env} to store profile photos."
+ )
+ parent = PurePosixPath(prompt_studio).parent
+ if str(parent) in (".", "/"):
+ raise ImproperlyConfigured(
+ f"Set {PHOTO_PATH_ENV}; {prompt_studio_env} has no bucket prefix."
+ )
+ return str(parent / "user-profile-photos")
+
+
+def photo_path(user: User) -> str:
+ return str(PurePosixPath(photo_base_path()) / str(user.pk) / "photo")
+
+
+def _storage():
+ return EnvHelper.get_storage(
+ storage_type=StorageType.PERMANENT,
+ env_name=FileStorageKeys.PERMANENT_REMOTE_STORAGE,
+ )
+
+
+def save_photo(user: User, data: bytes) -> None:
+ """Store an already validated PNG or JPEG as the user's photo."""
+ fs = _storage()
+ path = photo_path(user)
+ fs.mkdir(str(PurePosixPath(path).parent), create_parents=True)
+ fs.write(path=path, mode="wb", data=data)
+ user.profile_photo_updated_at = timezone.now()
+ user.save(update_fields=["profile_photo_updated_at"])
+
+
+def read_photo(user: User) -> tuple[bytes, str] | None:
+ """The photo bytes and content type, or None when there is no servable photo."""
+ if not user.profile_photo_updated_at:
+ return None
+ path = photo_path(user)
+ try:
+ data = _storage().read(path=path, mode="rb")
+ except FileNotFoundError:
+ logger.error("Profile photo of user %s is missing at %s", user.pk, path)
+ return None
+ if not data:
+ logger.error("Profile photo of user %s read back empty at %s", user.pk, path)
+ return None
+ content_type = magic.from_buffer(data, mime=True)
+ if content_type not in PHOTO_TYPES:
+ logger.warning(
+ "Profile photo of user %s is %s, not served", user.pk, content_type
+ )
+ return None
+ return data, content_type
+
+
+def delete_photo(user: User) -> None:
+ """Remove the object, then the record, so a failed removal can be retried."""
+ recorded = User.objects.filter(
+ pk=user.pk, profile_photo_updated_at__isnull=False
+ ).exists()
+ if recorded: # Without a recorded photo there is no storage to touch.
+ fs, path = _storage(), photo_path(user)
+ # rm_exact passes over a missing object silently.
+ if fs.exists(path):
+ fs.rm_exact(path)
+ else:
+ logger.warning("Profile photo of user %s was already gone", user.pk)
+ User.objects.filter(pk=user.pk).update(profile_photo_updated_at=None)
+ user.profile_photo_updated_at = None
+
+
+def photo_url(user: User, organization_id: str | None) -> str | None:
+ """Org-scoped URL of the photo endpoint, versioned by upload time in seconds."""
+ if not (user.profile_photo_updated_at and organization_id):
+ return None
+ version = int(user.profile_photo_updated_at.timestamp())
+ return (
+ f"/{settings.TENANT_SUBFOLDER_PREFIX}/{organization_id}"
+ f"/users/profile/photo/?v={version}"
+ )
+
+
+def with_profile_overrides(info: T, user: User, organization_id: str | None) -> T:
+ """A copy of the provider's user info with the locally edited values on top."""
+ changes: dict[str, str | None] = {}
+ if user.profile_display_name:
+ # The edited name is the whole name; the provider's surname would
+ # otherwise be appended to it where clients join the two.
+ changes["name"] = user.profile_display_name
+ changes["display_name"] = user.profile_display_name
+ changes["family_name"] = None
+ url = photo_url(user, organization_id)
+ if url:
+ changes["picture"] = url
+ return dataclasses.replace(info, **changes) if changes else info
diff --git a/backend/sample.env b/backend/sample.env
index bee755527..33d4f535b 100644
--- a/backend/sample.env
+++ b/backend/sample.env
@@ -271,6 +271,8 @@ API_FILE_STORAGE_CREDENTIALS='{"provider": "minio", "credentials": {"endpoint_ur
#Remote storage related envs
PERMANENT_REMOTE_STORAGE='{"provider": "minio", "credentials": {"endpoint_url": "http://unstract-minio:9000", "key": "minio", "secret": "minio123"}}'
TEMPORARY_REMOTE_STORAGE='{"provider": "minio", "credentials": {"endpoint_url": "http://unstract-minio:9000", "key": "minio", "secret": "minio123"}}'
+# Profile photos; defaults to a user-profile-photos folder beside the Prompt Studio path
+# REMOTE_USER_PROFILE_PHOTO_PATH=unstract/user-profile-photos
REMOTE_PROMPT_STUDIO_FILE_PATH=unstract/prompt-studio-data
# Storage Provider for Tool registry
diff --git a/backend/tenant_account_v2/ReadMe.md b/backend/tenant_account_v2/ReadMe.md
new file mode 100644
index 000000000..885f36b8e
--- /dev/null
+++ b/backend/tenant_account_v2/ReadMe.md
@@ -0,0 +1,33 @@
+# tenant_account_v2
+
+## Profile contract
+
+The current user's profile. All paths are organization-scoped: `/api/v1/unstract/<org_id>/users/profile/...`. The typed contract is the `@extend_schema` annotation on each view in `users_view.py` (operation ids `user_profile`, `user_profile_update`, `user_profile_photo`, `user_profile_photo_upload`, `user_profile_photo_delete`). It is not part of the published deployment API spec.
+
+| Method and path | Request | Response |
+|---|---|---|
+| GET `users/profile/` | none | `{"user": {...}}`, the fields below |
+| PATCH `users/profile/` | JSON, any of `display_name`, `language` | As GET |
+| GET `users/profile/photo/` | none | The image, `image/png` or `image/jpeg`; 404 when there is none, or when the stored object is missing or is not a PNG or JPEG |
+| POST `users/profile/photo/` | multipart, field `photo` | `{"photo_url": "..."}` |
+| DELETE `users/profile/photo/` | none | 204, also when there was no photo |
+
+### Fields
+
+- `name`, `display_name`: the name the user set on their profile, or the identity provider's when they have not set one.
+- `family_name`: null when the user has set a name, since that name is the whole name; otherwise the provider's.
+- `picture`: `photo_url` when the user has a photo, otherwise the provider's picture (null in OSS).
+- `photo_url`: the org-scoped URL of GET `users/profile/photo/` with a `?v=` version, the upload time in seconds; null when there is no photo.
+- `language`: a BCP 47 tag. `en-US` is the only value accepted until translations exist.
+- The other fields (`id`, `email`, `is_admin`, `role`, the onboarding flags, `organization_name`, `organization_id`) are unchanged.
+
+### Rules
+
+- `display_name` is trimmed and must be 1 to 64 characters. Empty or blank is refused, since the profile page requires a name. Once set, the name can be changed but not cleared back to the provider's.
+- The photo is PNG or JPEG, up to 2 MB. The type is read from the bytes, so the file name does not matter. Anything else is refused.
+- Field errors (400) use the backend's standard shape: `{"type": "validation_error", "errors": [{"code", "detail", "attr"}]}`, with `attr` naming the field. The photo 404 uses the same shape with `type: client_error`. GET and PATCH `users/profile/` answer 404 and 500 with `{"message": ...}`; a PATCH that gets one of these has still saved its change. Storage errors are `{"type": "sdk_error", "error": ...}`, and a missing photo path setting is a 500 `server_error` with `DEBUG` off, as in the cloud and on-prem settings.
+- Service accounts (platform API keys) get 403 on PATCH `users/profile/` and on POST and DELETE `users/profile/photo/`.
+- GET `users/profile/photo/` answers clients that accept only images (`Accept: image/png` or `image/*`) as well as `*/*`; its errors are JSON either way.
+- The edited name and photo are stored by Unstract and never written to the identity provider. They show wherever the backend builds user info through `AuthenticationController.get_user_info`: this endpoint and the set-organization response. Other responses, such as the cloud members list, build user details elsewhere and keep the provider's values.
+- Photos are kept in the permanent file storage (`PERMANENT_REMOTE_STORAGE`) under `REMOTE_USER_PROFILE_PHOTO_PATH`, or, when that is unset, in a `user-profile-photos` folder beside `REMOTE_PROMPT_STUDIO_FILE_PATH`. With both unset, or with a `REMOTE_PROMPT_STUDIO_FILE_PATH` that has no bucket prefix, uploading a photo, or reading or deleting a recorded one, fails with a configuration error.
+- The backend's `CacheControlMiddleware` sets `Cache-Control: no-store` on the photo as on other API responses, so browsers fetch it on each load.
diff --git a/backend/tenant_account_v2/serializer.py b/backend/tenant_account_v2/serializer.py
index 8b1789e0e..6af321c5f 100644
--- a/backend/tenant_account_v2/serializer.py
+++ b/backend/tenant_account_v2/serializer.py
@@ -2,9 +2,14 @@ from collections import OrderedDict
from typing import Any, cast
from account_v2.constants import Common
+from account_v2.models import NAME_SIZE
+from account_v2.user_profile import LANGUAGES, MAX_PHOTO_BYTES, PHOTO_TYPES
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.serializers import ModelSerializer
+from utils.FileValidator import FileValidator
from tenant_account_v2.capabilities import (
CAPABILITY_KEY_VALUES,
@@ -143,6 +148,66 @@ class UserInfoSerializer(serializers.Serializer):
picture = serializers.CharField()
+class UserProfileSerializer(UserInfoSerializer):
+ """The `user` object GET users/profile/ returns; documents the contract."""
+
+ # The identity provider's user info may leave these out.
+ id = serializers.CharField(allow_null=True)
+ name = serializers.CharField(
+ allow_null=True, help_text="The edited name when set, else the provider's"
+ )
+ display_name = serializers.CharField(
+ allow_null=True, help_text="The edited name when set, else the provider's"
+ )
+ family_name = serializers.CharField(allow_null=True)
+ picture = serializers.CharField(
+ allow_null=True,
+ help_text="`photo_url` when a photo is set, else the provider's picture",
+ )
+ is_admin = serializers.BooleanField()
+ login_onboarding_message_displayed = serializers.BooleanField()
+ prompt_onboarding_message_displayed = serializers.BooleanField()
+ role = serializers.CharField()
+ organization_name = serializers.CharField(required=False)
+ organization_id = serializers.CharField(required=False)
+ photo_url = serializers.CharField(
+ allow_null=True,
+ help_text="Org-scoped URL of GET users/profile/photo/, null when no photo",
+ )
+ language = serializers.CharField(help_text="BCP 47 tag; only `en-US` for now")
+
+
+class ProfileUpdateSerializer(serializers.Serializer):
+ # validated_data is keyed by the model field the value is saved to.
+ display_name = serializers.CharField(
+ max_length=NAME_SIZE, source="profile_display_name"
+ )
+ language = serializers.ChoiceField(choices=LANGUAGES, required=False)
+
+
+@extend_schema_field(OpenApiTypes.BINARY)
+class PhotoUploadField(serializers.FileField):
+ """A bare ``FileField`` documents as ``format: uri``, and generators emit a
+ string for it instead of a multipart upload.
+ """
+
+
+class ProfilePhotoSerializer(serializers.Serializer):
+ photo = PhotoUploadField()
+
+ def validate_photo(self, photo: Any) -> Any:
+ # Size first, so an oversized file is refused before it is read again
+ # for type sniffing. The parser has already received it; a request-size
+ # cap belongs in the proxy or DATA_UPLOAD_MAX_MEMORY_SIZE.
+ if photo.size > MAX_PHOTO_BYTES:
+ raise ValidationError(
+ f"The photo is larger than {MAX_PHOTO_BYTES // (1024 * 1024)} MB."
+ )
+ # The type is read from the bytes, so a renamed file is judged by content.
+ FileValidator(allowed_mimetypes=PHOTO_TYPES)([photo])
+ return photo
+
+
class GetRolesResponseSerializer(serializers.Serializer):
id = serializers.CharField()
name = serializers.CharField()
diff --git a/backend/tenant_account_v2/test_profile_views.py b/backend/tenant_account_v2/test_profile_views.py
new file mode 100644
index 000000000..4a5b937ef
--- /dev/null
+++ b/backend/tenant_account_v2/test_profile_views.py
@@ -0,0 +1,357 @@
+"""Profile update endpoints, through the org-scoped URL and the auth middleware."""
+
+from unittest.mock import MagicMock, patch
+
+from account_v2.models import Organization
+from account_v2.test_user_profile import GIF, LocalStorageMixin, make_user, png_bytes
+from django.core.files.uploadedfile import SimpleUploadedFile
+from django.test import RequestFactory, TestCase, override_settings
+from utils.user_context import UserContext
+
+from tenant_account_v2.models import OrganizationMember
+
+BASE = "/api/v1/unstract/org-a/users/profile/"
+PHOTO = f"{BASE}photo/"
+
+
+def upload(content: bytes, name: str = "me.png") -> dict:
+ return {"photo": SimpleUploadedFile(name, content)}
+
+
+class ProfileEndpointTests(LocalStorageMixin, TestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ org = Organization.objects.create(
+ name="org-a", display_name="Org A", organization_id="org-a"
+ )
+ self.user = make_user("[email protected]")
+ OrganizationMember.objects.create(organization=org, user=self.user, role="admin")
+ # OSS auth throughout.
+ for target in (
+ "account_v2.custom_auth_middleware.AuthenticationPluginRegistry"
+ ".is_plugin_available",
+ "account_v2.authentication_controller.AuthenticationPluginRegistry"
+ ".is_plugin_available",
+ ):
+ patcher = patch(target, MagicMock(return_value=False))
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self.addCleanup(UserContext.set_organization_identifier, None)
+ self.client.force_login(self.user)
+ session = self.client.session
+ session["organization"] = "org-a"
+ session.save()
+
+ def profile(self) -> dict:
+ response = self.client.get(BASE)
+ self.assertEqual(response.status_code, 200, response.content)
+ return response.json()["user"]
+
+ def patch_profile(self, body: dict):
+ return self.client.patch(BASE, body, content_type="application/json")
+
+ def error_attrs(self, response) -> list[str]:
+ self.assertEqual(response.status_code, 400, response.content)
+ return [e["attr"] for e in response.json()["errors"]]
+
+ # GET
+
+ def test_get_adds_photo_url_and_language(self) -> None:
+ user = self.profile()
+ self.assertIsNone(user["photo_url"])
+ self.assertEqual(user["language"], "en-US")
+ self.assertEqual(user["name"], "[email protected]")
+ self.assertTrue(user["is_admin"])
+
+ # PATCH
+
+ def test_patch_name_is_trimmed_and_shown(self) -> None:
+ response = self.patch_profile({"display_name": " Me Edited "})
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(response.json()["user"]["display_name"], "Me Edited")
+ user = self.profile()
+ self.assertEqual((user["name"], user["display_name"]), ("Me Edited",) * 2)
+ self.user.refresh_from_db()
+ self.assertEqual(self.user.profile_display_name, "Me Edited")
+
+ def test_patch_language(self) -> None:
+ type(self.user).objects.filter(pk=self.user.pk).update(language="xx-XX")
+ self.assertEqual(self.profile()["language"], "xx-XX")
+ response = self.patch_profile({"language": "en-US"})
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(self.profile()["language"], "en-US")
+
+ def test_empty_patch_changes_nothing(self) -> None:
+ self.patch_profile({"display_name": "Me Edited"})
+ response = self.patch_profile({})
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(response.json()["user"]["display_name"], "Me Edited")
+ self.user.refresh_from_db()
+ self.assertEqual(self.user.profile_display_name, "Me Edited")
+
+ def test_patch_refuses_empty_and_blank_names(self) -> None:
+ for name in ("", " "):
+ with self.subTest(name=name):
+ self.assertEqual(
+ self.error_attrs(self.patch_profile({"display_name": name})),
+ ["display_name"],
+ )
+
+ def test_patch_language_alone_keeps_the_name(self) -> None:
+ self.patch_profile({"display_name": "Me Edited"})
+ response = self.patch_profile({"language": "en-US"})
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(response.json()["user"]["display_name"], "Me Edited")
+
+ def test_patch_refuses_name_over_64(self) -> None:
+ self.assertEqual(
+ self.error_attrs(self.patch_profile({"display_name": "x" * 65})),
+ ["display_name"],
+ )
+ self.assertEqual(self.patch_profile({"display_name": "x" * 64}).status_code, 200)
+
+ def test_patch_keeps_the_change_when_the_read_back_fails(self) -> None:
+ with (
+ patch(
+ "tenant_account_v2.users_view.AuthenticationController"
+ ".get_organization_members_by_user",
+ side_effect=RuntimeError("auth service down"),
+ ),
+ self.assertLogs("tenant_account_v2.users_view", "ERROR") as logs,
+ ):
+ response = self.patch_profile({"display_name": "Me Edited"})
+ self.assertEqual(response.status_code, 500, response.content)
+ self.user.refresh_from_db()
+ self.assertEqual(self.user.profile_display_name, "Me Edited")
+ (record,) = logs.records
+ self.assertIsNotNone(record.exc_info)
+ self.assertIn(str(self.user.pk), record.getMessage())
+
+ def test_patch_ignores_fields_it_does_not_own(self) -> None:
+ before = type(self.user).objects.get(pk=self.user.pk)
+ response = self.patch_profile(
+ {
+ "display_name": "Me Edited",
+ "is_staff": True,
+ "email": "[email protected]",
+ "profile_photo_updated_at": "2026-01-01T00:00:00Z",
+ }
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+ self.user.refresh_from_db()
+ self.assertEqual(self.user.profile_display_name, "Me Edited")
+ self.assertEqual(
+ (self.user.is_staff, self.user.email, self.user.profile_photo_updated_at),
+ (before.is_staff, before.email, None),
+ )
+
+ def test_patch_refuses_unknown_language(self) -> None:
+ self.assertEqual(
+ self.error_attrs(
+ self.patch_profile({"display_name": "Me", "language": "fr-FR"})
+ ),
+ ["language"],
+ )
+
+ # Photo
+
+ def test_upload_then_profile_and_photo(self) -> None:
+ response = self.client.post(PHOTO, upload(png_bytes()))
+ self.assertEqual(response.status_code, 200, response.content)
+ url = response.json()["photo_url"]
+ self.assertTrue(url.startswith(PHOTO + "?v="), url)
+ user = self.profile()
+ self.assertEqual((user["photo_url"], user["picture"]), (url, url))
+
+ photo = self.client.get(url)
+ self.assertEqual(photo.status_code, 200)
+ self.assertEqual(photo.content, png_bytes())
+ self.assertEqual(photo["Content-Type"], "image/png")
+ self.assertEqual(photo["X-Content-Type-Options"], "nosniff")
+
+ def test_photo_is_served_to_a_client_that_accepts_only_images(self) -> None:
+ self.client.post(PHOTO, upload(png_bytes()))
+ for accept in ("image/png", "image/*"):
+ with self.subTest(accept=accept):
+ photo = self.client.get(PHOTO, HTTP_ACCEPT=accept)
+ self.assertEqual(photo.status_code, 200)
+ self.assertEqual(photo.content, png_bytes())
+ self.assertEqual(photo["Content-Type"], "image/png")
+
+ def test_no_photo_is_a_json_404_when_only_images_are_accepted(self) -> None:
+ response = self.client.get(PHOTO, HTTP_ACCEPT="image/png")
+ self.assertEqual(response.status_code, 404)
+ self.assertEqual(response["Content-Type"], "application/json")
+ self.assertEqual(response.json()["type"], "client_error")
+
+ def test_type_comes_from_the_bytes_not_the_name(self) -> None:
+ response = self.client.post(PHOTO, upload(png_bytes(), "me.jpg"))
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(self.client.get(PHOTO)["Content-Type"], "image/png")
+
+ def test_upload_refuses_gif(self) -> None:
+ response = self.client.post(PHOTO, upload(GIF, "me.gif"))
+ self.assertEqual(self.error_attrs(response), ["photo"])
+
+ def test_upload_refuses_over_2_mb_before_sniffing_its_type(self) -> None:
+ big = png_bytes() + b"\x00" * (2 * 1024 * 1024 + 1 - len(png_bytes()))
+ with patch("utils.FileValidator.magic.from_buffer") as sniff:
+ response = self.client.post(PHOTO, upload(big))
+ self.assertEqual(self.error_attrs(response), ["photo"])
+ sniff.assert_not_called()
+
+ def test_set_organization_returns_photo_for_the_new_organization(self) -> None:
+ from account_v2.authentication_controller import AuthenticationController
+
+ Organization.objects.create(
+ name="org-b", display_name="Org B", organization_id="org-b"
+ )
+ self.client.post(PHOTO, upload(png_bytes()))
+ self.user.refresh_from_db()
+ request = RequestFactory().post("/x/")
+ request.user = self.user
+ request.session = self.client.session # still on org-a
+ for target, value in (
+ (
+ "account_v2.authentication_controller.CacheService"
+ ".get_user_organizations",
+ MagicMock(return_value={"org-a", "org-b"}),
+ ),
+ (
+ "account_v2.authentication_controller.OrganizationMemberService"
+ ".remove_user_membership_in_organization_cache",
+ MagicMock(),
+ ),
+ (
+ "account_v2.authentication_controller.OrganizationMemberService"
+ ".set_user_membership_in_organization_cache",
+ MagicMock(),
+ ),
+ (
+ "account_v2.authentication_controller.AuthenticationService"
+ ".setup_default_adapters_for_user",
+ MagicMock(),
+ ),
+ ):
+ patcher = patch(target, value)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ response = AuthenticationController().set_user_organization(request, "org-b")
+ self.assertEqual(response.status_code, 200)
+ self.assertIn("/org-b/users/profile/photo/", response.data["user"]["picture"])
+
+ def test_upload_accepts_exactly_2_mb(self) -> None:
+ exact = png_bytes() + b"\x00" * (2 * 1024 * 1024 - len(png_bytes()))
+ self.assertEqual(self.client.post(PHOTO, upload(exact)).status_code, 200)
+
+ def test_upload_refuses_missing_file(self) -> None:
+ self.assertEqual(self.error_attrs(self.client.post(PHOTO, {})), ["photo"])
+
+ def test_storage_read_error_is_a_500_and_keeps_the_photo(self) -> None:
+ from unstract.sdk1.exceptions import FileOperationError
+
+ self.client.post(PHOTO, upload(png_bytes()))
+ with patch(
+ "unstract.sdk1.file_storage.impl.FileStorage.read",
+ side_effect=FileOperationError("AccessDenied"),
+ ):
+ self.assertEqual(self.client.get(PHOTO).status_code, 500)
+ self.user.refresh_from_db()
+ self.assertIsNotNone(self.user.profile_photo_updated_at)
+
+ @override_settings(DEBUG=False) # as in the cloud and on-prem settings
+ def test_missing_photo_path_setting_is_a_json_500(self) -> None:
+ self.client.post(PHOTO, upload(png_bytes()))
+ self.client.raise_request_exception = False
+ env = {"REMOTE_USER_PROFILE_PHOTO_PATH": "", "REMOTE_PROMPT_STUDIO_FILE_PATH": ""}
+ with patch.dict("os.environ", env):
+ response = self.client.get(PHOTO)
+ self.assertEqual(response.status_code, 500)
+ self.assertEqual(response.json()["type"], "server_error")
+
+ def test_no_photo_is_404(self) -> None:
+ self.assertEqual(self.client.get(PHOTO).status_code, 404)
+
+ def test_delete_photo(self) -> None:
+ self.client.post(PHOTO, upload(png_bytes()))
+ self.assertEqual(self.client.delete(PHOTO).status_code, 204)
+ self.assertEqual(self.client.get(PHOTO).status_code, 404)
+ self.assertIsNone(self.profile()["photo_url"])
+
+ def test_delete_without_photo_is_204(self) -> None:
+ self.assertEqual(self.client.delete(PHOTO).status_code, 204)
+
+ # Auth
+
+ def test_anonymous_caller_is_refused(self) -> None:
+ self.client.logout()
+ for method in ("get", "post", "delete"):
+ with self.subTest(method=method):
+ response = getattr(self.client, method)(PHOTO)
+ self.assertEqual(response.status_code, 401)
+ self.assertEqual(self.patch_profile({"display_name": "x"}).status_code, 401)
+
+ def test_service_account_cannot_change_the_profile(self) -> None:
+ type(self.user).objects.filter(pk=self.user.pk).update(is_service_account=True)
+ calls = (
+ ("patch", lambda: self.patch_profile({"display_name": "Bot"})),
+ ("post", lambda: self.client.post(PHOTO, upload(png_bytes()))),
+ ("delete", lambda: self.client.delete(PHOTO)),
+ )
+ for method, call in calls:
+ with self.subTest(method=method):
+ self.assertEqual(call().status_code, 403)
+ self.user.refresh_from_db()
+ self.assertEqual(self.user.profile_display_name, "")
+ self.assertIsNone(self.user.profile_photo_updated_at)
+
+
+class ProfileSchemaTests(TestCase):
+ def test_schema_documents_the_contract(self) -> None:
+ from drf_spectacular.generators import SchemaGenerator
+
+ from tenant_account_v2 import users_urls
+
+ schema = SchemaGenerator(patterns=users_urls.urlpatterns).get_schema(
+ request=None, public=True
+ )
+ ops = {
+ op["operationId"]: op
+ for path in schema["paths"].values()
+ for op in path.values()
+ }
+ self.assertTrue(
+ {
+ "user_profile",
+ "user_profile_update",
+ "user_profile_photo",
+ "user_profile_photo_upload",
+ "user_profile_photo_delete",
+ }
+ <= set(ops)
+ )
+ user = schema["components"]["schemas"]["UserProfile"]
+ self.assertTrue({"photo_url", "language"} <= set(user["required"]))
+ for field in ("id", "name", "display_name", "family_name", "photo_url"):
+ with self.subTest(field=field):
+ self.assertTrue(user["properties"][field].get("nullable"))
+ photo_url = schema["components"]["schemas"]["UserProfilePhotoResponse"]
+ self.assertTrue(photo_url["properties"]["photo_url"].get("nullable"))
+ update = schema["components"]["schemas"]["PatchedProfileUpdate"]
+ self.assertNotIn("required", update)
+ self.assertEqual(update["properties"]["display_name"]["maxLength"], 64)
+ self.assertEqual(
+ set(ops["user_profile_update"]["responses"]),
+ {"200", "400", "403", "404", "500"},
+ )
+ photo = ops["user_profile_photo"]["responses"]["200"]["content"]
+ self.assertEqual(set(photo), {"image/png", "image/jpeg"})
+ upload = ops["user_profile_photo_upload"]["requestBody"]["content"]
+ self.assertEqual(set(upload), {"multipart/form-data"})
+ # A bare FileField documents as `format: uri`, which generators turn
+ # into a string parameter instead of a multipart upload.
+ ref = upload["multipart/form-data"]["schema"]["$ref"].rsplit("/", 1)[-1]
+ self.assertEqual(
+ schema["components"]["schemas"][ref]["properties"]["photo"],
+ {"type": "string", "format": "binary"},
+ )
diff --git a/backend/tenant_account_v2/users_urls.py b/backend/tenant_account_v2/users_urls.py
index 4ada4cd25..5ae4f4955 100644
--- a/backend/tenant_account_v2/users_urls.py
+++ b/backend/tenant_account_v2/users_urls.py
@@ -13,6 +13,15 @@ user_profile = OrganizationUserViewSet.as_view(
{
"get": OrganizationUserViewSet.get_user_profile.__name__,
"put": OrganizationUserViewSet.update_flags.__name__,
+ "patch": OrganizationUserViewSet.update_profile.__name__,
+ }
+)
+
+user_profile_photo = OrganizationUserViewSet.as_view(
+ {
+ "get": OrganizationUserViewSet.get_profile_photo.__name__,
+ "post": OrganizationUserViewSet.upload_profile_photo.__name__,
+ "delete": OrganizationUserViewSet.delete_profile_photo.__name__,
}
)
@@ -33,6 +42,7 @@ organization_users = OrganizationUserViewSet.as_view(
urlpatterns = [
path("", organization_users, name="organization_user"),
path("profile/", user_profile, name="user_profile"),
+ path("profile/photo/", user_profile_photo, name="user_profile_photo"),
path("role/", organization_user_role, name="organization_user_role"),
path("invite/", invite_user, name="invite_user"),
]
diff --git a/backend/tenant_account_v2/users_view.py b/backend/tenant_account_v2/users_view.py
index 44611f34e..30ab17962 100644
--- a/backend/tenant_account_v2/users_view.py
+++ b/backend/tenant_account_v2/users_view.py
@@ -1,15 +1,22 @@
import logging
+from typing import Any
from account_v2.authentication_controller import AuthenticationController
from account_v2.exceptions import BadRequestException
+from account_v2.user_profile import delete_photo, photo_url, read_photo, save_photo
+from django.http import HttpResponse
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiResponse, extend_schema, inline_serializer
from platform_audit.actions import Action, TargetType
from platform_audit.recorder import (
BEFORE_UNAVAILABLE,
best_effort,
record_platform_event,
)
-from rest_framework import status, viewsets
+from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound
+from rest_framework.renderers import BaseRenderer, JSONRenderer
from rest_framework.request import Request
from rest_framework.response import Response
from utils.user_context import UserContext
@@ -21,16 +28,61 @@ from tenant_account_v2.serializer import (
ChangeUserRoleRequestSerializer,
InviteUserSerializer,
OrganizationMemberSerializer,
+ ProfilePhotoSerializer,
+ ProfileUpdateSerializer,
RemoveUserFromOrganizationSerializer,
UpdateFlagSerializer,
UserInfoSerializer,
UserInviteResponseSerializer,
+ UserProfileSerializer,
)
Logger = logging.getLogger(__name__)
+PROFILE_RESPONSE = inline_serializer(
+ "UserProfileResponse", {"user": UserProfileSerializer()}
+)
+SERVICE_ACCOUNT_REFUSED = OpenApiResponse(
+ description="The caller is a service account (platform API key)"
+)
+PHOTO_URL_RESPONSE = inline_serializer(
+ "UserProfilePhotoResponse",
+ {"photo_url": serializers.CharField(allow_null=True)},
+)
+
+
+class ProfilePhotoRenderer(BaseRenderer):
+ """Lets a client that accepts only images reach the photo view.
+
+ The photo itself is returned as an ``HttpResponse``, so this renderer only
+ renders the error bodies, as JSON.
+ """
+
+ media_type = "image/*"
+ format = "image"
+ charset = None
+ render_style = "binary"
+
+ def render(
+ self,
+ data: Any,
+ accepted_media_type: str | None = None,
+ renderer_context: dict[str, Any] | None = None,
+ ) -> bytes:
+ response = (renderer_context or {}).get("response")
+ if response is not None:
+ response["Content-Type"] = JSONRenderer.media_type
+ return JSONRenderer().render(data)
+
class OrganizationUserViewSet(viewsets.ViewSet):
+ def get_renderers(self) -> list[BaseRenderer]:
+ renderers = super().get_renderers()
+ if getattr(self, "action", None) == "get_profile_photo":
+ # JSON stays first, so a client that accepts both gets JSON errors.
+ renderers.append(ProfilePhotoRenderer())
+ return renderers
+
@action(detail=False, methods=["POST"])
def assign_organization_role_to_user(self, request: Request) -> Response:
serializer = ChangeUserRoleRequestSerializer(data=request.data)
@@ -85,6 +137,12 @@ class OrganizationUserViewSet(viewsets.ViewSet):
data={"status": "failed", "message": "failed"},
)
+ @extend_schema(
+ operation_id="user_profile",
+ tags=["profile"],
+ responses={200: PROFILE_RESPONSE},
+ description="The current user. See tenant_account_v2/ReadMe.md.",
+ )
@action(detail=False, methods=["GET"])
def get_user_profile(self, request: Request) -> Response:
auth_controller = AuthenticationController()
@@ -118,17 +176,105 @@ class OrganizationUserViewSet(viewsets.ViewSet):
if org:
serialized_user_info["organization_name"] = org.display_name
serialized_user_info["organization_id"] = org.organization_id
+ serialized_user_info["photo_url"] = photo_url(request.user, org_id)
+ serialized_user_info["language"] = request.user.language
return Response(
status=status.HTTP_200_OK, data={"user": serialized_user_info}
)
- except Exception as error:
- Logger.error(f"Error while get User : {error}")
+ except Exception:
+ Logger.exception("Profile read failed for user %s", request.user.pk)
return Response(
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
data={"message": "Internal Error"},
)
+ @extend_schema(
+ operation_id="user_profile_update",
+ tags=["profile"],
+ request=ProfileUpdateSerializer,
+ responses={
+ 200: PROFILE_RESPONSE,
+ 400: OpenApiResponse(description="Invalid field"),
+ 403: SERVICE_ACCOUNT_REFUSED,
+ 404: OpenApiResponse(
+ description="Saved, but the user was not found on read back"
+ ),
+ 500: OpenApiResponse(
+ description="Saved, but the profile could not be read back"
+ ),
+ },
+ )
+ @action(detail=False, methods=["PATCH"])
+ def update_profile(self, request: Request) -> Response:
+ """Set the name and/or language shown for the current user."""
+ if refused := _refuse_service_account(request):
+ return refused
+ serializer = ProfileUpdateSerializer(data=request.data, partial=True)
+ serializer.is_valid(raise_exception=True)
+ changes = serializer.validated_data
+ if changes:
+ for field, value in changes.items():
+ setattr(request.user, field, value)
+ request.user.save(update_fields=list(changes))
+ return self.get_user_profile(request)
+
+ @extend_schema(
+ operation_id="user_profile_photo",
+ tags=["profile"],
+ responses={
+ (200, "image/png"): OpenApiTypes.BINARY,
+ (200, "image/jpeg"): OpenApiTypes.BINARY,
+ 404: OpenApiResponse(description="No photo"),
+ },
+ )
+ @action(detail=False, methods=["GET"])
+ def get_profile_photo(self, request: Request) -> HttpResponse:
+ photo = read_photo(request.user)
+ if not photo:
+ raise NotFound("No profile photo.")
+ data, content_type = photo
+ response = HttpResponse(data, content_type=content_type)
+ response["Content-Disposition"] = "inline"
+ return response
+
+ @extend_schema(
+ operation_id="user_profile_photo_upload",
+ tags=["profile"],
+ request={"multipart/form-data": ProfilePhotoSerializer},
+ responses={
+ 200: PHOTO_URL_RESPONSE,
+ 400: OpenApiResponse(
+ description="No photo field, not a PNG or JPEG, or over 2 MB"
+ ),
+ 403: SERVICE_ACCOUNT_REFUSED,
+ },
+ )
+ @action(detail=False, methods=["POST"])
+ def upload_profile_photo(self, request: Request) -> Response:
+ if refused := _refuse_service_account(request):
+ return refused
+ serializer = ProfilePhotoSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ save_photo(request.user, serializer.validated_data["photo"].read())
+ org_id = UserSessionUtils.get_organization_id(request)
+ return Response(
+ status=status.HTTP_200_OK,
+ data={"photo_url": photo_url(request.user, org_id)},
+ )
+
+ @extend_schema(
+ operation_id="user_profile_photo_delete",
+ tags=["profile"],
+ responses={204: None, 403: SERVICE_ACCOUNT_REFUSED},
+ )
+ @action(detail=False, methods=["DELETE"])
+ def delete_profile_photo(self, request: Request) -> Response:
+ if refused := _refuse_service_account(request):
+ return refused
+ delete_photo(request.user)
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
@action(detail=False, methods=["POST"])
def invite_user(self, request: Request) -> Response:
serializer = InviteUserSerializer(data=request.data)
@@ -222,6 +368,16 @@ class OrganizationUserViewSet(viewsets.ViewSet):
)
+def _refuse_service_account(request: Request) -> Response | None:
+ """A 403 for service accounts (platform API keys), which have no profile."""
+ if getattr(request.user, "is_service_account", False):
+ return Response(
+ status=status.HTTP_403_FORBIDDEN,
+ data={"message": "Service accounts have no profile"},
+ )
+ return None
+
+
# Returned for an e-mail with no membership, so that ``None`` (from
# ``best_effort``) means only "the lookup failed".
_NOT_A_MEMBER: dict = {}