feat: bootstrap 2 users, tenant, org-scoped tokens, platform admin UI
Bootstrap script now creates: - SaaS Owner (admin/admin) with platform-admin role - Tenant Admin (camel/camel) in Example Tenant org - Traditional Web App for cameleer3-server OIDC - DB records: tenant, default environment, license - Configures cameleer3-server OIDC via its admin API All credentials configurable via env vars. Backend: - Fix LogtoManagementClient resource URL (https://default.logto.app/api) - Add getUserRoles/getUserOrganizations to LogtoManagementClient - Add GET /api/me endpoint (user info, platform admin status, tenants) - Add GET /api/tenants list-all for platform admins - Remove insecure X-header forwarding from Traefik Frontend: - Org-scoped tokens: getAccessToken(resource, orgId) for tenant context - OrgResolver component populates org store from /api/me - useOrganization Zustand store (currentOrgId + currentTenantId) - Platform admin sidebar section + AdminTenantsPage - View Dashboard link points to cameleer3-server on port 8081 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -3,7 +3,7 @@ import { api } from './client';
|
||||
import type {
|
||||
TenantResponse, EnvironmentResponse, AppResponse,
|
||||
DeploymentResponse, LicenseResponse, AgentStatusResponse,
|
||||
ObservabilityStatusResponse, LogEntry,
|
||||
ObservabilityStatusResponse, LogEntry, MeResponse,
|
||||
} from '../types/api';
|
||||
|
||||
// Tenant
|
||||
@@ -183,3 +183,19 @@ export function useLogs(appId: string, params?: { since?: string; limit?: number
|
||||
enabled: !!appId,
|
||||
});
|
||||
}
|
||||
|
||||
// Platform
|
||||
export function useMe() {
|
||||
return useQuery({
|
||||
queryKey: ['me'],
|
||||
queryFn: () => api.get<MeResponse>('/me'),
|
||||
staleTime: 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useAllTenants() {
|
||||
return useQuery({
|
||||
queryKey: ['tenants', 'all'],
|
||||
queryFn: () => api.get<TenantResponse[]>('/tenants'),
|
||||
});
|
||||
}
|
||||
|
||||
47
ui/src/auth/OrgResolver.tsx
Normal file
47
ui/src/auth/OrgResolver.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import { useEffect } from 'react';
|
||||
import { Spinner } from '@cameleer/design-system';
|
||||
import { useMe } from '../api/hooks';
|
||||
import { useOrgStore } from './useOrganization';
|
||||
|
||||
/**
|
||||
* Fetches /api/me and populates the org store with platform admin status
|
||||
* and tenant-to-org mapping. Renders children once resolved.
|
||||
*/
|
||||
export function OrgResolver({ children }: { children: React.ReactNode }) {
|
||||
const { data: me, isLoading, isError } = useMe();
|
||||
const { setIsPlatformAdmin, setOrganizations, setCurrentOrg, currentOrgId } = useOrgStore();
|
||||
|
||||
useEffect(() => {
|
||||
if (!me) return;
|
||||
|
||||
setIsPlatformAdmin(me.isPlatformAdmin);
|
||||
|
||||
// Map tenants: logtoOrgId is the org ID for token scoping, id is the DB UUID
|
||||
const orgEntries = me.tenants.map((t) => ({
|
||||
id: t.logtoOrgId,
|
||||
name: t.name,
|
||||
slug: t.slug,
|
||||
tenantId: t.id,
|
||||
}));
|
||||
setOrganizations(orgEntries);
|
||||
|
||||
// Auto-select if single tenant and no org selected yet
|
||||
if (orgEntries.length === 1 && !currentOrgId) {
|
||||
setCurrentOrg(orgEntries[0].id);
|
||||
}
|
||||
}, [me]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh' }}>
|
||||
<Spinner />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useLogto } from '@logto/react';
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useOrgStore } from './useOrganization';
|
||||
|
||||
interface IdTokenClaims {
|
||||
sub?: string;
|
||||
@@ -14,6 +15,7 @@ interface IdTokenClaims {
|
||||
export function useAuth() {
|
||||
const { isAuthenticated, isLoading, getIdTokenClaims, signOut, signIn } = useLogto();
|
||||
const [claims, setClaims] = useState<IdTokenClaims | null>(null);
|
||||
const { currentTenantId, isPlatformAdmin } = useOrgStore();
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuthenticated) {
|
||||
@@ -25,7 +27,8 @@ export function useAuth() {
|
||||
|
||||
const username = claims?.username ?? claims?.name ?? claims?.email ?? claims?.sub ?? null;
|
||||
const roles = (claims?.roles as string[]) ?? [];
|
||||
const tenantId = (claims?.organization_id as string) ?? null;
|
||||
// tenantId is the DB UUID from the org store (set by OrgResolver after /api/me)
|
||||
const tenantId = currentTenantId;
|
||||
|
||||
const logout = useCallback(() => {
|
||||
signOut(window.location.origin + '/login');
|
||||
@@ -37,6 +40,7 @@ export function useAuth() {
|
||||
username,
|
||||
roles,
|
||||
tenantId,
|
||||
isPlatformAdmin,
|
||||
logout,
|
||||
signIn,
|
||||
};
|
||||
|
||||
31
ui/src/auth/useOrganization.ts
Normal file
31
ui/src/auth/useOrganization.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { create } from 'zustand';
|
||||
|
||||
export interface OrgInfo {
|
||||
id: string; // Logto org ID (for token scoping)
|
||||
name: string;
|
||||
slug?: string;
|
||||
tenantId?: string; // DB tenant UUID (for API calls)
|
||||
}
|
||||
|
||||
interface OrgState {
|
||||
currentOrgId: string | null; // Logto org ID — used for getAccessToken(resource, orgId)
|
||||
currentTenantId: string | null; // DB UUID — used for API calls like /api/tenants/{id}
|
||||
organizations: OrgInfo[];
|
||||
isPlatformAdmin: boolean;
|
||||
setCurrentOrg: (orgId: string | null) => void;
|
||||
setOrganizations: (orgs: OrgInfo[]) => void;
|
||||
setIsPlatformAdmin: (value: boolean) => void;
|
||||
}
|
||||
|
||||
export const useOrgStore = create<OrgState>((set, get) => ({
|
||||
currentOrgId: null,
|
||||
currentTenantId: null,
|
||||
organizations: [],
|
||||
isPlatformAdmin: false,
|
||||
setCurrentOrg: (orgId) => {
|
||||
const org = get().organizations.find((o) => o.id === orgId);
|
||||
set({ currentOrgId: orgId, currentTenantId: org?.tenantId ?? null });
|
||||
},
|
||||
setOrganizations: (orgs) => set({ organizations: orgs }),
|
||||
setIsPlatformAdmin: (value) => set({ isPlatformAdmin: value }),
|
||||
}));
|
||||
@@ -89,9 +89,18 @@ function UserIcon() {
|
||||
);
|
||||
}
|
||||
|
||||
function PlatformIcon() {
|
||||
return (
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
|
||||
<path d="M8 1l6 3.5v7L8 15l-6-3.5v-7L8 1z" stroke="currentColor" strokeWidth="1.5" />
|
||||
<path d="M8 1v14M2 4.5L14 4.5M2 11.5L14 11.5" stroke="currentColor" strokeWidth="1" opacity="0.4" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function Layout() {
|
||||
const navigate = useNavigate();
|
||||
const { username, logout } = useAuth();
|
||||
const { username, logout, isPlatformAdmin } = useAuth();
|
||||
|
||||
const [envSectionOpen, setEnvSectionOpen] = useState(true);
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
@@ -134,12 +143,24 @@ export function Layout() {
|
||||
{null}
|
||||
</Sidebar.Section>
|
||||
|
||||
{/* Platform Admin section */}
|
||||
{isPlatformAdmin && (
|
||||
<Sidebar.Section
|
||||
icon={<PlatformIcon />}
|
||||
label="Platform"
|
||||
open={false}
|
||||
onToggle={() => navigate('/admin/tenants')}
|
||||
>
|
||||
{null}
|
||||
</Sidebar.Section>
|
||||
)}
|
||||
|
||||
<Sidebar.Footer>
|
||||
{/* Link to the observability SPA (external) */}
|
||||
{/* Link to the observability SPA (direct port, not via Traefik prefix) */}
|
||||
<Sidebar.FooterLink
|
||||
icon={<ObsIcon />}
|
||||
label="View Dashboard"
|
||||
onClick={() => window.open('/dashboard', '_blank', 'noopener')}
|
||||
onClick={() => window.open('http://localhost:8081', '_blank', 'noopener')}
|
||||
/>
|
||||
|
||||
{/* User info + logout */}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { LogtoProvider, useLogto } from '@logto/react';
|
||||
import { LogtoProvider, UserScope, useLogto } from '@logto/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { BrowserRouter } from 'react-router';
|
||||
import { ThemeProvider, ToastProvider, BreadcrumbProvider, GlobalFilterProvider, CommandPaletteProvider, Spinner } from '@cameleer/design-system';
|
||||
@@ -8,6 +8,7 @@ import '@cameleer/design-system/style.css';
|
||||
import { AppRouter } from './router';
|
||||
import { fetchConfig } from './config';
|
||||
import { setTokenProvider, setLogoutHandler } from './api/client';
|
||||
import { useOrgStore } from './auth/useOrganization';
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
@@ -19,15 +20,44 @@ const queryClient = new QueryClient({
|
||||
});
|
||||
|
||||
function TokenSync({ resource }: { resource: string }) {
|
||||
const { getAccessToken, isAuthenticated, signOut } = useLogto();
|
||||
const { getAccessToken, isAuthenticated, signOut, fetchUserInfo } = useLogto();
|
||||
const { currentOrgId, setCurrentOrg, setOrganizations } = useOrgStore();
|
||||
|
||||
// After auth, resolve user's organizations from Logto
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) {
|
||||
setOrganizations([]);
|
||||
setCurrentOrg(null);
|
||||
return;
|
||||
}
|
||||
|
||||
fetchUserInfo().then((info) => {
|
||||
const orgData = (info as Record<string, unknown>)?.organization_data as
|
||||
Array<{ id: string; name: string }> | undefined;
|
||||
const orgs = orgData ?? [];
|
||||
setOrganizations(orgs.map((o) => ({ id: o.id, name: o.name })));
|
||||
|
||||
// Auto-select if user has exactly one org
|
||||
if (orgs.length === 1 && !currentOrgId) {
|
||||
setCurrentOrg(orgs[0].id);
|
||||
}
|
||||
}).catch(() => {
|
||||
// fetchUserInfo may fail if token is being refreshed
|
||||
});
|
||||
}, [isAuthenticated]);
|
||||
|
||||
// Set token provider — org-scoped if org selected, plain otherwise
|
||||
useEffect(() => {
|
||||
if (isAuthenticated && resource) {
|
||||
setTokenProvider(() => getAccessToken(resource));
|
||||
if (currentOrgId) {
|
||||
setTokenProvider(() => getAccessToken(resource, currentOrgId));
|
||||
} else {
|
||||
setTokenProvider(() => getAccessToken(resource));
|
||||
}
|
||||
} else {
|
||||
setTokenProvider(null);
|
||||
}
|
||||
}, [isAuthenticated, getAccessToken, resource]);
|
||||
}, [isAuthenticated, getAccessToken, resource, currentOrgId]);
|
||||
|
||||
const handleLogout = useCallback(() => {
|
||||
signOut(window.location.origin + '/login');
|
||||
@@ -66,7 +96,11 @@ function App() {
|
||||
endpoint: config.logtoEndpoint,
|
||||
appId: config.logtoClientId,
|
||||
resources: config.logtoResource ? [config.logtoResource] : [],
|
||||
scopes: ['openid', 'profile', 'email', 'offline_access'],
|
||||
scopes: [
|
||||
'openid', 'profile', 'email', 'offline_access',
|
||||
UserScope.Organizations,
|
||||
UserScope.OrganizationRoles,
|
||||
],
|
||||
}}
|
||||
>
|
||||
<TokenSync resource={config.logtoResource} />
|
||||
|
||||
75
ui/src/pages/AdminTenantsPage.tsx
Normal file
75
ui/src/pages/AdminTenantsPage.tsx
Normal file
@@ -0,0 +1,75 @@
|
||||
import { useNavigate } from 'react-router';
|
||||
import {
|
||||
Badge,
|
||||
Card,
|
||||
DataTable,
|
||||
Spinner,
|
||||
} from '@cameleer/design-system';
|
||||
import type { Column } from '@cameleer/design-system';
|
||||
import { useAllTenants } from '../api/hooks';
|
||||
import { useOrgStore } from '../auth/useOrganization';
|
||||
import type { TenantResponse } from '../types/api';
|
||||
|
||||
const columns: Column<TenantResponse>[] = [
|
||||
{ key: 'name', header: 'Name' },
|
||||
{ key: 'slug', header: 'Slug' },
|
||||
{
|
||||
key: 'tier',
|
||||
header: 'Tier',
|
||||
render: (_v: unknown, row: TenantResponse) => <Badge label={row.tier} color="primary" />,
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
header: 'Status',
|
||||
render: (_v: unknown, row: TenantResponse) => (
|
||||
<Badge
|
||||
label={row.status}
|
||||
color={row.status === 'ACTIVE' ? 'success' : 'warning'}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{ key: 'createdAt', header: 'Created' },
|
||||
];
|
||||
|
||||
export function AdminTenantsPage() {
|
||||
const navigate = useNavigate();
|
||||
const { data: tenants, isLoading } = useAllTenants();
|
||||
const { setCurrentOrg } = useOrgStore();
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<Spinner />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const handleRowClick = (tenant: TenantResponse) => {
|
||||
// Find the matching org from the store and switch context
|
||||
const orgs = useOrgStore.getState().organizations;
|
||||
const match = orgs.find(
|
||||
(o) => o.name === tenant.name || o.slug === tenant.slug,
|
||||
);
|
||||
if (match) {
|
||||
setCurrentOrg(match.id);
|
||||
navigate('/');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-semibold text-white">All Tenants</h1>
|
||||
<Badge label="Platform Admin" color="warning" />
|
||||
</div>
|
||||
|
||||
<Card title={`${tenants?.length ?? 0} Tenants`}>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={tenants ?? []}
|
||||
onRowClick={handleRowClick}
|
||||
/>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,12 +2,14 @@ import { Routes, Route } from 'react-router';
|
||||
import { LoginPage } from './auth/LoginPage';
|
||||
import { CallbackPage } from './auth/CallbackPage';
|
||||
import { ProtectedRoute } from './auth/ProtectedRoute';
|
||||
import { OrgResolver } from './auth/OrgResolver';
|
||||
import { Layout } from './components/Layout';
|
||||
import { DashboardPage } from './pages/DashboardPage';
|
||||
import { EnvironmentsPage } from './pages/EnvironmentsPage';
|
||||
import { EnvironmentDetailPage } from './pages/EnvironmentDetailPage';
|
||||
import { AppDetailPage } from './pages/AppDetailPage';
|
||||
import { LicensePage } from './pages/LicensePage';
|
||||
import { AdminTenantsPage } from './pages/AdminTenantsPage';
|
||||
|
||||
export function AppRouter() {
|
||||
return (
|
||||
@@ -17,7 +19,9 @@ export function AppRouter() {
|
||||
<Route
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<Layout />
|
||||
<OrgResolver>
|
||||
<Layout />
|
||||
</OrgResolver>
|
||||
</ProtectedRoute>
|
||||
}
|
||||
>
|
||||
@@ -26,6 +30,7 @@ export function AppRouter() {
|
||||
<Route path="environments/:envId" element={<EnvironmentDetailPage />} />
|
||||
<Route path="environments/:envId/apps/:appId" element={<AppDetailPage />} />
|
||||
<Route path="license" element={<LicensePage />} />
|
||||
<Route path="admin/tenants" element={<AdminTenantsPage />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
);
|
||||
|
||||
@@ -83,3 +83,14 @@ export interface LogEntry {
|
||||
stream: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface MeResponse {
|
||||
userId: string;
|
||||
isPlatformAdmin: boolean;
|
||||
tenants: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
logtoOrgId: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user