Skip to content

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

UN-4388 [FEAT] Remember each user's last-used product on the server, with a first-login flag on the session (#2360)

ali686a185b12fb
diff --git a/backend/account_v2/ReadMe.md b/backend/account_v2/ReadMe.md
index 35695cfb5..08f83c6e1 100644
--- a/backend/account_v2/ReadMe.md
+++ b/backend/account_v2/ReadMe.md
@@ -24,3 +24,25 @@
## Signout
1.signout APi
+
+## Last-used product preference
+
+Each user has one last-used product, shared by all their organisations
+(`UserProductPreference`, logic in `product_preference.py`).
+
+- `GET /api/v1/users/me/product-preference/` returns `product` (`unstract`,
+ `llm-whisperer`, `verticals` or `flow`, or null), `updated_at` and
+ `has_chosen`.
+- `PUT` the same URL with `{"product": "<id>"}` to store it. Unknown ids get a
+ 400. Service accounts get a 403.
+- `GET /api/v1/session` also returns `last_product` and `has_chosen`.
+- `has_chosen` is false until a product is first stored. Clients use it as the
+ first-login signal.
+- The backend never writes it on its own. The client is expected to `PUT` it
+ (from the product switcher, and after a login that started from a product
+ page via `selectedProduct`) before reading `session`. Because the write is
+ client-side, it works the same for every auth plugin.
+- The `product` column has a database check constraint, so only the ids above
+ can be stored.
+
+JSON Schemas for the responses and the request body are in `contract/`.
diff --git a/backend/account_v2/contract/product-preference-request.schema.json b/backend/account_v2/contract/product-preference-request.schema.json
new file mode 100644
index 000000000..7942bbcfc
--- /dev/null
+++ b/backend/account_v2/contract/product-preference-request.schema.json
@@ -0,0 +1,9 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "unstract/account/product-preference-request/v1",
+ "type": "object",
+ "required": ["product"],
+ "properties": {
+ "product": {"enum": ["unstract", "llm-whisperer", "verticals", "flow"]}
+ }
+}
diff --git a/backend/account_v2/contract/product-preference-response.schema.json b/backend/account_v2/contract/product-preference-response.schema.json
new file mode 100644
index 000000000..038bb4e48
--- /dev/null
+++ b/backend/account_v2/contract/product-preference-response.schema.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "unstract/account/product-preference-response/v1",
+ "type": "object",
+ "required": ["product", "updated_at", "has_chosen"],
+ "additionalProperties": false,
+ "properties": {
+ "product": {
+ "enum": ["unstract", "llm-whisperer", "verticals", "flow", null]
+ },
+ "updated_at": {"type": ["string", "null"], "format": "date-time"},
+ "has_chosen": {"type": "boolean"}
+ }
+}
diff --git a/backend/account_v2/contract/session-product-fields.schema.json b/backend/account_v2/contract/session-product-fields.schema.json
new file mode 100644
index 000000000..5a9146537
--- /dev/null
+++ b/backend/account_v2/contract/session-product-fields.schema.json
@@ -0,0 +1,13 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "unstract/account/session-product-fields/v1",
+ "description": "Product-preference fields of the session response (GET /api/v1/session). Partial schema: other session fields are not described here, so additional properties are allowed.",
+ "type": "object",
+ "required": ["last_product", "has_chosen"],
+ "properties": {
+ "last_product": {
+ "enum": ["unstract", "llm-whisperer", "verticals", "flow", null]
+ },
+ "has_chosen": {"type": "boolean"}
+ }
+}
diff --git a/backend/account_v2/dto.py b/backend/account_v2/dto.py
index 4ac2731f5..d5ec5e1e5 100644
--- a/backend/account_v2/dto.py
+++ b/backend/account_v2/dto.py
@@ -63,6 +63,8 @@ class UserSessionInfo:
provider: str
is_staff: bool = False
disable_sso_idp_authorization: bool = False
+ last_product: str | None = None
+ has_chosen: bool = False
@staticmethod
def from_dict(data: dict[str, Any]) -> "UserSessionInfo":
@@ -77,6 +79,10 @@ class UserSessionInfo:
disable_sso_idp_authorization=data.get(
"disable_sso_idp_authorization", False
),
+ last_product=data.get("last_product"),
+ # Derived from the product when absent, never defaulted to False:
+ # a stored product means the user has chosen.
+ has_chosen=data.get("has_chosen", data.get("last_product") is not None),
)
def to_dict(self) -> Any:
@@ -88,6 +94,8 @@ class UserSessionInfo:
"role": self.role,
"is_staff": self.is_staff,
"disable_sso_idp_authorization": self.disable_sso_idp_authorization,
+ "last_product": self.last_product,
+ "has_chosen": self.has_chosen,
}
diff --git a/backend/account_v2/enums.py b/backend/account_v2/enums.py
index 9ee2dd4f2..e2485c0e3 100644
--- a/backend/account_v2/enums.py
+++ b/backend/account_v2/enums.py
@@ -7,6 +7,8 @@ silently changes permissions.
from enum import StrEnum
+from django.db import models
+
class UserRole(StrEnum):
"""Roles of the OSS default authentication service (no auth plugin)."""
@@ -23,3 +25,17 @@ class UnstractRole(StrEnum):
SUPERVISOR = "unstract_supervisor"
REVIEWER = "unstract_reviewer"
PLATFORM_ADMIN = "unstract_platform_admin"
+
+
+class Product(models.TextChoices):
+ """Product ids a user can land in.
+
+ ``verticals`` is API Hub; the id matches the frontend ``selectedProduct``
+ value, so it must not be renamed. ``flow`` is accepted, but the backend has
+ no Flow-specific behaviour; the client decides where it lands.
+ """
+
+ UNSTRACT = "unstract", "Unstract"
+ LLM_WHISPERER = "llm-whisperer", "LLMWhisperer"
+ VERTICALS = "verticals", "API Hub"
+ FLOW = "flow", "Flow"
diff --git a/backend/account_v2/migrations/0009_user_product_preference.py b/backend/account_v2/migrations/0009_user_product_preference.py
new file mode 100644
index 000000000..2d034bfda
--- /dev/null
+++ b/backend/account_v2/migrations/0009_user_product_preference.py
@@ -0,0 +1,57 @@
+# Generated by Django 4.2.30 on 2026-10-21 06:46
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("account_v2", "0008_organization_capability_settings"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="UserProductPreference",
+ fields=[
+ (
+ "user",
+ models.OneToOneField(
+ on_delete=django.db.models.deletion.CASCADE,
+ primary_key=True,
+ related_name="product_preference",
+ serialize=False,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "product",
+ models.CharField(
+ choices=[
+ ("unstract", "Unstract"),
+ ("llm-whisperer", "LLMWhisperer"),
+ ("verticals", "API Hub"),
+ ("flow", "Flow"),
+ ],
+ db_comment="Product id the user last used, e.g. unstract or llm-whisperer",
+ max_length=32,
+ ),
+ ),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ],
+ options={
+ "verbose_name": "User Product Preference",
+ "verbose_name_plural": "User Product Preferences",
+ "db_table": "user_product_preference",
+ },
+ ),
+ migrations.AddConstraint(
+ model_name="userproductpreference",
+ constraint=models.CheckConstraint(
+ check=models.Q(
+ ("product__in", ["unstract", "llm-whisperer", "verticals", "flow"])
+ ),
+ name="user_product_preference_product_valid",
+ ),
+ ),
+ ]
diff --git a/backend/account_v2/models.py b/backend/account_v2/models.py
index 447aa9947..36c3ae954 100644
--- a/backend/account_v2/models.py
+++ b/backend/account_v2/models.py
@@ -3,6 +3,7 @@ import uuid
from django.contrib.auth.models import AbstractUser, Group, Permission
from django.db import models
+from account_v2.enums import Product
from backend.constants import FieldLengthConstants as FieldLength
NAME_SIZE = 64
@@ -162,6 +163,38 @@ class User(AbstractUser):
db_table = "user"
+class UserProductPreference(models.Model):
+ """A user's last-used product, shared across their organisations.
+
+ No row means the user has never chosen a product (the first-login flag).
+ See ``account_v2/product_preference.py``.
+ """
+
+ user = models.OneToOneField(
+ "User",
+ on_delete=models.CASCADE,
+ primary_key=True,
+ related_name="product_preference",
+ )
+ product = models.CharField(
+ max_length=32,
+ choices=Product.choices,
+ db_comment="Product id the user last used, e.g. unstract or llm-whisperer",
+ )
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ verbose_name = "User Product Preference"
+ verbose_name_plural = "User Product Preferences"
+ db_table = "user_product_preference"
+ constraints = [
+ models.CheckConstraint(
+ check=models.Q(product__in=Product.values),
+ name="user_product_preference_product_valid",
+ )
+ ]
+
+
class PlatformKey(models.Model):
"""Model to hold details of Platform keys.
diff --git a/backend/account_v2/product_preference.py b/backend/account_v2/product_preference.py
new file mode 100644
index 000000000..ad9b22f1d
--- /dev/null
+++ b/backend/account_v2/product_preference.py
@@ -0,0 +1,54 @@
+"""Last-used product preference.
+
+One row per user, shared by every organisation the user belongs to, so the
+platform can land a returning user in the product they used last. The row's
+existence is the first-login flag: a user with no row has never chosen.
+
+The backend never writes it on its own: the client is expected to store it
+with ``PUT users/me/product-preference/``. It is read back on ``session`` as
+``last_product`` and ``has_chosen``.
+"""
+
+from dataclasses import dataclass
+from datetime import datetime
+
+from account_v2.enums import Product
+from account_v2.models import User, UserProductPreference
+
+
+@dataclass(frozen=True)
+class ProductPreference:
+ product: str | None
+ updated_at: datetime | None
+
+ @property
+ def has_chosen(self) -> bool:
+ return self.product is not None
+
+
+NO_PREFERENCE = ProductPreference(product=None, updated_at=None)
+
+
+def get_product_preference(user: User) -> ProductPreference:
+ row = (
+ UserProductPreference.objects.filter(user=user)
+ .values("product", "updated_at")
+ .first()
+ )
+ if row is None:
+ return NO_PREFERENCE
+ return ProductPreference(product=row["product"], updated_at=row["updated_at"])
+
+
+def set_product_preference(user: User, product: str) -> ProductPreference:
+ """Store ``product`` as the user's last-used product.
+
+ Raises ValueError for an unknown product id. The view validates the
+ request first, so this guards the table, not user input.
+ """
+ if product not in Product.values:
+ raise ValueError(f"Unknown product: {product!r}")
+ row, _ = UserProductPreference.objects.update_or_create(
+ user=user, defaults={"product": product}
+ )
+ return ProductPreference(product=row.product, updated_at=row.updated_at)
diff --git a/backend/account_v2/serializer.py b/backend/account_v2/serializer.py
index b92f9377d..81e2cec2d 100644
--- a/backend/account_v2/serializer.py
+++ b/backend/account_v2/serializer.py
@@ -3,6 +3,7 @@ import re
from rest_framework import serializers
from utils.input_sanitizer import validate_name_field
+from account_v2.enums import Product
from account_v2.models import Organization, User
@@ -128,3 +129,16 @@ class UserSessionResponseSerializer(serializers.Serializer):
provider = serializers.CharField()
is_staff = serializers.BooleanField()
disable_sso_idp_authorization = serializers.BooleanField()
+ # The user's last-used product and whether they have ever chosen one.
+ last_product = serializers.ChoiceField(choices=Product.choices, allow_null=True)
+ has_chosen = serializers.BooleanField()
+
+
+class ProductPreferenceSerializer(serializers.Serializer):
+ product = serializers.ChoiceField(choices=Product.choices, allow_null=True)
+ updated_at = serializers.DateTimeField(allow_null=True)
+ has_chosen = serializers.BooleanField()
+
+
+class ProductPreferenceUpdateSerializer(serializers.Serializer):
+ product = serializers.ChoiceField(choices=Product.choices)
diff --git a/backend/account_v2/test_product_preference.py b/backend/account_v2/test_product_preference.py
new file mode 100644
index 000000000..ca1ffc089
--- /dev/null
+++ b/backend/account_v2/test_product_preference.py
@@ -0,0 +1,263 @@
+"""Last-used product preference and first-login flag.
+
+* A new user has no product and ``has_chosen`` false; one PUT sets both.
+* The preference belongs to the user: each user sees only their own value, the
+ same value in every organisation, and service accounts are refused.
+* Only known product ids can be stored, by the API and by the database.
+* ``session`` carries ``last_product`` and ``has_chosen`` beside its existing
+ fields.
+* Responses validate against the committed JSON Schemas, and the schemas'
+ product list matches ``Product``.
+
+Requests go through the real URLconf and middleware with the Django test
+client, so routing and the auth middleware are covered too. The built-in
+session auth is forced, so a distribution's auth plugin (cloud's Auth0) cannot
+401 the request first, as in ``global_search/tests/test_contract.py``.
+
+DB-backed Django ``TestCase`` → auto-marked ``integration`` by ``backend/conftest.py``.
+"""
+
+import json
+import secrets
+from datetime import timedelta
+from pathlib import Path
+from unittest import mock
+
+import jsonschema
+from django.db import IntegrityError
+from django.test import SimpleTestCase, TestCase
+from django.utils import timezone
+
+from account_v2.authentication_plugin_registry import AuthenticationPluginRegistry
+from account_v2.enums import Product
+from account_v2.models import User, UserProductPreference
+from account_v2.product_preference import (
+ get_product_preference,
+ set_product_preference,
+)
+
+URL = "/api/v1/users/me/product-preference/"
+SESSION_URL = "/api/v1/session"
+
+CONTRACT = Path(__file__).parent / "contract"
+RESPONSE_SCHEMA = json.loads(
+ (CONTRACT / "product-preference-response.schema.json").read_text()
+)
+REQUEST_SCHEMA = json.loads(
+ (CONTRACT / "product-preference-request.schema.json").read_text()
+)
+SESSION_SCHEMA = json.loads((CONTRACT / "session-product-fields.schema.json").read_text())
+FORMATS = jsonschema.FormatChecker()
+
+# Session fields that existed before the product fields, from
+# UserSessionResponseSerializer.
+EXISTING_SESSION_FIELDS = {
+ "id",
+ "user_id",
+ "email",
+ "organization_id",
+ "role",
+ "provider",
+ "is_staff",
+ "disable_sso_idp_authorization",
+}
+
+
+class _BuiltInSessionAuth(TestCase):
+ def setUp(self) -> None:
+ no_plugin = mock.patch.object(
+ AuthenticationPluginRegistry, "is_plugin_available", return_value=False
+ )
+ no_plugin.start()
+ self.addCleanup(no_plugin.stop)
+
+
+def _user(email: str, **fields) -> User:
+ return User.objects.create_user(
+ username=email, email=email, password=secrets.token_urlsafe(), **fields
+ )
+
+
+class ProductPreferenceEndpointTests(_BuiltInSessionAuth):
+ def setUp(self) -> None:
+ super().setUp()
+ self.user = _user("[email protected]")
+ self.client.force_login(self.user)
+
+ def _put(self, body: dict):
+ return self.client.put(
+ URL, data=json.dumps(body), content_type="application/json"
+ )
+
+ def _assert_contract(self, data: dict) -> None:
+ jsonschema.validate(data, RESPONSE_SCHEMA, format_checker=FORMATS)
+
+ def test_new_user_has_no_product_and_has_not_chosen(self) -> None:
+ response = self.client.get(URL)
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(
+ response.json(), {"product": None, "updated_at": None, "has_chosen": False}
+ )
+ self._assert_contract(response.json())
+
+ def test_one_put_sets_product_and_clears_first_login_flag(self) -> None:
+ response = self._put({"product": "llm-whisperer"})
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.json()["product"], "llm-whisperer")
+ self.assertTrue(response.json()["has_chosen"])
+ self.assertIsNotNone(response.json()["updated_at"])
+ self._assert_contract(response.json())
+
+ read = self.client.get(URL).json()
+ self.assertEqual(read, response.json())
+
+ def test_put_replaces_the_previous_product(self) -> None:
+ self._put({"product": "llm-whisperer"})
+ self._put({"product": "unstract"})
+
+ self.assertEqual(self.client.get(URL).json()["product"], "unstract")
+ self.assertEqual(UserProductPreference.objects.filter(user=self.user).count(), 1)
+
+ def test_overwrite_moves_updated_at_forward(self) -> None:
+ first = self._put({"product": "llm-whisperer"}).json()["updated_at"]
+ later = timezone.now() + timedelta(minutes=5)
+ with mock.patch("django.utils.timezone.now", return_value=later):
+ second = self._put({"product": "unstract"}).json()["updated_at"]
+
+ self.assertGreater(second, first)
+ self.assertEqual(self.client.get(URL).json()["updated_at"], second)
+
+ def test_every_product_id_is_accepted(self) -> None:
+ for product in Product.values:
+ with self.subTest(product=product):
+ jsonschema.validate({"product": product}, REQUEST_SCHEMA)
+ response = self._put({"product": product})
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.json()["product"], product)
+
+ def test_invalid_bodies_are_rejected_and_nothing_is_stored(self) -> None:
+ bodies = (
+ {"product": "photoshop"},
+ {"product": None},
+ {},
+ {"product": "LLMWhisperer"},
+ {"product": "API Hub"},
+ {"product": "UNSTRACT"},
+ {"product": 123},
+ {"product": ["unstract"]},
+ )
+ for body in bodies:
+ with self.subTest(body=body):
+ with self.assertRaises(jsonschema.ValidationError):
+ jsonschema.validate(body, REQUEST_SCHEMA)
+ self.assertEqual(self._put(body).status_code, 400)
+ self.assertFalse(UserProductPreference.objects.filter(user=self.user).exists())
+
+ def test_malformed_json_is_rejected(self) -> None:
+ response = self.client.put(URL, data="{", content_type="application/json")
+
+ self.assertEqual(response.status_code, 400)
+ self.assertFalse(UserProductPreference.objects.filter(user=self.user).exists())
+
+ def test_a_user_reads_and_writes_only_their_own_preference(self) -> None:
+ self._put({"product": "llm-whisperer"})
+ other = _user("[email protected]")
+ self.client.force_login(other)
+
+ self.assertFalse(self.client.get(URL).json()["has_chosen"])
+ self._put({"product": "unstract"})
+
+ self.assertEqual(get_product_preference(self.user).product, "llm-whisperer")
+ self.assertEqual(get_product_preference(other).product, "unstract")
+
+ def test_service_accounts_are_refused(self) -> None:
+ bot = _user("[email protected]", is_service_account=True)
+ self.client.force_login(bot)
+
+ self.assertEqual(self.client.get(URL).status_code, 403)
+ self.assertEqual(self._put({"product": "unstract"}).status_code, 403)
+ self.assertEqual(self._put({"product": "photoshop"}).status_code, 403)
+ self.assertFalse(UserProductPreference.objects.filter(user=bot).exists())
+
+ def test_anonymous_request_is_unauthorised(self) -> None:
+ self.client.logout()
+
+ self.assertEqual(self.client.get(URL).status_code, 401)
+ self.assertEqual(self._put({"product": "unstract"}).status_code, 401)
+ self.assertFalse(UserProductPreference.objects.exists())
+
+ def test_other_methods_are_not_allowed(self) -> None:
+ self.assertEqual(self.client.post(URL, {"product": "unstract"}).status_code, 405)
+ self.assertEqual(self.client.patch(URL, {"product": "unstract"}).status_code, 405)
+ self.assertEqual(self.client.delete(URL).status_code, 405)
+
+
+class SessionProductFieldsTests(_BuiltInSessionAuth):
+ def setUp(self) -> None:
+ super().setUp()
+ self.user = _user("[email protected]")
+ self.client.force_login(self.user)
+
+ def _session(self, organization: str | None = None) -> dict:
+ if organization is not None:
+ session = self.client.session
+ session["organization"] = organization
+ session.save()
+ response = self.client.get(SESSION_URL)
+ self.assertEqual(response.status_code, 201)
+ return response.json()
+
+ def test_new_user_session_has_no_product_and_has_not_chosen(self) -> None:
+ data = self._session()
+
+ self.assertIsNone(data["last_product"])
+ self.assertFalse(data["has_chosen"])
+ jsonschema.validate(data, SESSION_SCHEMA)
+
+ def test_session_keeps_its_fields_and_adds_the_product_fields(self) -> None:
+ self.assertLessEqual(
+ EXISTING_SESSION_FIELDS | {"last_product", "has_chosen"}, set(self._session())
+ )
+
+ def test_session_carries_the_stored_product_in_every_organisation(self) -> None:
+ set_product_preference(self.user, "llm-whisperer")
+
+ for organization in ("org_one", "org_two"):
+ with self.subTest(organization=organization):
+ data = self._session(organization)
+ self.assertEqual(data["last_product"], "llm-whisperer")
+ self.assertTrue(data["has_chosen"])
+ self.assertEqual(data["organization_id"], organization)
+ jsonschema.validate(data, SESSION_SCHEMA)
+
+
+class ProductPreferenceServiceTests(TestCase):
+ def setUp(self) -> None:
+ self.user = _user("[email protected]")
+
+ def test_set_rejects_an_unknown_product(self) -> None:
+ with self.assertRaises(ValueError):
+ set_product_preference(self.user, "photoshop")
+ self.assertFalse(get_product_preference(self.user).has_chosen)
+
+ def test_database_rejects_an_unknown_product(self) -> None:
+ set_product_preference(self.user, "unstract")
+
+ with self.assertRaises(IntegrityError):
+ UserProductPreference.objects.filter(user=self.user).update(
+ product="photoshop"
+ )
+
+
+class ProductContractTests(SimpleTestCase):
+ def test_schemas_list_exactly_the_product_ids(self) -> None:
+ products = set(Product.values)
+ self.assertEqual(
+ set(RESPONSE_SCHEMA["properties"]["product"]["enum"]) - {None}, products
+ )
+ self.assertEqual(set(REQUEST_SCHEMA["properties"]["product"]["enum"]), products)
+ self.assertEqual(
+ set(SESSION_SCHEMA["properties"]["last_product"]["enum"]) - {None}, products
+ )
diff --git a/backend/account_v2/urls.py b/backend/account_v2/urls.py
index a17879266..d7290c601 100644
--- a/backend/account_v2/urls.py
+++ b/backend/account_v2/urls.py
@@ -7,6 +7,7 @@ from account_v2.views import (
get_session_data,
login,
logout,
+ product_preference,
set_organization,
signup,
)
@@ -20,4 +21,9 @@ urlpatterns = [
path("organization", get_organizations, name="get_organizations"),
path("organization/<str:id>/set", set_organization, name="set_organization"),
path("organization/create", create_organization, name="create_organization"),
+ path(
+ "users/me/product-preference/",
+ product_preference,
+ name="product_preference",
+ ),
]
diff --git a/backend/account_v2/views.py b/backend/account_v2/views.py
index c59cd2bea..d68674d71 100644
--- a/backend/account_v2/views.py
+++ b/backend/account_v2/views.py
@@ -16,9 +16,15 @@ from account_v2.dto import (
)
from account_v2.models import Organization
from account_v2.organization import OrganizationService
+from account_v2.product_preference import (
+ get_product_preference,
+ set_product_preference,
+)
from account_v2.serializer import (
OrganizationSignupResponseSerializer,
OrganizationSignupSerializer,
+ ProductPreferenceSerializer,
+ ProductPreferenceUpdateSerializer,
UserSessionResponseSerializer,
)
@@ -142,6 +148,9 @@ def make_session_response(
auth_controller = AuthenticationController()
token_data = UserSessionUtils.get_token_data(request)
provider = "" if token_data is None else token_data.get("provider", "")
+ # Not guarded: a failed read must not pass for "never chosen", which
+ # would send a returning user through the first-login choice.
+ preference = get_product_preference(request.user)
return UserSessionResponseSerializer(
UserSessionInfo(
id=request.user.id,
@@ -153,10 +162,41 @@ def make_session_response(
provider=provider,
is_staff=request.user.is_staff,
disable_sso_idp_authorization=settings.DISABLE_SSO_IDP_AUTHORIZATION,
+ last_product=preference.product,
+ has_chosen=preference.has_chosen,
)
).data
+@api_view(["GET", "PUT"])
+def product_preference(request: Request) -> Response:
+ """Read or write the signed-in user's last-used product.
+
+ The preference belongs to the user, not the organisation, so this route
+ carries no organisation segment and needs none selected: it answers on
+ first login, before the user has picked an organisation. A user only
+ ever reaches their own row, since the row is looked up from
+ ``request.user``. Service accounts (platform API keys) are refused, as
+ they never land anywhere.
+ """
+ if getattr(request.user, "is_service_account", False):
+ return Response(
+ status=status.HTTP_403_FORBIDDEN,
+ data={"message": "Service accounts have no product preference"},
+ )
+ if request.method == "PUT":
+ serializer = ProductPreferenceUpdateSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ preference = set_product_preference(
+ request.user, serializer.validated_data["product"]
+ )
+ else:
+ preference = get_product_preference(request.user)
+ return Response(
+ status=status.HTTP_200_OK, data=ProductPreferenceSerializer(preference).data
+ )
+
+
def makeSignupRequestParams(
serializer: OrganizationSignupSerializer,
) -> OrganizationSignupRequestBody: