Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Let people change their own display name (PATCH /auth/me)

Simon Flack4eb7a7348912
diff --git a/console/tooling-e2e/surface/exemptions.json b/console/tooling-e2e/surface/exemptions.json
index 974a949e3..d8d7dcea1 100644
--- a/console/tooling-e2e/surface/exemptions.json
+++ b/console/tooling-e2e/surface/exemptions.json
@@ -23,6 +23,7 @@
"GET /gateway/redoc": "FastAPI's generated API documentation; no behaviour of Switch's own to cover.",
"GET /gateway/service-connections/{service}/flows/authorize": "Needs the third-party service's own sign-in page in a browser.",
"GET /gateway/service-connections/{service}/flows/callback": "Needs the third-party service's own sign-in page in a browser.",
+ "PATCH /gateway/auth/me": "Changing your own display name. Covered by core's test_update_me.py against real Postgres; no scenario changes a signed-in user's profile yet.",
"POST /gateway/auth/oidc/exchange": "Needs a code from a live OIDC sign-in; the harness signs in with a password.",
"POST /gateway/chats/{room_id}/agents": "Switch Console group chats. Covered by core's test_chats_groups.py against real Postgres; no scenario drives Console chats yet (every other /gateway/chats route is still in the backlog), and the stacks the harness builds do not turn on the group_chats flag these routes need.",
"POST /gateway/chats/{room_id}/unarchive": "Switch Console archived chats. Covered by core's test_chats_routes.py against real Postgres; no scenario drives Console chats yet (every other /gateway/chats route is still in the backlog).",
diff --git a/console/tooling-e2e/surface/server-surface.json b/console/tooling-e2e/surface/server-surface.json
index f48797e87..16522d0fc 100644
--- a/console/tooling-e2e/surface/server-surface.json
+++ b/console/tooling-e2e/surface/server-surface.json
@@ -940,6 +940,11 @@
"auth": "session",
"flags": []
},
+ {
+ "route": "PATCH /gateway/auth/me",
+ "auth": "session",
+ "flags": []
+ },
{
"route": "PATCH /gateway/collaborations/{bridge_id}",
"auth": "session",
diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.py
index c3df102f0..a1264a28c 100644
--- a/core/switch_core/gateway/auth_routes.py
+++ b/core/switch_core/gateway/auth_routes.py
@@ -84,6 +84,7 @@ from switch_core.gateway.schemas import (
SignupMachine,
SignupRequest,
SignupResponse,
+ UpdateMeRequest,
UserResponse,
)
from switch_core.providers.hosted import HostedControllerSettings
@@ -528,6 +529,23 @@ async def delete_my_account(
return {"ok": True}
[email protected]("/auth/me")
+async def update_me(
+ req: UpdateMeRequest,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ user: Annotated[User, Depends(get_current_user)],
+) -> SessionUserResponse:
+ """Change the signed-in person's display name.
+
+ Like the password change, this writes the `User` that `get_current_user`
+ handed over and commits the session `get_session` handed over, which are
+ the same object within a request.
+ """
+ user.name = req.name
+ await session.commit()
+ return _session_response(user)
+
+
@router.put("/auth/me/password")
async def change_password(
req: ChangePasswordRequest,
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index fac1d44ee..3c523a014 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -963,6 +963,16 @@ class ChangePasswordRequest(BaseModel):
new_password: Password
+class UpdateMeRequest(BaseModel):
+ """The signed-in person's own profile fields. Only the name, for now: the
+ email is the sign-in identity and changes through the account's provider."""
+
+ model_config = ConfigDict(extra="forbid")
+ name: Annotated[
+ str, StringConstraints(strip_whitespace=True, min_length=1, max_length=255)
+ ]
+
+
class DeleteAccountRequest(BaseModel):
"""The account's own email, typed by the person as their confirmation:
an SSO account has no password to ask for."""
diff --git a/core/tests/switch_core/gateway/test_update_me.py b/core/tests/switch_core/gateway/test_update_me.py
new file mode 100644
index 000000000..207e4f9c9
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_update_me.py
@@ -0,0 +1,114 @@
+"""Changing your own display name (PATCH /auth/me), end to end.
+
+Real HTTP against real Postgres, for the same reason as the password change:
+the route writes the `User` that `get_current_user` handed it and commits the
+session `get_session` handed it, so only a read through a fresh session proves
+the write was issued.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import httpx
+from fastapi import FastAPI
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import User
+from switch_core.db.stores.user_store import UserStore
+from switch_core.gateway import dependencies as gw_deps
+from switch_core.gateway.auth import create_jwt
+from switch_core.gateway.auth_routes import router
+from switch_core.keys import Keyring
+
+_SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow
+_KEYRING = Keyring.parse("test:" + _SECRET, legacy_secret=None)
+_USER_STORE = UserStore()
+
+
+def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:
+ async def _session_dep():
+ async with session_factory() as session:
+ yield session
+
+ app = FastAPI()
+ app.include_router(router)
+ app.dependency_overrides[gw_deps.get_session] = _session_dep
+ app.dependency_overrides[gw_deps.get_system_session] = _session_dep
+ app.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factory
+ app.dependency_overrides[gw_deps.get_user_store] = lambda: _USER_STORE
+ app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(
+ keyring=_KEYRING,
+ gateway_cookie_secure=False,
+ gateway_password_login_enabled=True,
+ gateway_tenant_choice_enabled=False,
+ )
+ return app
+
+
+async def _seed_user(
+ session_factory: async_sessionmaker[AsyncSession], email: str
+) -> str:
+ async with session_factory() as session:
+ user = User(name="Ada", email=email, role="user", password_hash=None)
+ await _USER_STORE.create(session, user)
+ await session.commit()
+ return user.id
+
+
+async def _stored_name(
+ session_factory: async_sessionmaker[AsyncSession], user_id: str
+) -> str:
+ async with session_factory() as session:
+ user = await _USER_STORE.get(session, user_id)
+ assert user is not None
+ return user.name
+
+
+def _client(app: FastAPI, user_id: str, email: str) -> httpx.AsyncClient:
+ return httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app),
+ base_url="http://test",
+ cookies={"switch_auth": create_jwt(user_id, email, "user", _KEYRING, None)},
+ )
+
+
+async def test_the_new_name_is_stored_and_answered(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ email = "[email protected]"
+ user_id = await _seed_user(session_factory, email)
+
+ async with _client(_app(session_factory), user_id, email) as client:
+ response = await client.patch("/auth/me", json={"name": " Ada Lovelace "})
+
+ assert response.status_code == 200, response.text
+ assert response.json()["name"] == "Ada Lovelace"
+ assert await _stored_name(session_factory, user_id) == "Ada Lovelace"
+
+
+async def test_a_blank_name_is_refused_and_writes_nothing(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ email = "[email protected]"
+ user_id = await _seed_user(session_factory, email)
+
+ async with _client(_app(session_factory), user_id, email) as client:
+ blank = await client.patch("/auth/me", json={"name": " "})
+ too_long = await client.patch("/auth/me", json={"name": "x" * 256})
+ extra = await client.patch("/auth/me", json={"name": "Bo", "email": "[email protected]"})
+
+ assert blank.status_code == 422
+ assert too_long.status_code == 422
+ assert extra.status_code == 422
+ assert await _stored_name(session_factory, user_id) == "Ada"
+
+
+async def test_signed_out_is_refused(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=_app(session_factory)), base_url="http://test"
+ ) as anonymous:
+ response = await anonymous.patch("/auth/me", json={"name": "Anyone"})
+ assert response.status_code == 401