Skip to content

🙌 OpenHands: AI-Driven Development

fix: user does not immediately appear in org after accepting invite in openhands cloud (#13562)

Hiep Lea75038bee022
diff --git a/enterprise/server/routes/org_invitation_models.py b/enterprise/server/routes/org_invitation_models.py
index 0c04c6de06..5f416aaa78 100644
--- a/enterprise/server/routes/org_invitation_models.py
+++ b/enterprise/server/routes/org_invitation_models.py
@@ -120,3 +120,18 @@ class BatchInvitationResponse(BaseModel):
successful: list[InvitationResponse]
failed: list[InvitationFailure]
+
+
+class AcceptInvitationRequest(BaseModel):
+ """Request model for accepting an invitation via POST."""
+
+ token: str
+
+
+class AcceptInvitationResponse(BaseModel):
+ """Response model for successful invitation acceptance."""
+
+ success: bool
+ org_id: str
+ org_name: str
+ role: str
diff --git a/enterprise/server/routes/org_invitations.py b/enterprise/server/routes/org_invitations.py
index 771b78e91f..de3f8cc058 100644
--- a/enterprise/server/routes/org_invitations.py
+++ b/enterprise/server/routes/org_invitations.py
@@ -5,6 +5,8 @@ from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi.responses import RedirectResponse
from server.routes.org_invitation_models import (
+ AcceptInvitationRequest,
+ AcceptInvitationResponse,
BatchInvitationResponse,
EmailMismatchError,
InsufficientPermissionError,
@@ -17,10 +19,11 @@ from server.routes.org_invitation_models import (
)
from server.services.org_invitation_service import OrgInvitationService
from server.utils.rate_limit_utils import check_rate_limit_by_user_id
+from storage.org_store import OrgStore
+from storage.role_store import RoleStore
from openhands.core.logger import openhands_logger as logger
from openhands.server.user_auth import get_user_id
-from openhands.server.user_auth.user_auth import get_user_auth
# Router for invitation operations on an organization (requires org_id)
invitation_router = APIRouter(prefix='/api/organizations/{org_id}/members')
@@ -123,70 +126,93 @@ async def create_invitation(
@accept_router.get('/accept')
-async def accept_invitation(
+async def accept_invitation_redirect(
token: str,
request: Request,
):
- """Accept an organization invitation via token.
+ """Redirect invitation acceptance to frontend.
This endpoint is accessed via the link in the invitation email.
+ It always redirects to the home page with the invitation token,
+ allowing the frontend to handle the acceptance flow via a modal.
- Flow:
- 1. If user is authenticated: Accept invitation directly and redirect to home
- 2. If user is not authenticated: Redirect to login page with invitation token
- - Frontend stores token and includes it in OAuth state during login
- - After authentication, keycloak_callback processes the invitation
+ This approach works with SameSite='strict' cookies because:
+ - Cross-site navigation (clicking email link) doesn't send cookies
+ - But same-origin POST requests (from frontend) DO send cookies
Args:
token: The invitation token from the email link
request: FastAPI request
Returns:
- RedirectResponse: Redirect to home page on success, or login page if not authenticated,
- or home page with error query params on failure
+ RedirectResponse: Redirect to home page with invitation_token query param
"""
base_url = str(request.base_url).rstrip('/')
- # Try to get user_id from auth (may not be authenticated)
- user_id = None
- try:
- user_auth = await get_user_auth(request)
- if user_auth:
- user_id = await user_auth.get_user_id()
- except Exception:
- pass
-
- if not user_id:
- # User not authenticated - redirect to login page with invitation token
- # Frontend will store the token and include it in OAuth state during login
- logger.info(
- 'Invitation accept: redirecting unauthenticated user to login',
- extra={'token_prefix': token[:10] + '...'},
- )
- login_url = f'{base_url}/login?invitation_token={token}'
- return RedirectResponse(login_url, status_code=302)
+ logger.info(
+ 'Invitation accept: redirecting to frontend for acceptance',
+ extra={'token_prefix': token[:10] + '...'},
+ )
+
+ return RedirectResponse(f'{base_url}/?invitation_token={token}', status_code=302)
+
+
+@accept_router.post('/accept', response_model=AcceptInvitationResponse)
+async def accept_invitation(
+ request_data: AcceptInvitationRequest,
+ user_id: str = Depends(get_user_id),
+):
+ """Accept an organization invitation via authenticated POST request.
+
+ This endpoint is called by the frontend after displaying the acceptance modal.
+ Requires authentication - cookies are sent because this is a same-origin request.
+
+ Args:
+ request_data: Contains the invitation token
+ user_id: Authenticated user ID (from dependency)
+
+ Returns:
+ AcceptInvitationResponse: Success response with organization details
+
+ Raises:
+ HTTPException 400: Invalid or expired token
+ HTTPException 403: Email mismatch
+ HTTPException 409: User already a member
+ """
+ token = request_data.token
- # User is authenticated - process the invitation directly
try:
- await OrgInvitationService.accept_invitation(token, UUID(user_id))
+ invitation = await OrgInvitationService.accept_invitation(token, UUID(user_id))
+
+ # Get organization and role details for response
+ org = await OrgStore.get_org_by_id(invitation.org_id)
+ role = await RoleStore.get_role_by_id(invitation.role_id)
logger.info(
- 'Invitation accepted successfully',
+ 'Invitation accepted via API',
extra={
'token_prefix': token[:10] + '...',
'user_id': user_id,
+ 'org_id': str(invitation.org_id),
},
)
- # Redirect to home page on success
- return RedirectResponse(f'{base_url}/', status_code=302)
+ return AcceptInvitationResponse(
+ success=True,
+ org_id=str(invitation.org_id),
+ org_name=org.name if org else '',
+ role=role.name if role else '',
+ )
except InvitationExpiredError:
logger.warning(
'Invitation accept failed: expired',
extra={'token_prefix': token[:10] + '...', 'user_id': user_id},
)
- return RedirectResponse(f'{base_url}/?invitation_expired=true', status_code=302)
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail='invitation_expired',
+ )
except InvitationInvalidError as e:
logger.warning(
@@ -197,14 +223,20 @@ async def accept_invitation(
'error': str(e),
},
)
- return RedirectResponse(f'{base_url}/?invitation_invalid=true', status_code=302)
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail='invitation_invalid',
+ )
except UserAlreadyMemberError:
logger.info(
'Invitation accept: user already member',
extra={'token_prefix': token[:10] + '...', 'user_id': user_id},
)
- return RedirectResponse(f'{base_url}/?already_member=true', status_code=302)
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail='already_member',
+ )
except EmailMismatchError as e:
logger.warning(
@@ -215,15 +247,21 @@ async def accept_invitation(
'error': str(e),
},
)
- return RedirectResponse(f'{base_url}/?email_mismatch=true', status_code=302)
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail='email_mismatch',
+ )
except Exception as e:
logger.exception(
- 'Unexpected error accepting invitation',
+ 'Unexpected error accepting invitation via API',
extra={
'token_prefix': token[:10] + '...',
'user_id': user_id,
'error': str(e),
},
)
- return RedirectResponse(f'{base_url}/?invitation_error=true', status_code=302)
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail='An unexpected error occurred',
+ )
diff --git a/enterprise/server/utils/url_utils.py b/enterprise/server/utils/url_utils.py
index 5c939dbe8f..61ea369430 100644
--- a/enterprise/server/utils/url_utils.py
+++ b/enterprise/server/utils/url_utils.py
@@ -29,7 +29,10 @@ def get_cookie_domain() -> str | None:
def get_cookie_samesite() -> Literal['lax', 'strict']:
- # for localhost and feature/staging stacks we set it to 'lax' as the cookie domain won't allow 'strict'
+ # Use 'strict' in production for maximum CSRF protection
+ # Use 'lax' for local development and staging environments
+ # Note: For invitation links from emails, the frontend handles acceptance via
+ # an authenticated POST request (same-origin), which works with 'strict' cookies
web_url = get_global_config().web_url
return (
'strict'
diff --git a/enterprise/tests/unit/test_org_invitations_router.py b/enterprise/tests/unit/test_org_invitations_router.py
index cbfbf4c810..acd8424ae9 100644
--- a/enterprise/tests/unit/test_org_invitations_router.py
+++ b/enterprise/tests/unit/test_org_invitations_router.py
@@ -41,191 +41,157 @@ class TestRouterPrefixes:
assert accept_router.prefix == '/api/organizations/members/invite'
-class TestAcceptInvitationEndpoint:
- """Test cases for the accept invitation endpoint."""
+class TestAcceptInvitationGetEndpoint:
+ """Test cases for the GET accept invitation endpoint (redirect flow)."""
+
+ def test_get_accept_redirects_to_home_with_token(self, client):
+ """Test that GET request always redirects to home with invitation_token.
+
+ The GET endpoint is accessed via the link in invitation emails.
+ It always redirects to the home page with the token, allowing the
+ frontend to handle acceptance via a modal with authenticated POST.
+ """
+ response = client.get(
+ '/api/organizations/members/invite/accept?token=inv-test-token-123',
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 302
+ location = response.headers.get('location', '')
+ assert '/?invitation_token=inv-test-token-123' in location
+
+
+class TestAcceptInvitationPostEndpoint:
+ """Test cases for the POST accept invitation endpoint (authenticated flow)."""
@pytest.fixture
- def mock_user_auth(self):
- """Create a mock user auth."""
- user_auth = MagicMock()
- user_auth.get_user_id = AsyncMock(
- return_value='87654321-4321-8765-4321-876543218765'
+ def auth_app(self):
+ """Create a FastAPI app with dependency overrides for authenticated tests."""
+
+ from openhands.server.user_auth import get_user_id
+
+ app = FastAPI()
+ app.include_router(accept_router)
+
+ # Override the get_user_id dependency
+ app.dependency_overrides[get_user_id] = (
+ lambda: '87654321-4321-8765-4321-876543218765'
)
- return user_auth
- @pytest.mark.asyncio
- async def test_accept_unauthenticated_redirects_to_login(self, client):
- """Test that unauthenticated users are redirected to login with invitation token."""
- with patch(
- 'server.routes.org_invitations.get_user_auth',
- new_callable=AsyncMock,
- return_value=None,
- ):
- response = client.get(
- '/api/organizations/members/invite/accept?token=inv-test-token-123',
- follow_redirects=False,
- )
+ return app
- assert response.status_code == 302
- assert '/login?invitation_token=inv-test-token-123' in response.headers.get(
- 'location', ''
- )
+ @pytest.fixture
+ def auth_client(self, auth_app):
+ """Create a test client with authentication dependency overrides."""
+ return TestClient(auth_app)
@pytest.mark.asyncio
- async def test_accept_authenticated_success_redirects_home(
- self, client, mock_user_auth
- ):
- """Test that successful acceptance redirects to home page."""
+ async def test_post_accept_success_returns_org_details(self, auth_client):
+ """Test that successful POST acceptance returns organization details."""
+ from uuid import UUID
+
mock_invitation = MagicMock()
+ mock_invitation.org_id = UUID('12345678-1234-5678-1234-567812345678')
+ mock_invitation.role_id = 3
+
+ mock_org = MagicMock()
+ mock_org.name = 'Test Organization'
+
+ mock_role = MagicMock()
+ mock_role.name = 'member'
with (
- patch(
- 'server.routes.org_invitations.get_user_auth',
- new_callable=AsyncMock,
- return_value=mock_user_auth,
- ),
patch(
'server.routes.org_invitations.OrgInvitationService.accept_invitation',
new_callable=AsyncMock,
return_value=mock_invitation,
),
- ):
- response = client.get(
- '/api/organizations/members/invite/accept?token=inv-test-token-123',
- follow_redirects=False,
- )
-
- assert response.status_code == 302
- location = response.headers.get('location', '')
- assert location.endswith('/')
- assert 'invitation_expired' not in location
- assert 'invitation_invalid' not in location
- assert 'email_mismatch' not in location
-
- @pytest.mark.asyncio
- async def test_accept_expired_invitation_redirects_with_flag(
- self, client, mock_user_auth
- ):
- """Test that expired invitation redirects with invitation_expired=true."""
- with (
patch(
- 'server.routes.org_invitations.get_user_auth',
+ 'server.routes.org_invitations.OrgStore.get_org_by_id',
new_callable=AsyncMock,
- return_value=mock_user_auth,
+ return_value=mock_org,
),
patch(
- 'server.routes.org_invitations.OrgInvitationService.accept_invitation',
+ 'server.routes.org_invitations.RoleStore.get_role_by_id',
new_callable=AsyncMock,
- side_effect=InvitationExpiredError(),
+ return_value=mock_role,
),
):
- response = client.get(
- '/api/organizations/members/invite/accept?token=inv-test-token-123',
- follow_redirects=False,
+ response = auth_client.post(
+ '/api/organizations/members/invite/accept',
+ json={'token': 'inv-test-token-123'},
)
- assert response.status_code == 302
- assert 'invitation_expired=true' in response.headers.get('location', '')
+ assert response.status_code == 200
+ data = response.json()
+ assert data['success'] is True
+ assert data['org_id'] == '12345678-1234-5678-1234-567812345678'
+ assert data['org_name'] == 'Test Organization'
+ assert data['role'] == 'member'
@pytest.mark.asyncio
- async def test_accept_invalid_invitation_redirects_with_flag(
- self, client, mock_user_auth
- ):
- """Test that invalid invitation redirects with invitation_invalid=true."""
- with (
- patch(
- 'server.routes.org_invitations.get_user_auth',
- new_callable=AsyncMock,
- return_value=mock_user_auth,
- ),
- patch(
- 'server.routes.org_invitations.OrgInvitationService.accept_invitation',
- new_callable=AsyncMock,
- side_effect=InvitationInvalidError(),
- ),
+ async def test_post_accept_expired_returns_400(self, auth_client):
+ """Test that expired invitation returns 400 with detail."""
+ with patch(
+ 'server.routes.org_invitations.OrgInvitationService.accept_invitation',
+ new_callable=AsyncMock,
+ side_effect=InvitationExpiredError(),
):
- response = client.get(
- '/api/organizations/members/invite/accept?token=inv-test-token-123',
- follow_redirects=False,
+ response = auth_client.post(
+ '/api/organizations/members/invite/accept',
+ json={'token': 'inv-test-token-123'},
)
- assert response.status_code == 302
- assert 'invitation_invalid=true' in response.headers.get('location', '')
+ assert response.status_code == 400
+ assert response.json()['detail'] == 'invitation_expired'
@pytest.mark.asyncio
- async def test_accept_already_member_redirects_with_flag(
- self, client, mock_user_auth
- ):
- """Test that already member error redirects with already_member=true."""
- with (
- patch(
- 'server.routes.org_invitations.get_user_auth',
- new_callable=AsyncMock,
- return_value=mock_user_auth,
- ),
- patch(
- 'server.routes.org_invitations.OrgInvitationService.accept_invitation',
- new_callable=AsyncMock,
- side_effect=UserAlreadyMemberError(),
- ),
+ async def test_post_accept_invalid_returns_400(self, auth_client):
+ """Test that invalid invitation returns 400 with detail."""
+ with patch(
+ 'server.routes.org_invitations.OrgInvitationService.accept_invitation',
+ new_callable=AsyncMock,
+ side_effect=InvitationInvalidError(),
):
- response = client.get(
- '/api/organizations/members/invite/accept?token=inv-test-token-123',
- follow_redirects=False,
+ response = auth_client.post(
+ '/api/organizations/members/invite/accept',
+ json={'token': 'inv-test-token-123'},
)
- assert response.status_code == 302
- assert 'already_member=true' in response.headers.get('location', '')
+ assert response.status_code == 400
+ assert response.json()['detail'] == 'invitation_invalid'
@pytest.mark.asyncio
- async def test_accept_email_mismatch_redirects_with_flag(
- self, client, mock_user_auth
- ):
- """Test that email mismatch error redirects with email_mismatch=true."""
- with (
- patch(
- 'server.routes.org_invitations.get_user_auth',
- new_callable=AsyncMock,
- return_value=mock_user_auth,
- ),
- patch(
- 'server.routes.org_invitations.OrgInvitationService.accept_invitation',
- new_callable=AsyncMock,
- side_effect=EmailMismatchError(),
- ),
+ async def test_post_accept_already_member_returns_409(self, auth_client):
+ """Test that already member error returns 409 with detail."""
+ with patch(
+ 'server.routes.org_invitations.OrgInvitationService.accept_invitation',
+ new_callable=AsyncMock,
+ side_effect=UserAlreadyMemberError(),
):
- response = client.get(
- '/api/organizations/members/invite/accept?token=inv-test-token-123',
- follow_redirects=False,
+ response = auth_client.post(
+ '/api/organizations/members/invite/accept',
+ json={'token': 'inv-test-token-123'},
)
- assert response.status_code == 302
- assert 'email_mismatch=true' in response.headers.get('location', '')
+ assert response.status_code == 409
+ assert response.json()['detail'] == 'already_member'
@pytest.mark.asyncio
- async def test_accept_unexpected_error_redirects_with_flag(
- self, client, mock_user_auth
- ):
- """Test that unexpected errors redirect with invitation_error=true."""
- with (
- patch(
- 'server.routes.org_invitations.get_user_auth',
- new_callable=AsyncMock,
- return_value=mock_user_auth,
- ),
- patch(
- 'server.routes.org_invitations.OrgInvitationService.accept_invitation',
- new_callable=AsyncMock,
- side_effect=Exception('Unexpected error'),
- ),
+ async def test_post_accept_email_mismatch_returns_403(self, auth_client):
+ """Test that email mismatch error returns 403 with detail."""
+ with patch(
+ 'server.routes.org_invitations.OrgInvitationService.accept_invitation',
+ new_callable=AsyncMock,
+ side_effect=EmailMismatchError(),
):
- response = client.get(
- '/api/organizations/members/invite/accept?token=inv-test-token-123',
- follow_redirects=False,
+ response = auth_client.post(
+ '/api/organizations/members/invite/accept',
+ json={'token': 'inv-test-token-123'},
)
- assert response.status_code == 302
- assert 'invitation_error=true' in response.headers.get('location', '')
+ assert response.status_code == 403
+ assert response.json()['detail'] == 'email_mismatch'
class TestCreateInvitationBatchEndpoint:
diff --git a/frontend/__tests__/components/features/invitations/invitation-accept-modal.test.tsx b/frontend/__tests__/components/features/invitations/invitation-accept-modal.test.tsx
new file mode 100644
index 0000000000..fc3973efd4
--- /dev/null
+++ b/frontend/__tests__/components/features/invitations/invitation-accept-modal.test.tsx
@@ -0,0 +1,321 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { renderWithProviders, createAxiosError } from "test-utils";
+import { InvitationAcceptModal } from "#/components/features/invitations/invitation-accept-modal";
+import { organizationService } from "#/api/organization-service/organization-service.api";
+import * as toastHandlers from "#/utils/custom-toast-handlers";
+
+// Mock the organization service
+vi.mock("#/api/organization-service/organization-service.api", () => ({
+ organizationService: {
+ acceptInvitation: vi.fn(),
+ },
+}));
+
+// Mock toast handlers
+vi.mock("#/utils/custom-toast-handlers", () => ({
+ displaySuccessToast: vi.fn(),
+ displayErrorToast: vi.fn(),
+}));
+
+describe("InvitationAcceptModal", () => {
+ const mockToken = "test-invitation-token-123";
+ const mockOnClose = vi.fn();
+ const mockOnSuccess = vi.fn();
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("should render the modal with title and description", () => {
+ renderWithProviders(
+ <InvitationAcceptModal
+ token={mockToken}
+ onClose={mockOnClose}
+ onSuccess={mockOnSuccess}
+ />,
+ );
+
+ expect(screen.getByTestId("invitation-accept-modal")).toBeInTheDocument();
+ expect(
+ screen.getByText("ORG$INVITATION_ACCEPT_TITLE"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText("ORG$INVITATION_ACCEPT_DESCRIPTION"),
+ ).toBeInTheDocument();
+ });
+
+ it("should render accept and cancel buttons", () => {
+ renderWithProviders(
+ <InvitationAcceptModal
+ token={mockToken}
+ onClose={mockOnClose}
+ onSuccess={mockOnSuccess}
+ />,
+ );
+
+ expect(screen.getByTestId("accept-invitation-button")).toBeInTheDocument();
+ expect(screen.getByTestId("cancel-invitation-button")).toBeInTheDocument();
+ });
+
+ it("should call onClose when cancel button is clicked", async () => {
+ const user = userEvent.setup();
+
+ renderWithProviders(
+ <InvitationAcceptModal
+ token={mockToken}
+ onClose={mockOnClose}
+ onSuccess={mockOnSuccess}
+ />,
+ );
+
+ await user.click(screen.getByTestId("cancel-invitation-button"));
+
+ expect(mockOnClose).toHaveBeenCalledOnce();
+ });
+
+ it("should call acceptInvitation when accept button is clicked", async () => {
+ const user = userEvent.setup();
+ const mockResponse = {
+ success: true,
+ org_id: "org-123",
+ org_name: "Test Organization",
+ role: "member",
+ };
+
+ vi.mocked(organizationService.acceptInvitation).mockResolvedValueOnce(
+ mockResponse,
+ );
+
+ renderWithProviders(
+ <InvitationAcceptModal
+ token={mockToken}
+ onClose={mockOnClose}
+ onSuccess={mockOnSuccess}
+ />,
+ );
+
+ await user.click(screen.getByTestId("accept-invitation-button"));
+
+ await waitFor(() => {
+ expect(organizationService.acceptInvitation).toHaveBeenCalledWith({
+ token: mockToken,
+ });
+ });
+ });
+
+ it("should call onSuccess with org_id and show success toast on successful acceptance", async () => {
+ const user = userEvent.setup();
+ const mockResponse = {
+ success: true,
+ org_id: "org-123",
+ org_name: "Test Organization",
+ role: "member",
+ };
+
+ vi.mocked(organizationService.acceptInvitation).mockResolvedValueOnce(
+ mockResponse,
+ );
+
+ renderWithProviders(
+ <InvitationAcceptModal
+ token={mockToken}
+ onClose={mockOnClose}
+ onSuccess={mockOnSuccess}
+ />,
+ );
+
+ await user.click(screen.getByTestId("accept-invitation-button"));
+
+ await waitFor(() => {
+ expect(mockOnSuccess).toHaveBeenCalledWith({
+ orgId: "org-123",
+ orgName: "Test Organization",
+ isPersonal: false,
+ });
+ });
+
+ expect(toastHandlers.displaySuccessToast).toHaveBeenCalled();
+ });
+
+ it("should show loading spinner and disable buttons while accepting", async () => {
+ const user = userEvent.setup();
+
+ // Create a promise that we can control
+ let resolvePromise: (value: unknown) => void;
+ const pendingPromise = new Promise((resolve) => {
+ resolvePromise = resolve;
+ });
+
+ vi.mocked(organizationService.acceptInvitation).mockReturnValueOnce(
+ pendingPromise as Promise<{
+ success: boolean;
+ org_id: string;
+ org_name: string;
+ role: string;
+ }>,
+ );
+
+ renderWithProviders(
+ <InvitationAcceptModal
+ token={mockToken}
+ onClose={mockOnClose}
+ onSuccess={mockOnSuccess}
+ />,
+ );
+
+ // Click accept to trigger loading state
+ await user.click(screen.getByTestId("accept-invitation-button"));
+
+ // Check loading state
+ await waitFor(() => {
+ expect(screen.getByTestId("loading-spinner")).toBeInTheDocument();
+ });
+ expect(screen.getByTestId("accept-invitation-button")).toBeDisabled();
+ expect(screen.getByTestId("cancel-invitation-button")).toBeDisabled();
+
+ // Resolve the promise to clean up
+ resolvePromise!({
+ success: true,
+ org_id: "org-123",
+ org_name: "Test Organization",
+ role: "member",
+ });
+ });
+
+ describe("error handling", () => {
+ it("should show expired error toast and call onClose when invitation is expired", async () => {
+ const user = userEvent.setup();
+
+ vi.mocked(organizationService.acceptInvitation).mockRejectedValueOnce(
+ createAxiosError(400, "Bad Request", { detail: "invitation_expired" }),
+ );
+
+ renderWithProviders(
+ <InvitationAcceptModal
+ token={mockToken}
+ onClose={mockOnClose}
+ onSuccess={mockOnSuccess}
+ />,
+ );
+
+ await user.click(screen.getByTestId("accept-invitation-button"));
+
+ await waitFor(() => {
+ expect(toastHandlers.displayErrorToast).toHaveBeenCalledWith(
+ "ORG$INVITATION_EXPIRED",
+ );
+ });
+
+ expect(mockOnClose).toHaveBeenCalledOnce();
+ expect(mockOnSuccess).not.toHaveBeenCalled();
+ });
+
+ it("should show invalid error toast and call onClose when invitation is invalid", async () => {
+ const user = userEvent.setup();
+
+ vi.mocked(organizationService.acceptInvitation).mockRejectedValueOnce(
+ createAxiosError(400, "Bad Request", { detail: "invitation_invalid" }),
+ );
+
+ renderWithProviders(
+ <InvitationAcceptModal
+ token={mockToken}
+ onClose={mockOnClose}
+ onSuccess={mockOnSuccess}
+ />,
+ );
+
+ await user.click(screen.getByTestId("accept-invitation-button"));
+
+ await waitFor(() => {
+ expect(toastHandlers.displayErrorToast).toHaveBeenCalledWith(
+ "ORG$INVITATION_INVALID",
+ );
+ });
+
+ expect(mockOnClose).toHaveBeenCalledOnce();
+ });
+
+ it("should show already member error toast when user is already a member", async () => {
+ const user = userEvent.setup();
+
+ vi.mocked(organizationService.acceptInvitation).mockRejectedValueOnce(
+ createAxiosError(409, "Conflict", { detail: "already_member" }),
+ );
+
+ renderWithProviders(
+ <InvitationAcceptModal
+ token={mockToken}
+ onClose={mockOnClose}
+ onSuccess={mockOnSuccess}
+ />,
+ );
+
+ await user.click(screen.getByTestId("accept-invitation-button"));
+
+ await waitFor(() => {
+ expect(toastHandlers.displayErrorToast).toHaveBeenCalledWith(
+ "ORG$ALREADY_MEMBER",
+ );
+ });
+
+ expect(mockOnClose).toHaveBeenCalledOnce();
+ });
+
+ it("should show email mismatch error toast when email does not match", async () => {
+ const user = userEvent.setup();
+
+ vi.mocked(organizationService.acceptInvitation).mockRejectedValueOnce(
+ createAxiosError(403, "Forbidden", { detail: "email_mismatch" }),
+ );
+
+ renderWithProviders(
+ <InvitationAcceptModal
+ token={mockToken}
+ onClose={mockOnClose}
+ onSuccess={mockOnSuccess}
+ />,
+ );
+
+ await user.click(screen.getByTestId("accept-invitation-button"));
+
+ await waitFor(() => {
+ expect(toastHandlers.displayErrorToast).toHaveBeenCalledWith(
+ "ORG$INVITATION_EMAIL_MISMATCH",
+ );
+ });
+
+ expect(mockOnClose).toHaveBeenCalledOnce();
+ });
+
+ it("should show generic error toast for unknown errors", async () => {
+ const user = userEvent.setup();
+
+ vi.mocked(organizationService.acceptInvitation).mockRejectedValueOnce(
+ createAxiosError(500, "Internal Server Error", {
+ detail: "unexpected_error",
+ }),
+ );
+
+ renderWithProviders(
+ <InvitationAcceptModal
+ token={mockToken}
+ onClose={mockOnClose}
+ onSuccess={mockOnSuccess}
+ />,
+ );
+
+ await user.click(screen.getByTestId("accept-invitation-button"));
+
+ await waitFor(() => {
+ expect(toastHandlers.displayErrorToast).toHaveBeenCalledWith(
+ "ORG$INVITATION_ACCEPT_ERROR",
+ );
+ });
+
+ expect(mockOnClose).toHaveBeenCalledOnce();
+ });
+ });
+});
diff --git a/frontend/src/api/organization-service/organization-service.api.ts b/frontend/src/api/organization-service/organization-service.api.ts
index 690adbac50..36a424e07f 100644
--- a/frontend/src/api/organization-service/organization-service.api.ts
+++ b/frontend/src/api/organization-service/organization-service.api.ts
@@ -156,4 +156,15 @@ export const organizationService = {
);
return data;
},
+
+ acceptInvitation: async ({ token }: { token: string }) => {
+ const { data } = await openHands.post<{
+ success: boolean;
+ org_id: string;
+ org_name: string;
+ role: string;
+ }>("/api/organizations/members/invite/accept", { token });
+
+ return data;
+ },
};
diff --git a/frontend/src/components/features/invitations/invitation-accept-modal.tsx b/frontend/src/components/features/invitations/invitation-accept-modal.tsx
new file mode 100644
index 0000000000..d0e17dad06
--- /dev/null
+++ b/frontend/src/components/features/invitations/invitation-accept-modal.tsx
@@ -0,0 +1,118 @@
+import { AxiosError } from "axios";
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { LoadingSpinner } from "#/components/shared/loading-spinner";
+import {
+ useAcceptInvitation,
+ getInvitationErrorCode,
+} from "#/hooks/mutation/use-accept-invitation";
+import {
+ displayErrorToast,
+ displaySuccessToast,
+} from "#/utils/custom-toast-handlers";
+
+interface InvitationAcceptModalProps {
+ token: string;
+ onClose: () => void;
+ onSuccess: (payload: {
+ orgId: string;
+ orgName: string;
+ isPersonal: boolean;
+ }) => void;
+}
+
+export function InvitationAcceptModal({
+ token,
+ onClose,
+ onSuccess,
+}: InvitationAcceptModalProps) {
+ const { t } = useTranslation();
+ const { mutate: acceptInvitation, isPending } = useAcceptInvitation();
+
+ const getErrorMessage = (errorCode: string | null): string => {
+ switch (errorCode) {
+ case "invitation_expired":
+ return t(I18nKey.ORG$INVITATION_EXPIRED);
+ case "invitation_invalid":
+ return t(I18nKey.ORG$INVITATION_INVALID);
+ case "already_member":
+ return t(I18nKey.ORG$ALREADY_MEMBER);
+ case "email_mismatch":
+ return t(I18nKey.ORG$INVITATION_EMAIL_MISMATCH);
+ default:
+ return t(I18nKey.ORG$INVITATION_ACCEPT_ERROR);
+ }
+ };
+
+ const handleAccept = () => {
+ acceptInvitation(
+ { token },
+ {
+ onSuccess: (data) => {
+ displaySuccessToast(
+ t(I18nKey.ORG$INVITATION_ACCEPTED_SUCCESS, {
+ orgName: data.org_name,
+ }),
+ );
+ onSuccess({
+ orgId: data.org_id,
+ orgName: data.org_name,
+ isPersonal: false,
+ });
+ },
+ onError: (error) => {
+ const errorCode = getInvitationErrorCode(
+ error as AxiosError<{ detail: string }>,
+ );
+ displayErrorToast(getErrorMessage(errorCode));
+ onClose();
+ },
+ },
+ );
+ };
+
+ return (
+ <ModalBackdrop onClose={onClose} aria-label="Accept invitation">
+ <div
+ data-testid="invitation-accept-modal"
+ className="bg-base-secondary p-6 rounded-xl flex flex-col gap-4 border border-tertiary"
+ style={{ width: "500px" }}
+ >
+ <h3 className="text-xl font-bold">
+ {t(I18nKey.ORG$INVITATION_ACCEPT_TITLE)}
+ </h3>
+ <p className="text-sm text-gray-300">
+ {t(I18nKey.ORG$INVITATION_ACCEPT_DESCRIPTION)}
+ </p>
+ <div className="w-full flex gap-2 mt-2">
+ <BrandButton
+ testId="accept-invitation-button"
+ type="button"
+ variant="primary"
+ className="grow flex items-center justify-center"
+ onClick={handleAccept}
+ isDisabled={isPending}
+ >
+ {isPending ? (
+ <LoadingSpinner size="small" />
+ ) : (
+ t(I18nKey.BUTTON$CONFIRM)
+ )}
+ </BrandButton>
+ <BrandButton
+ testId="cancel-invitation-button"
+ type="button"
+ variant="secondary"
+ className="grow"
+ onClick={onClose}
+ isDisabled={isPending}
+ >
+ {t(I18nKey.BUTTON$CANCEL)}
+ </BrandButton>
+ </div>
+ </div>
+ </ModalBackdrop>
+ );
+}
diff --git a/frontend/src/hooks/mutation/use-accept-invitation.ts b/frontend/src/hooks/mutation/use-accept-invitation.ts
new file mode 100644
index 0000000000..886073d760
--- /dev/null
+++ b/frontend/src/hooks/mutation/use-accept-invitation.ts
@@ -0,0 +1,36 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { AxiosError } from "axios";
+import { organizationService } from "#/api/organization-service/organization-service.api";
+
+interface AcceptInvitationError {
+ detail: string;
+}
+
+export const useAcceptInvitation = () => {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: ({ token }: { token: string }) =>
+ organizationService.acceptInvitation({ token }),
+ onSuccess: () => {
+ // Invalidate organizations query to refresh the list
+ queryClient.invalidateQueries({ queryKey: ["organizations"] });
+ },
+ // Note: Error handling is done in the component to allow for custom messages
+ // based on the error code
+ });
+};
+
+/**
+ * Extract the error code from an invitation acceptance error.
+ * @param error The Axios error from the accept invitation mutation
+ * @returns The error code string (e.g., 'invitation_expired', 'already_member')
+ */
+export const getInvitationErrorCode = (
+ error: AxiosError<AcceptInvitationError>,
+): string | null => {
+ if (error.response?.data?.detail) {
+ return error.response.data.detail;
+ }
+ return null;
+};
diff --git a/frontend/src/i18n/declaration.ts b/frontend/src/i18n/declaration.ts
index d6e5a58c71..7529891668 100644
--- a/frontend/src/i18n/declaration.ts
+++ b/frontend/src/i18n/declaration.ts
@@ -1151,6 +1151,14 @@ export enum I18nKey {
ORG$NO_MEMBERS_FOUND = "ORG$NO_MEMBERS_FOUND",
ORG$NO_MEMBERS_MATCHING_FILTER = "ORG$NO_MEMBERS_MATCHING_FILTER",
ORG$FAILED_TO_LOAD_MEMBERS = "ORG$FAILED_TO_LOAD_MEMBERS",
+ ORG$INVITATION_ACCEPT_TITLE = "ORG$INVITATION_ACCEPT_TITLE",
+ ORG$INVITATION_ACCEPT_DESCRIPTION = "ORG$INVITATION_ACCEPT_DESCRIPTION",
+ ORG$INVITATION_ACCEPTED_SUCCESS = "ORG$INVITATION_ACCEPTED_SUCCESS",
+ ORG$INVITATION_EXPIRED = "ORG$INVITATION_EXPIRED",
+ ORG$INVITATION_INVALID = "ORG$INVITATION_INVALID",
+ ORG$ALREADY_MEMBER = "ORG$ALREADY_MEMBER",
+ ORG$INVITATION_EMAIL_MISMATCH = "ORG$INVITATION_EMAIL_MISMATCH",
+ ORG$INVITATION_ACCEPT_ERROR = "ORG$INVITATION_ACCEPT_ERROR",
ONBOARDING$ORG_NAME_QUESTION = "ONBOARDING$ORG_NAME_QUESTION",
ONBOARDING$ORG_NAME_INPUT_NAME = "ONBOARDING$ORG_NAME_INPUT_NAME",
ONBOARDING$ORG_NAME_INPUT_DOMAIN = "ONBOARDING$ORG_NAME_INPUT_DOMAIN",
diff --git a/frontend/src/i18n/translation.json b/frontend/src/i18n/translation.json
index 9d41f33e43..f6899d2e05 100644
--- a/frontend/src/i18n/translation.json
+++ b/frontend/src/i18n/translation.json
@@ -19568,6 +19568,142 @@
"uk": "Не вдалося завантажити членів",
"ca": "No s'han pogut carregar els membres"
},
+ "ORG$INVITATION_ACCEPT_TITLE": {
+ "en": "Join Organization",
+ "ja": "組織に参加",
+ "zh-CN": "加入组织",
+ "zh-TW": "加入組織",
+ "ko-KR": "조직 가입",
+ "no": "Bli med i organisasjon",
+ "ar": "الانضمام إلى المنظمة",
+ "de": "Organisation beitreten",
+ "fr": "Rejoindre l'organisation",
+ "it": "Unisciti all'organizzazione",
+ "pt": "Entrar na organização",
+ "es": "Unirse a la organización",
+ "tr": "Organizasyona Katıl",
+ "uk": "Приєднатися до організації",
+ "ca": "Unir-se a l'organització"
+ },
+ "ORG$INVITATION_ACCEPT_DESCRIPTION": {
+ "en": "You have been invited to join an organization. Would you like to accept this invitation?",
+ "ja": "組織への参加招待を受けました。この招待を受け入れますか?",
+ "zh-CN": "您已被邀请加入一个组织。您想接受此邀请吗?",
+ "zh-TW": "您已被邀請加入一個組織。您想接受此邀請嗎?",
+ "ko-KR": "조직에 가입하라는 초대를 받았습니다. 이 초대를 수락하시겠습니까?",
+ "no": "Du har blitt invitert til å bli med i en organisasjon. Vil du godta denne invitasjonen?",
+ "ar": "لقد تمت دعوتك للانضمام إلى منظمة. هل تريد قبول هذه الدعوة؟",
+ "de": "Sie wurden eingeladen, einer Organisation beizutreten. Möchten Sie diese Einladung annehmen?",
+ "fr": "Vous avez été invité à rejoindre une organisation. Souhaitez-vous accepter cette invitation ?",
+ "it": "Sei stato invitato a unirti a un'organizzazione. Vuoi accettare questo invito?",
+ "pt": "Você foi convidado para entrar em uma organização. Gostaria de aceitar este convite?",
+ "es": "Has sido invitado a unirte a una organización. ¿Te gustaría aceptar esta invitación?",
+ "tr": "Bir organizasyona katılmaya davet edildiniz. Bu daveti kabul etmek ister misiniz?",
+ "uk": "Вас запросили приєднатися до організації. Бажаєте прийняти це запрошення?",
+ "ca": "Heu estat convidat a unir-vos a una organització. Voleu acceptar aquesta invitació?"
+ },
+ "ORG$INVITATION_ACCEPTED_SUCCESS": {
+ "en": "Successfully joined {{orgName}}",
+ "ja": "{{orgName}}に正常に参加しました",
+ "zh-CN": "成功加入 {{orgName}}",
+ "zh-TW": "成功加入 {{orgName}}",
+ "ko-KR": "{{orgName}}에 성공적으로 가입했습니다",
+ "no": "Ble med i {{orgName}}",
+ "ar": "تم الانضمام بنجاح إلى {{orgName}}",
+ "de": "Erfolgreich {{orgName}} beigetreten",
+ "fr": "Vous avez rejoint {{orgName}} avec succès",
+ "it": "Ti sei unito con successo a {{orgName}}",
+ "pt": "Entrou com sucesso em {{orgName}}",
+ "es": "Te has unido exitosamente a {{orgName}}",
+ "tr": "{{orgName}} organizasyonuna başarıyla katıldınız",
+ "uk": "Успішно приєднано до {{orgName}}",
+ "ca": "Us heu unit amb èxit a {{orgName}}"
+ },
+ "ORG$INVITATION_EXPIRED": {
+ "en": "This invitation has expired",
+ "ja": "この招待は期限切れです",
+ "zh-CN": "此邀请已过期",
+ "zh-TW": "此邀請已過期",
+ "ko-KR": "이 초대가 만료되었습니다",
+ "no": "Denne invitasjonen har utløpt",
+ "ar": "انتهت صلاحية هذه الدعوة",
+ "de": "Diese Einladung ist abgelaufen",
+ "fr": "Cette invitation a expiré",
+ "it": "Questo invito è scaduto",
+ "pt": "Este convite expirou",
+ "es": "Esta invitación ha expirado",
+ "tr": "Bu davet süresi doldu",
+ "uk": "Термін дії цього запрошення закінчився",
+ "ca": "Aquesta invitació ha caducat"
+ },
+ "ORG$INVITATION_INVALID": {
+ "en": "This invitation is no longer valid",
+ "ja": "この招待はもう有効ではありません",
+ "zh-CN": "此邀请不再有效",
+ "zh-TW": "此邀請不再有效",
+ "ko-KR": "이 초대는 더 이상 유효하지 않습니다",
+ "no": "Denne invitasjonen er ikke lenger gyldig",
+ "ar": "هذه الدعوة لم تعد صالحة",
+ "de": "Diese Einladung ist nicht mehr gültig",
+ "fr": "Cette invitation n'est plus valide",
+ "it": "Questo invito non è più valido",
+ "pt": "Este convite não é mais válido",
+ "es": "Esta invitación ya no es válida",
+ "tr": "Bu davet artık geçerli değil",
+ "uk": "Це запрошення більше не дійсне",
+ "ca": "Aquesta invitació ja no és vàlida"
+ },
+ "ORG$ALREADY_MEMBER": {
+ "en": "You are already a member of this organization",
+ "ja": "あなたはすでにこの組織のメンバーです",
+ "zh-CN": "您已经是此组织的成员",
+ "zh-TW": "您已經是此組織的成員",
+ "ko-KR": "이미 이 조직의 멤버입니다",
+ "no": "Du er allerede medlem av denne organisasjonen",
+ "ar": "أنت بالفعل عضو في هذه المنظمة",
+ "de": "Sie sind bereits Mitglied dieser Organisation",
+ "fr": "Vous êtes déjà membre de cette organisation",
+ "it": "Sei già membro di questa organizzazione",
+ "pt": "Você já é membro desta organização",
+ "es": "Ya eres miembro de esta organización",
+ "tr": "Zaten bu organizasyonun bir üyesisiniz",
+ "uk": "Ви вже є членом цієї організації",
+ "ca": "Ja sou membre d'aquesta organització"
+ },
+ "ORG$INVITATION_EMAIL_MISMATCH": {
+ "en": "Your email does not match the invitation",
+ "ja": "メールアドレスが招待と一致しません",
+ "zh-CN": "您的邮箱与邀请不匹配",
+ "zh-TW": "您的電子郵件與邀請不符",
+ "ko-KR": "이메일이 초대와 일치하지 않습니다",
+ "no": "E-posten din samsvarer ikke med invitasjonen",
+ "ar": "بريدك الإلكتروني لا يتطابق مع الدعوة",
+ "de": "Ihre E-Mail stimmt nicht mit der Einladung überein",
+ "fr": "Votre email ne correspond pas à l'invitation",
+ "it": "La tua email non corrisponde all'invito",
+ "pt": "Seu email não corresponde ao convite",
+ "es": "Tu correo electrónico no coincide con la invitación",
+ "tr": "E-postanız davetle eşleşmiyor",
+ "uk": "Ваша електронна пошта не відповідає запрошенню",
+ "ca": "El vostre correu electrònic no coincideix amb la invitació"
+ },
+ "ORG$INVITATION_ACCEPT_ERROR": {
+ "en": "Failed to accept invitation",
+ "ja": "招待の承認に失敗しました",
+ "zh-CN": "接受邀请失败",
+ "zh-TW": "接受邀請失敗",
+ "ko-KR": "초대 수락에 실패했습니다",
+ "no": "Kunne ikke godta invitasjonen",
+ "ar": "فشل قبول الدعوة",
+ "de": "Einladung konnte nicht angenommen werden",
+ "fr": "Échec de l'acceptation de l'invitation",
+ "it": "Impossibile accettare l'invito",
+ "pt": "Falha ao aceitar o convite",
+ "es": "Error al aceptar la invitación",
+ "tr": "Davet kabul edilemedi",
+ "uk": "Не вдалося прийняти запрошення",
+ "ca": "No s'ha pogut acceptar la invitació"
+ },
"ONBOARDING$ORG_NAME_QUESTION": {
"en": "What's the name of your organization?",
"ja": "あなたの組織の名前は?",
diff --git a/frontend/src/routes/root-layout.tsx b/frontend/src/routes/root-layout.tsx
index b61c281379..636ae85c11 100644
--- a/frontend/src/routes/root-layout.tsx
+++ b/frontend/src/routes/root-layout.tsx
@@ -30,6 +30,9 @@ import { AlertBanner } from "#/components/features/alerts/alert-banner";
import { cn } from "#/utils/utils";
import { LoadingSpinner } from "#/components/shared/loading-spinner";
import { useAppTitle } from "#/hooks/use-app-title";
+import { useInvitation } from "#/hooks/use-invitation";
+import { InvitationAcceptModal } from "#/components/features/invitations/invitation-accept-modal";
+import { useSwitchOrganization } from "#/hooks/mutation/use-switch-organization";
export function ErrorBoundary() {
const error = useRouteError();
@@ -84,6 +87,11 @@ export default function MainApp() {
const [consentFormIsOpen, setConsentFormIsOpen] = React.useState(false);
+ // Invitation acceptance modal state
+ const { invitationToken, clearInvitation } = useInvitation();
+ const { mutate: switchOrganization } = useSwitchOrganization();
+ const [showInvitationModal, setShowInvitationModal] = React.useState(false);
+
// Auto-login if login method is stored in local storage
useAutoLogin();
@@ -134,6 +142,28 @@ export default function MainApp() {
}
}, [settings?.is_new_user, config.data?.app_mode]);
+ // Show invitation modal when authenticated and has invitation token
+ React.useEffect(() => {
+ if (isAuthed && invitationToken && !isOnIntermediatePage) {
+ setShowInvitationModal(true);
+ }
+ }, [isAuthed, invitationToken, isOnIntermediatePage]);
+
+ const handleInvitationClose = React.useCallback(() => {
+ setShowInvitationModal(false);
+ clearInvitation();
+ }, [clearInvitation]);
+
+ const handleInvitationSuccess = React.useCallback(
+ (payload: { orgId: string; orgName: string; isPersonal: boolean }) => {
+ setShowInvitationModal(false);
+ clearInvitation();
+ // Switch to the newly joined organization
+ switchOrganization(payload);
+ },
+ [clearInvitation, switchOrganization],
+ );
+
// Function to check if login method exists in local storage
const checkLoginMethodExists = React.useCallback(() => {
// Only check localStorage if we're in a browser environment
@@ -262,6 +292,13 @@ export default function MainApp() {
}}
/>
)}
+ {showInvitationModal && invitationToken && (
+ <InvitationAcceptModal
+ token={invitationToken}
+ onClose={handleInvitationClose}
+ onSuccess={handleInvitationSuccess}
+ />
+ )}
</div>
);
}