Skip to content

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

UN-4283 [FEAT] Add role, member count and region to the organisation list (#2361)

Athul3c59e85ef6b5
diff --git a/backend/account_v2/ReadMe.md b/backend/account_v2/ReadMe.md
index 08f83c6e1..70e5b1ff8 100644
--- a/backend/account_v2/ReadMe.md
+++ b/backend/account_v2/ReadMe.md
@@ -25,6 +25,41 @@
1.signout APi
+## Organization list contract
+
+`GET /api/v1/organization` returns the caller's organizations. The typed contract is the `organization_list` operation's `@extend_schema` annotation in `views.py`, read with drf-spectacular; it is not part of the published deployment API spec. This section states the rules the annotation can't. Example from a cloud deployment:
+
+```json
+{
+ "message": "success",
+ "organizations": [
+ {
+ "id": "org_abc",
+ "display_name": "Zipstack",
+ "name": "zipstack",
+ "metadata": {},
+ "role": "unstract_admin",
+ "member_count": 40,
+ "region": "US"
+ }
+ ]
+}
+```
+
+- `id`, `display_name`, `name` and `metadata` are always present, in that order. `metadata` is always `null` in OSS. In cloud it holds the identity provider's organization metadata, or `null` when the organization has none.
+- `role`, `member_count` and `region` are each **absent, never null**, when this deployment can't answer for that organization. In cloud, regions share one identity provider, so the list can name organizations with no data on this deployment.
+- Absent means unknown. A client leaves the value out of the display and draws no conclusion from it: the same rows come back without the three fields when working them out fails (see below).
+
+| Field | Present when | Value |
+|---|---|---|
+| `role` | The caller has a membership in the organization on this deployment. | The stored role: `admin` or `user` in OSS; `unstract_admin`, `unstract_user`, `unstract_supervisor` or `unstract_reviewer` in cloud. |
+| `member_count` | The organization exists on this deployment. | The people the members page lists: the organization's member records on this deployment. Platform API key accounts and pending invitations are not counted. |
+| `region` | The organization exists on this deployment and the deployment sets `REGION`. | The region code (`US`, `EU`; `STAGING`, `DEV` or `INTEGRATION` outside production). The client maps it to a label. OSS and on-prem never send it: their settings don't read `REGION`, whatever the environment sets. It is the region of the deployment that answered: an organization from another region that the user once opened here has a local copy, so it shows this region and this deployment's member count. |
+
+If working out these three fields fails, the list is returned without them and the failure is logged.
+
+If the organizations can't be listed at all, the response is `412` and the session is logged out. For a known authorization error the body is `{"domain": ..., "code": ...}` with `code` one of `USF`, `USR`, `INE001`, `INE002` or `INS`; otherwise the body is empty.
+
## Last-used product preference
Each user has one last-used product, shared by all their organisations
diff --git a/backend/account_v2/authentication_controller.py b/backend/account_v2/authentication_controller.py
index 51bee8557..bf204321c 100644
--- a/backend/account_v2/authentication_controller.py
+++ b/backend/account_v2/authentication_controller.py
@@ -1,9 +1,11 @@
import logging
from collections.abc import Callable
+from contextlib import nullcontext
from typing import Any
from django.conf import settings
from django.contrib.auth import logout as django_logout
+from django.db import connection, transaction
from django.db.utils import IntegrityError
from django.http import HttpRequest
from django.middleware import csrf
@@ -46,6 +48,7 @@ from account_v2.enums import UserRole
from account_v2.exceptions import OrganizationNotExist
from account_v2.models import Organization, User
from account_v2.organization import OrganizationService
+from account_v2.organization_details import with_member_details
from account_v2.serializer import (
GetOrganizationsResponseSerializer,
OrganizationSerializer,
@@ -110,11 +113,12 @@ class AuthenticationController:
"""List a user's organizations.
Args:
- user (User): User instance
- z_code (str): _description_
+ request: the authenticated request.
Returns:
- list[OrganizationData]: _description_
+ Response with ``message`` and ``organizations`` (see
+ account_v2/ReadMe.md), or 412 with the session logged out if the
+ organizations can't be listed.
"""
try:
organizations = self.auth_service.user_organizations(request)
@@ -143,8 +147,23 @@ class AuthenticationController:
CacheService.set_user_organizations(user.user_id, list(org_ids))
+ # Under ATOMIC_REQUESTS a failed query aborts the request's
+ # transaction; a savepoint keeps the rest of the request usable.
+ guard = transaction.atomic() if connection.in_atomic_block else nullcontext()
+ try:
+ with guard:
+ listed: list[Any] = with_member_details(organizations, user)
+ except Exception:
+ # The details are optional; the list itself must still load.
+ logger.exception(
+ "Could not add member details to the organization list "
+ "for user %s (%d organizations)",
+ user.user_id,
+ len(organizations),
+ )
+ listed = organizations
serialized_organizations = GetOrganizationsResponseSerializer(
- organizations, many=True
+ listed, many=True
).data
response = Response(
status=status.HTTP_200_OK,
diff --git a/backend/account_v2/organization_details.py b/backend/account_v2/organization_details.py
new file mode 100644
index 000000000..bd6deb38b
--- /dev/null
+++ b/backend/account_v2/organization_details.py
@@ -0,0 +1,87 @@
+"""Role, member count and region for each organization in a user's list.
+
+The list comes from the auth service, which can name organizations this
+deployment has no data for: in cloud, regions share one identity provider. A
+field is added only where this deployment can answer it, and is otherwise left
+out of the row rather than sent as null:
+
+- ``role``: the caller has a membership row in that organization here.
+- ``member_count``: the organization exists here. Counts the people the
+ members page lists: the organization's member records here, without
+ platform API key accounts. Pending invitations have no record yet.
+- ``region``: the organization exists here and ``settings.REGION`` is set.
+"""
+
+from collections.abc import Sequence
+from typing import Any, Protocol
+
+from django.conf import settings
+from django.db.models import Count, Q
+from tenant_account_v2.models import OrganizationMember
+
+from account_v2.models import Organization, User
+
+
+class ListedOrganization(Protocol):
+ """What the auth services return for each organization.
+
+ ``metadata`` is read too where the object has it (cloud does, OSS
+ doesn't); a Protocol can't declare an optional attribute.
+ """
+
+ id: str
+ display_name: str
+ name: str
+
+
+def with_member_details(
+ organizations: Sequence[ListedOrganization], user: User
+) -> list[dict[str, Any]]:
+ """Return each organization as a dict with the details this deployment has.
+
+ Args:
+ organizations: objects with ``id`` (the organization_id),
+ ``display_name``, ``name`` and optionally ``metadata``, in the
+ order the list should keep.
+ user: the user the list belongs to.
+
+ Returns:
+ New dicts in input order; the inputs are not changed.
+ """
+ ids = [org.id for org in organizations]
+ member_counts = dict(
+ Organization.objects.filter(organization_id__in=ids)
+ .annotate(
+ # Same rule as OrganizationMemberService.get_members (the members
+ # page): platform API key accounts are members but not people.
+ member_count=Count(
+ "organizationmember",
+ filter=Q(organizationmember__user__is_service_account=False),
+ )
+ )
+ .values_list("organization_id", "member_count")
+ )
+ # _base_manager: the default manager filters to the request's organization.
+ roles = dict(
+ OrganizationMember._base_manager.filter(
+ user=user, organization__organization_id__in=ids
+ ).values_list("organization__organization_id", "role")
+ )
+ region = getattr(settings, "REGION", None)
+
+ rows = []
+ for org in organizations:
+ row: dict[str, Any] = {
+ "id": org.id,
+ "display_name": org.display_name,
+ "name": org.name,
+ "metadata": getattr(org, "metadata", None),
+ }
+ if org.id in roles:
+ row["role"] = roles[org.id]
+ if org.id in member_counts:
+ row["member_count"] = member_counts[org.id]
+ if region:
+ row["region"] = region
+ rows.append(row)
+ return rows
diff --git a/backend/account_v2/serializer.py b/backend/account_v2/serializer.py
index 81e2cec2d..8fb47a3b2 100644
--- a/backend/account_v2/serializer.py
+++ b/backend/account_v2/serializer.py
@@ -34,8 +34,29 @@ class GetOrganizationsResponseSerializer(serializers.Serializer):
id = serializers.CharField()
display_name = serializers.CharField()
name = serializers.CharField()
- metadata = serializers.JSONField(required=False, allow_null=True)
- # Add more fields as needed
+ # Always sent: allow_null turns a missing attribute into null.
+ metadata = serializers.JSONField(allow_null=True)
+ # Absent, never null, where this deployment can't answer for the
+ # organization: see account_v2/organization_details.py. Absent means
+ # unknown, so clients leave it out rather than infer from it.
+ role = serializers.CharField(
+ required=False,
+ help_text="The caller's role. Absent if the caller has no membership "
+ "in this organization on this deployment, or if the details could not "
+ "be loaded.",
+ )
+ member_count = serializers.IntegerField(
+ required=False,
+ help_text="The people the members page lists, without platform API key "
+ "accounts. Absent if the organization has no data on this deployment, "
+ "or if the details could not be loaded.",
+ )
+ region = serializers.CharField(
+ required=False,
+ help_text="The deployment's region code, e.g. US or EU. Absent where "
+ "the deployment has no regions, the organization has no data here, or "
+ "the details could not be loaded.",
+ )
def to_representation(self, instance): # type: ignore
data = super().to_representation(instance)
diff --git a/backend/account_v2/test_organization_details.py b/backend/account_v2/test_organization_details.py
new file mode 100644
index 000000000..439462b76
--- /dev/null
+++ b/backend/account_v2/test_organization_details.py
@@ -0,0 +1,166 @@
+"""Tests for the role, member count and region added to the organization list."""
+
+import secrets
+from dataclasses import dataclass
+from types import SimpleNamespace
+
+from django.test import TestCase, override_settings
+from tenant_account_v2.models import OrganizationMember
+from utils.user_context import UserContext
+
+from account_v2.dto import OrganizationData
+from account_v2.models import Organization, User
+from account_v2.organization_details import with_member_details
+
+
+@dataclass
+class CloudOrg:
+ """Same fields as the cloud plugin's Auth0Organization."""
+
+ id: str
+ display_name: str
+ name: str
+ metadata: dict | None = None
+
+
+def _user(email: str) -> User:
+ return User.objects.create_user(
+ username=email, email=email, password=secrets.token_urlsafe()
+ )
+
+
+def _bot(email: str) -> User:
+ """A platform API key account."""
+ bot = _user(email)
+ bot.is_service_account = True
+ bot.save()
+ return bot
+
+
+def _org(slug: str, display_name: str) -> Organization:
+ return Organization.objects.create(
+ name=slug, display_name=display_name, organization_id=slug
+ )
+
+
+def _data(org: Organization) -> OrganizationData:
+ return OrganizationData(
+ id=org.organization_id, display_name=org.display_name, name=org.name
+ )
+
+
+# REGION comes from the deployment's settings; start every test without one.
+@override_settings(REGION=None)
+class WithMemberDetailsTests(TestCase):
+ def setUp(self) -> None:
+ self.caller = _user("[email protected]")
+ self.org_a = _org("org-a", "Org A")
+ self.org_b = _org("org-b", "Org B")
+ self.org_c = _org("org-c", "Org C")
+ members = [
+ (self.org_a, self.caller, "admin"),
+ # Other members hold a role the caller never has, so a leak shows.
+ (self.org_a, _user("[email protected]"), "reviewer"),
+ (self.org_a, _user("[email protected]"), "reviewer"),
+ (self.org_b, self.caller, "user"),
+ (self.org_b, _user("[email protected]"), "reviewer"),
+ (self.org_c, _user("[email protected]"), "admin"),
+ ]
+ for org, user, role in members:
+ OrganizationMember.objects.create(organization=org, user=user, role=role)
+ # The list is requested from inside one organization's context.
+ UserContext.set_organization_identifier(self.org_a.organization_id)
+ self.addCleanup(UserContext.set_organization_identifier, None)
+
+ @override_settings(REGION="US")
+ def test_role_count_and_region_per_organisation(self) -> None:
+ rows = with_member_details([_data(self.org_a), _data(self.org_b)], self.caller)
+ self.assertEqual(
+ rows,
+ [
+ {
+ "id": "org-a",
+ "display_name": "Org A",
+ "name": "org-a",
+ "metadata": None,
+ "role": "admin",
+ "member_count": 3,
+ "region": "US",
+ },
+ {
+ "id": "org-b",
+ "display_name": "Org B",
+ "name": "org-b",
+ "metadata": None,
+ "role": "user",
+ "member_count": 2,
+ "region": "US",
+ },
+ ],
+ )
+
+ @override_settings(REGION=None)
+ def test_region_absent_without_regions(self) -> None:
+ rows = with_member_details([_data(self.org_a)], self.caller)
+ self.assertNotIn("region", rows[0])
+
+ @override_settings(REGION="US")
+ def test_unknown_organisation_gets_no_details(self) -> None:
+ unknown = OrganizationData(id="org-x", display_name="X", name="org-x")
+ rows = with_member_details([unknown], self.caller)
+ self.assertEqual(
+ rows,
+ [{"id": "org-x", "display_name": "X", "name": "org-x", "metadata": None}],
+ )
+
+ @override_settings(REGION="US")
+ def test_member_count_without_caller_membership(self) -> None:
+ row = with_member_details([_data(self.org_c)], self.caller)[0]
+ self.assertEqual(row["member_count"], 1)
+ self.assertEqual(row["region"], "US")
+ self.assertNotIn("role", row)
+
+ def test_member_count_leaves_out_service_accounts(self) -> None:
+ # Platform API keys get a member row; the members page doesn't list them.
+ bot = _bot("[email protected]")
+ OrganizationMember.objects.create(organization=self.org_a, user=bot, role="user")
+ row = with_member_details([_data(self.org_a)], self.caller)[0]
+ self.assertEqual(row["member_count"], 3)
+
+ @override_settings(REGION="US")
+ def test_organisation_with_no_people_counts_zero(self) -> None:
+ bot = _bot("[email protected]")
+ empty = _org("org-empty", "Empty")
+ OrganizationMember.objects.create(organization=empty, user=bot, role="user")
+ row = with_member_details([_data(empty)], self.caller)[0]
+ self.assertEqual((row["member_count"], row["region"]), (0, "US"))
+
+ def test_two_queries_for_any_number_of_organisations(self) -> None:
+ orgs = [_data(self.org_a), _data(self.org_b), _data(self.org_c)]
+ with self.assertNumQueries(2):
+ with_member_details(orgs, self.caller)
+
+ def test_metadata_passes_through(self) -> None:
+ cloud = CloudOrg(
+ id="org-a", display_name="Org A", name="org-a", metadata={"k": "v"}
+ )
+ row = with_member_details([cloud], self.caller)[0]
+ self.assertEqual(list(row)[:4], ["id", "display_name", "name", "metadata"])
+ self.assertEqual(row["metadata"], {"k": "v"})
+
+ def test_input_is_not_mutated(self) -> None:
+ org = _data(self.org_a)
+ with_member_details([org], self.caller)
+ self.assertFalse(hasattr(org, "role"))
+
+ def test_any_object_with_the_fields_works(self) -> None:
+ # A plugin may hand back plain objects rather than dataclasses.
+ org = SimpleNamespace(id="org-a", display_name="Org A", name="org-a")
+ row = with_member_details([org], self.caller)[0]
+ self.assertEqual(
+ list(row), ["id", "display_name", "name", "metadata", "role", "member_count"]
+ )
+ self.assertIsNone(row["metadata"])
+
+ def test_no_organizations(self) -> None:
+ self.assertEqual(with_member_details([], self.caller), [])
diff --git a/backend/account_v2/test_organization_list.py b/backend/account_v2/test_organization_list.py
new file mode 100644
index 000000000..9f971b9d0
--- /dev/null
+++ b/backend/account_v2/test_organization_list.py
@@ -0,0 +1,337 @@
+"""Tests for GET organization: the role, member count and region it now carries."""
+
+import secrets
+from unittest.mock import MagicMock, patch
+
+from django.db import connection
+from django.test import TestCase, override_settings
+from drf_spectacular.generators import SchemaGenerator
+from rest_framework.request import Request
+from rest_framework.test import APIRequestFactory, force_authenticate
+from tenant_account_v2.models import OrganizationMember
+from utils.user_context import UserContext
+
+from account_v2 import urls, views
+from account_v2.authentication_controller import AuthenticationController
+from account_v2.constants import AuthorizationErrorCode
+from account_v2.dto import OrganizationData
+from account_v2.models import Organization, User
+
+
+class _AuthorizationError(Exception):
+ code = AuthorizationErrorCode.USF
+ data = {"domain": "example.com"}
+
+
+def _user(email: str) -> User:
+ return User.objects.create_user(
+ username=email, email=email, password=secrets.token_urlsafe()
+ )
+
+
+class OrganizationListTests(TestCase):
+ def setUp(self) -> None:
+ self.caller = _user("[email protected]")
+ org_a = Organization.objects.create(
+ name="org-a", display_name="Org A", organization_id="org-a"
+ )
+ org_b = Organization.objects.create(
+ name="org-b", display_name="Org B", organization_id="org-b"
+ )
+ for org, user, role in [
+ (org_a, self.caller, "admin"),
+ (org_a, _user("[email protected]"), "user"),
+ (org_a, _user("[email protected]"), "user"),
+ (org_b, self.caller, "user"),
+ (org_b, _user("[email protected]"), "admin"),
+ ]:
+ OrganizationMember.objects.create(organization=org, user=user, role=role)
+ UserContext.set_organization_identifier(org_a.organization_id)
+ self.addCleanup(UserContext.set_organization_identifier, None)
+
+ for target, kwargs in [
+ (
+ "account_v2.authentication_controller."
+ "AuthenticationPluginRegistry.is_plugin_available",
+ {"return_value": False},
+ ),
+ (
+ "account_v2.authentication_controller."
+ "CacheService.set_user_organizations",
+ {},
+ ),
+ ]:
+ patcher = patch(target, **kwargs)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ self.controller = AuthenticationController()
+ self.listed = [
+ OrganizationData(
+ id=o.organization_id, display_name=o.display_name, name=o.name
+ )
+ for o in (org_a, org_b)
+ ]
+ patcher = patch.object(
+ self.controller.auth_service, "user_organizations", return_value=self.listed
+ )
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ raw = APIRequestFactory().get("/api/v1/organization")
+ force_authenticate(raw, user=self.caller)
+ self.request = Request(raw)
+
+ @override_settings(REGION="US")
+ def test_list_carries_the_new_fields(self) -> None:
+ response = self.controller.user_organizations(self.request)
+ self.assertEqual(response.status_code, 200)
+ a, b = response.data["organizations"]
+ self.assertEqual((a["role"], a["member_count"], a["region"]), ("admin", 3, "US"))
+ self.assertEqual((b["role"], b["member_count"], b["region"]), ("user", 2, "US"))
+
+ def test_existing_fields_keep_their_order(self) -> None:
+ org = self.controller.user_organizations(self.request).data["organizations"][0]
+ self.assertEqual(list(org)[:4], ["id", "display_name", "name", "metadata"])
+
+ @override_settings(REGION=None)
+ def test_no_region_key_without_regions(self) -> None:
+ orgs = self.controller.user_organizations(self.request).data["organizations"]
+ self.assertTrue(all("region" not in org for org in orgs))
+
+ def test_details_failure_still_lists_without_logout(self) -> None:
+ with (
+ self.assertLogs("account_v2.authentication_controller", "ERROR") as logs,
+ patch(
+ "account_v2.authentication_controller.with_member_details",
+ side_effect=RuntimeError("boom"),
+ ),
+ patch.object(self.controller, "user_logout") as logout,
+ ):
+ response = self.controller.user_organizations(self.request)
+ self.assertEqual(response.status_code, 200)
+ orgs = response.data["organizations"]
+ self.assertEqual([org["id"] for org in orgs], ["org-a", "org-b"])
+ self.assertNotIn("role", orgs[0])
+ self.assertEqual(list(orgs[0]), ["id", "display_name", "name", "metadata"])
+ logout.assert_not_called()
+ self.assertIn(self.caller.user_id, logs.output[0])
+ self.assertIn("2 organizations", logs.output[0])
+
+ def test_failed_details_query_leaves_the_transaction_usable(self) -> None:
+ # TestCase wraps each test in a transaction, as ATOMIC_REQUESTS would.
+ def bad_query(*args: object) -> None:
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT * FROM no_such_table")
+
+ with (
+ self.assertLogs("account_v2.authentication_controller", "ERROR"),
+ patch(
+ "account_v2.authentication_controller.with_member_details",
+ side_effect=bad_query,
+ ),
+ ):
+ response = self.controller.user_organizations(self.request)
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(User.objects.filter(pk=self.caller.pk).count(), 1)
+
+ def test_failure_outside_a_transaction_needs_no_savepoint(self) -> None:
+ with (
+ self.assertLogs("account_v2.authentication_controller", "ERROR"),
+ patch(
+ "account_v2.authentication_controller.connection",
+ MagicMock(in_atomic_block=False),
+ ),
+ patch("account_v2.authentication_controller.transaction.atomic") as atomic,
+ patch(
+ "account_v2.authentication_controller.with_member_details",
+ side_effect=RuntimeError("boom"),
+ ),
+ ):
+ response = self.controller.user_organizations(self.request)
+ self.assertEqual(response.status_code, 200)
+ atomic.assert_not_called()
+
+ def test_known_listing_error_is_412_with_code_and_logs_out(self) -> None:
+ with (
+ patch.object(
+ self.controller.auth_service,
+ "user_organizations",
+ side_effect=_AuthorizationError(),
+ ),
+ patch.object(self.controller, "user_logout") as logout,
+ ):
+ response = self.controller.user_organizations(self.request)
+ self.assertEqual(response.status_code, 412)
+ self.assertEqual(response.data, {"domain": "example.com", "code": "USF"})
+ logout.assert_called_once()
+
+ def test_unknown_listing_error_is_412_with_no_body(self) -> None:
+ with (
+ patch.object(
+ self.controller.auth_service,
+ "user_organizations",
+ side_effect=RuntimeError("idp down"),
+ ),
+ patch.object(self.controller, "user_logout") as logout,
+ ):
+ response = self.controller.user_organizations(self.request)
+ self.assertEqual(response.status_code, 412)
+ self.assertIsNone(response.data)
+ logout.assert_called_once()
+
+ def test_no_organizations_lists_none(self) -> None:
+ with patch.object(
+ self.controller.auth_service, "user_organizations", return_value=[]
+ ):
+ response = self.controller.user_organizations(self.request)
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.data["organizations"], [])
+
+ @override_settings(REGION=None)
+ def test_view_returns_the_old_payload_plus_details(self) -> None:
+ # Through the view, as v0 calls it: every old key and value unchanged.
+ raw = APIRequestFactory().get("/api/v1/organization")
+ force_authenticate(raw, user=self.caller)
+ # org-x has no data on this deployment, as for another region's org.
+ unknown = OrganizationData(id="org-x", display_name="X", name="org-x")
+ with patch(
+ "account_v2.authentication_controller.AuthenticationService.user_organizations",
+ return_value=[*self.listed, unknown],
+ ):
+ response = views.get_organizations(raw)
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(
+ response.data,
+ {
+ "message": "success",
+ "organizations": [
+ {
+ "id": "org-a",
+ "display_name": "Org A",
+ "name": "org-a",
+ "metadata": None,
+ "role": "admin",
+ "member_count": 3,
+ },
+ {
+ "id": "org-b",
+ "display_name": "Org B",
+ "name": "org-b",
+ "metadata": None,
+ "role": "user",
+ "member_count": 2,
+ },
+ {
+ "id": "org-x",
+ "display_name": "X",
+ "name": "org-x",
+ "metadata": None,
+ },
+ ],
+ },
+ )
+ # assertEqual ignores key order; the wire order is part of the contract.
+ self.assertEqual(
+ [list(org) for org in response.data["organizations"]],
+ [
+ ["id", "display_name", "name", "metadata", "role", "member_count"],
+ ["id", "display_name", "name", "metadata", "role", "member_count"],
+ ["id", "display_name", "name", "metadata"],
+ ],
+ )
+
+
+class OrganizationListSchemaTests(TestCase):
+ def test_schema_documents_the_fields(self) -> None:
+ schema = SchemaGenerator(patterns=urls.urlpatterns).get_schema(
+ request=None, public=True
+ )
+ org = schema["components"]["schemas"]["GetOrganizationsResponse"]
+ self.assertTrue({"role", "member_count", "region"} <= set(org["properties"]))
+ self.assertEqual(set(org["required"]), {"id", "display_name", "name", "metadata"})
+ for field in ("role", "member_count", "region"):
+ self.assertNotIn("nullable", org["properties"][field])
+ failed = schema["paths"]["/organization"]["get"]["responses"]["412"]
+ body = failed["content"]["application/json"]["schema"]
+ body = schema["components"]["schemas"][body["$ref"].rsplit("/", 1)[1]]
+ self.assertEqual(set(body["properties"]), {"domain", "code"})
+ self.assertEqual(set(body["required"]), {"domain", "code"})
+ operation = schema["paths"]["/organization"]["get"]
+ self.assertEqual(operation["operationId"], "organization_list")
+
+
+@override_settings(REGION="US")
+class OrganizationListEndpointTests(TestCase):
+ """Through the URL and the auth middleware, as a browser calls it."""
+
+ url = "/api/v1/organization"
+
+ def setUp(self) -> None:
+ self.caller = _user("[email protected]")
+ org_a = Organization.objects.create(
+ name="org-a", display_name="Org A", organization_id="org-a"
+ )
+ org_b = Organization.objects.create(
+ name="org-b", display_name="Org B", organization_id="org-b"
+ )
+ for org, user, role in [
+ (org_a, self.caller, "admin"),
+ (org_b, self.caller, "user"),
+ (org_b, _user("[email protected]"), "admin"),
+ ]:
+ OrganizationMember.objects.create(organization=org, user=user, role=role)
+ listed = [
+ OrganizationData(
+ id=o.organization_id, display_name=o.display_name, name=o.name
+ )
+ for o in (org_a, org_b)
+ ]
+ self.list_organizations = MagicMock(return_value=listed)
+ for target, value in [
+ (
+ "account_v2.authentication_controller."
+ "AuthenticationService.user_organizations",
+ self.list_organizations,
+ ),
+ # OSS auth throughout, and no write to the shared cache.
+ (
+ "account_v2.custom_auth_middleware."
+ "AuthenticationPluginRegistry.is_plugin_available",
+ MagicMock(return_value=False),
+ ),
+ (
+ "account_v2.authentication_controller."
+ "AuthenticationPluginRegistry.is_plugin_available",
+ MagicMock(return_value=False),
+ ),
+ (
+ "account_v2.authentication_controller."
+ "CacheService.set_user_organizations",
+ MagicMock(),
+ ),
+ ]:
+ patcher = patch(target, value)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self.addCleanup(UserContext.set_organization_identifier, None)
+
+ def test_signed_in_caller_gets_the_details(self) -> None:
+ # Signed in to org-a, as the browser is when it opens the switcher.
+ self.client.force_login(self.caller)
+ session = self.client.session
+ session["organization"] = "org-a"
+ session.save()
+ response = self.client.get(self.url)
+ self.assertEqual(response.status_code, 200)
+ rows = [
+ (org["id"], org["role"], org["member_count"], org["region"])
+ for org in response.json()["organizations"]
+ ]
+ self.assertEqual(rows, [("org-a", "admin", 1, "US"), ("org-b", "user", 2, "US")])
+
+ def test_anonymous_caller_is_refused(self) -> None:
+ response = self.client.get(self.url)
+ self.assertEqual(response.status_code, 401)
+ self.assertEqual(response.json(), {"message": "Unauthorized"})
+ self.list_organizations.assert_not_called()
diff --git a/backend/account_v2/views.py b/backend/account_v2/views.py
index d68674d71..ef5ce5f75 100644
--- a/backend/account_v2/views.py
+++ b/backend/account_v2/views.py
@@ -2,7 +2,8 @@ import logging
from typing import Any
from django.conf import settings
-from rest_framework import status
+from drf_spectacular.utils import OpenApiResponse, extend_schema, inline_serializer
+from rest_framework import serializers, status
from rest_framework.decorators import api_view
from rest_framework.request import Request
from rest_framework.response import Response
@@ -21,6 +22,7 @@ from account_v2.product_preference import (
set_product_preference,
)
from account_v2.serializer import (
+ GetOrganizationsResponseSerializer,
OrganizationSignupResponseSerializer,
OrganizationSignupSerializer,
ProductPreferenceSerializer,
@@ -79,6 +81,37 @@ def logout(request: Request) -> Response:
return auth_controller.user_logout(request)
+@extend_schema(
+ operation_id="organization_list",
+ tags=["organization"],
+ responses={
+ 200: inline_serializer(
+ "OrganizationListResponse",
+ {
+ "message": serializers.CharField(),
+ "organizations": GetOrganizationsResponseSerializer(many=True),
+ },
+ ),
+ 412: OpenApiResponse(
+ # Describes the body for a known error, which always carries both
+ # keys; for any other error the body is empty, as the description
+ # says. One OpenAPI response can't express both.
+ response=inline_serializer(
+ "OrganizationListFailed",
+ {
+ "domain": serializers.CharField(allow_null=True),
+ "code": serializers.CharField(),
+ },
+ ),
+ description="Listing the organizations failed and the session is "
+ "logged out. For a known authorization error the body carries "
+ "`code` (USF, USR, INE001, INE002 or INS) and `domain`; otherwise "
+ "it is empty.",
+ ),
+ },
+ description="The caller's organizations. See account_v2/ReadMe.md for "
+ "when role, member_count and region are present.",
+)
@api_view(["GET"])
def get_organizations(request: Request) -> Response:
"""get_organizations.