Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Let users change their own password in the gateway (#323)
Abel Dantascb4266e247c5
diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.pyindex 5229182c3..80529940c 100644--- a/core/switch_core/gateway/auth_routes.py+++ b/core/switch_core/gateway/auth_routes.py@@ -27,6 +27,7 @@ from switch_core.gateway.dependencies import ()from switch_core.gateway.schemas import (AuthConfigResponse,+ ChangePasswordRequest,CreateUserRequest,LinkedIdentity,LoginRequest,@@ -176,6 +177,20 @@ async def my_identities(return linked[email protected]("/auth/me/password")+async def change_password(+ req: ChangePasswordRequest,+ session: Annotated[AsyncSession, Depends(get_session)],+ user: Annotated[User, Depends(get_current_user)],+) -> dict[str, bool]:+ if not verify_password(req.current_password, user.password_hash):+ raise HTTPException(status_code=403, detail="Current password is incorrect")++ user.password_hash = hash_password(req.new_password)+ await session.commit()+ return {"ok": True}++@router.get("/users")async def list_users(session: Annotated[AsyncSession, Depends(get_session)],diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex d0c95411b..35a6bd677 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -653,6 +653,11 @@ class CreateUserRequest(BaseModel):role: str = "user"+class ChangePasswordRequest(BaseModel):+ current_password: str+ new_password: str = Field(min_length=8)++class AuthConfigResponse(BaseModel):# Read unauthenticated by the login page to decide which login methods to# show. `oidc_provider_label` is the button text (e.g. "Okta").diff --git a/core/tests/switch_core/gateway/test_change_password.py b/core/tests/switch_core/gateway/test_change_password.pynew file mode 100644index 000000000..07b883d7d--- /dev/null+++ b/core/tests/switch_core/gateway/test_change_password.py@@ -0,0 +1,100 @@+"""Tests for self-service password change (PUT /auth/me/password).++Exercises the route coroutine directly — same approach as test_auth_refresh.py.+A lightweight async session stub replaces the real DB session so the test runs+without PostgreSQL.+"""++from __future__ import annotations++import pytest+from fastapi import HTTPException+from pydantic import ValidationError++from switch_core.db.models import User+from switch_core.gateway.auth import hash_password, verify_password+from switch_core.gateway.auth_routes import change_password+from switch_core.gateway.schemas import ChangePasswordRequest+++class _FakeSession:+ """Stub that records whether commit was called."""++ def __init__(self) -> None:+ self.committed = False++ async def commit(self) -> None:+ self.committed = True+++def _user(password: str = "old-password-1") -> User:+ return User(+ id="u-1",+ name="Ada",+ email="[email protected]",+ role="user",+ password_hash=hash_password(password),+ )+++async def test_happy_path_changes_password() -> None:+ user = _user()+ session = _FakeSession()+ req = ChangePasswordRequest(+ current_password="old-password-1", new_password="new-password-1"+ )++ result = await change_password(req, session, user) # type: ignore[arg-type]++ assert result == {"ok": True}+ assert session.committed+ assert verify_password("new-password-1", user.password_hash)+ assert not verify_password("old-password-1", user.password_hash)+++async def test_wrong_current_password_returns_403() -> None:+ user = _user()+ session = _FakeSession()+ req = ChangePasswordRequest(+ current_password="wrong-password", new_password="new-password-1"+ )++ with pytest.raises(HTTPException) as exc_info:+ await change_password(req, session, user) # type: ignore[arg-type]++ assert exc_info.value.status_code == 403+ assert not session.committed+++async def test_short_new_password_rejected_by_schema() -> None:+ with pytest.raises(ValidationError) as exc_info:+ ChangePasswordRequest(current_password="old-password-1", new_password="short")++ errors = exc_info.value.errors()+ assert any(e["type"] == "string_too_short" for e in errors)+++async def test_empty_new_password_rejected_by_schema() -> None:+ with pytest.raises(ValidationError):+ ChangePasswordRequest(current_password="old-password-1", new_password="")+++async def test_oidc_user_without_password_hash_returns_403() -> None:+ """OIDC-provisioned users have password_hash=None — changing password must fail cleanly."""+ user = User(+ id="u-2",+ name="Oidc User",+ email="[email protected]",+ role="user",+ password_hash=None,+ )+ session = _FakeSession()+ req = ChangePasswordRequest(+ current_password="anything", new_password="new-password-1"+ )++ with pytest.raises(HTTPException) as exc_info:+ await change_password(req, session, user) # type: ignore[arg-type]++ assert exc_info.value.status_code == 403+ assert not session.committeddiff --git a/gateway/src/data/api.ts b/gateway/src/data/api.tsindex 9838d219a..324a5aab5 100644--- a/gateway/src/data/api.ts+++ b/gateway/src/data/api.ts@@ -202,6 +202,20 @@ export interface UpdateRoomInput {write_visibility?: "public" | "private";}+/** FastAPI's `detail` is a string for HTTPException but an array of+ * validation objects for a 422; render both as text so no error surfaces+ * as "[object Object]". */+function errorText(detail: unknown, fallback: string): string {+ if (typeof detail === "string") return detail;+ if (Array.isArray(detail)) {+ const msgs = detail+ .map((d) => (d && typeof d === "object" && "msg" in d ? String(d.msg) : null))+ .filter((m): m is string => m !== null);+ if (msgs.length > 0) return msgs.join("; ");+ }+ return fallback;+}+async function jsonRequest<T>(path: string,method: string,@@ -215,7 +229,7 @@ async function jsonRequest<T>(});if (!res.ok) {const detail = await res.json().catch(() => null);- throw new Error(detail?.detail ?? `${res.status} ${res.statusText}`);+ throw new Error(errorText(detail?.detail, `${res.status} ${res.statusText}`));}return (await res.json()) as T;}@@ -869,6 +883,16 @@ export function oidcLoginUrl(): string {return `${BASE}/auth/oidc/login`;}+export async function changePassword(+ currentPassword: string,+ newPassword: string,+): Promise<void> {+ await jsonRequest("/auth/me/password", "PUT", {+ current_password: currentPassword,+ new_password: newPassword,+ });+}+export async function fetchUsers(): Promise<UserInfo[] | null> {return fetchJson<UserInfo[]>("/users");}diff --git a/gateway/src/layout/ChangePasswordDialog.tsx b/gateway/src/layout/ChangePasswordDialog.tsxnew file mode 100644index 000000000..919148804--- /dev/null+++ b/gateway/src/layout/ChangePasswordDialog.tsx@@ -0,0 +1,112 @@+import {+ Alert,+ Button,+ CircularProgress,+ Dialog,+ DialogActions,+ DialogContent,+ DialogTitle,+ Stack,+ TextField,+} from "@mui/material";+import { useCallback, useState } from "react";+import { changePassword } from "../data/api";++interface Props {+ open: boolean;+ onClose: () => void;+}++export default function ChangePasswordDialog({ open, onClose }: Props) {+ const [currentPassword, setCurrentPassword] = useState("");+ const [newPassword, setNewPassword] = useState("");+ const [confirmPassword, setConfirmPassword] = useState("");+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [success, setSuccess] = useState(false);++ const reset = useCallback(() => {+ setCurrentPassword("");+ setNewPassword("");+ setConfirmPassword("");+ setError(null);+ setSuccess(false);+ }, []);++ const handleClose = useCallback(() => {+ if (submitting) return;+ reset();+ onClose();+ }, [submitting, reset, onClose]);++ const handleSubmit = useCallback(async () => {+ if (newPassword !== confirmPassword) {+ setError("New passwords do not match");+ return;+ }+ if (newPassword.length < 8) {+ setError("New password must be at least 8 characters");+ return;+ }+ setSubmitting(true);+ setError(null);+ try {+ await changePassword(currentPassword, newPassword);+ setSuccess(true);+ setCurrentPassword("");+ setNewPassword("");+ setConfirmPassword("");+ } catch (err) {+ setError(err instanceof Error ? err.message : "Failed to change password");+ } finally {+ setSubmitting(false);+ }+ }, [currentPassword, newPassword, confirmPassword]);++ return (+ <Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>+ <DialogTitle>Change Password</DialogTitle>+ <DialogContent>+ <Stack spacing={2} sx={{ mt: 1 }}>+ {error && <Alert severity="error">{error}</Alert>}+ {success && <Alert severity="success">Password changed successfully.</Alert>}+ <TextField+ label="Current password"+ type="password"+ autoComplete="current-password"+ value={currentPassword}+ onChange={(e) => setCurrentPassword(e.target.value)}+ required+ />+ <TextField+ label="New password"+ type="password"+ autoComplete="new-password"+ value={newPassword}+ onChange={(e) => setNewPassword(e.target.value)}+ required+ />+ <TextField+ label="Confirm new password"+ type="password"+ autoComplete="new-password"+ value={confirmPassword}+ onChange={(e) => setConfirmPassword(e.target.value)}+ required+ />+ </Stack>+ </DialogContent>+ <DialogActions>+ <Button onClick={handleClose}>Cancel</Button>+ <Button+ variant="contained"+ onClick={handleSubmit}+ disabled={submitting || !currentPassword || !newPassword || !confirmPassword}+ startIcon={submitting ? <CircularProgress size={16} /> : undefined}+ >+ Change Password+ </Button>+ </DialogActions>+ </Dialog>+ );+}diff --git a/gateway/src/layout/NavRail.tsx b/gateway/src/layout/NavRail.tsxindex 49cb89602..c3a161edc 100644--- a/gateway/src/layout/NavRail.tsx+++ b/gateway/src/layout/NavRail.tsx@@ -1,6 +1,7 @@import AccountTreeOutlined from "@mui/icons-material/AccountTreeOutlined";import ChatBubbleOutlineOutlined from "@mui/icons-material/ChatBubbleOutlineOutlined";import FolderOutlined from "@mui/icons-material/FolderOutlined";+import LockOutlined from "@mui/icons-material/LockOutlined";import LogoutOutlined from "@mui/icons-material/LogoutOutlined";import MeetingRoomOutlined from "@mui/icons-material/MeetingRoomOutlined";import PeopleOutlined from "@mui/icons-material/PeopleOutlined";@@ -11,6 +12,7 @@ import { memo, useState } from "react";import { NavLink, useLocation } from "react-router";import type { ComponentType, MouseEvent } from "react";import { useAuth } from "../data/AuthContext";+import ChangePasswordDialog from "./ChangePasswordDialog";import ThemeModeToggle from "./ThemeModeToggle";interface NavItem {@@ -87,6 +89,7 @@ export default memo(function NavRail() {const location = useLocation();const { user, logout } = useAuth();const [anchor, setAnchor] = useState<HTMLElement | null>(null);+ const [passwordDialogOpen, setPasswordDialogOpen] = useState(false);const items = user?.role === "admin" ? [...NAV_ITEMS, ...ADMIN_ITEMS] : NAV_ITEMS;const initial = (user?.email ?? "?").charAt(0).toUpperCase();@@ -209,11 +212,26 @@ export default memo(function NavRail() {<ThemeModeToggle /></Box><Divider sx={{ my: 0.5 }} />+ <MenuItem+ onClick={() => {+ setAnchor(null);+ setPasswordDialogOpen(true);+ }}+ sx={{ gap: 1 }}+ >+ <LockOutlined sx={{ fontSize: 16 }} />+ Change password+ </MenuItem><MenuItem onClick={logout} sx={{ gap: 1 }}><LogoutOutlined sx={{ fontSize: 16 }} />Sign out</MenuItem></Menu>++ <ChangePasswordDialog+ open={passwordDialogOpen}+ onClose={() => setPasswordDialogOpen(false)}+ /></Stack>);});