Merge pull request #2 from jamesii-b/gatehouse/secuird-CA-merge-v2.01

Gatehouse/secuird ca merge v2.01
This commit is contained in:
2026-03-03 13:52:25 +10:30
committed by GitHub
38 changed files with 9301 additions and 1034 deletions
+83 -9
View File
@@ -18,13 +18,16 @@ import ResetPasswordPage from "@/pages/auth/ResetPasswordPage";
import InviteAcceptPage from "@/pages/auth/InviteAcceptPage"; import InviteAcceptPage from "@/pages/auth/InviteAcceptPage";
import OIDCConsentPage from "@/pages/auth/OIDCConsentPage"; import OIDCConsentPage from "@/pages/auth/OIDCConsentPage";
import OIDCErrorPage from "@/pages/auth/OIDCErrorPage"; import OIDCErrorPage from "@/pages/auth/OIDCErrorPage";
import OIDCLoginPage from "@/pages/auth/OIDCLoginPage";
import OAuthCallbackPage from "@/pages/auth/OAuthCallbackPage"; import OAuthCallbackPage from "@/pages/auth/OAuthCallbackPage";
import ActivatePage from "@/pages/auth/ActivatePage";
// User pages // User pages
import ProfilePage from "@/pages/user/ProfilePage"; import ProfilePage from "@/pages/user/ProfilePage";
import SecurityPage from "@/pages/user/SecurityPage"; import SecurityPage from "@/pages/user/SecurityPage";
import LinkedAccountsPage from "@/pages/user/LinkedAccountsPage"; import LinkedAccountsPage from "@/pages/user/LinkedAccountsPage";
import ActivityPage from "@/pages/user/ActivityPage"; import ActivityPage from "@/pages/user/ActivityPage";
import SSHKeysPage from "@/pages/user/SSHKeysPage";
// Organization pages // Organization pages
import OrgOverviewPage from "@/pages/org/OrgOverviewPage"; import OrgOverviewPage from "@/pages/org/OrgOverviewPage";
@@ -33,6 +36,13 @@ import PoliciesPage from "@/pages/org/PoliciesPage";
import CompliancePage from "@/pages/org/CompliancePage"; import CompliancePage from "@/pages/org/CompliancePage";
import OrgAuditPage from "@/pages/org/OrgAuditPage"; import OrgAuditPage from "@/pages/org/OrgAuditPage";
import OIDCClientsPage from "@/pages/org/OIDCClientsPage"; import OIDCClientsPage from "@/pages/org/OIDCClientsPage";
import CAsPage from "@/pages/org/CAsPage";
import DepartmentsPage from "@/pages/org/DepartmentsPage";
import PrincipalsPage from "@/pages/org/PrincipalsPage";
import MyMembershipsPage from "@/pages/org/MyMembershipsPage";
import SystemAuditPage from "@/pages/admin/SystemAuditPage";
import OAuthProvidersPage from "@/pages/admin/OAuthProvidersPage";
import OrgSetupPage from "@/pages/auth/OrgSetupPage";
import NotFound from "@/pages/NotFound"; import NotFound from "@/pages/NotFound";
import ApiDevTools from "@/components/dev/ApiDevTools"; import ApiDevTools from "@/components/dev/ApiDevTools";
@@ -65,26 +75,77 @@ const App = () => (
); );
// Separate component so AuthProvider can use useNavigate // Separate component so AuthProvider can use useNavigate
import { AuthProvider } from "@/contexts/AuthContext"; import { AuthProvider, useAuth } from "@/contexts/AuthContext";
import { OrgProvider } from "@/contexts/OrgContext";
import { Navigate } from "react-router-dom";
/** Redirects already-authenticated users away from guest-only pages (e.g. /login). */
function GuestRoute({ children }: { children: React.ReactNode }) {
const { isAuthenticated, isOrgMember, isLoading } = useAuth();
// Allow authenticated users through to /login when it's a CLI auth request or
// an OIDC session — LoginPage will immediately forward the existing token.
const params = new URLSearchParams(window.location.search);
const isCli = params.has('cli_token') || params.has('cli_redirect');
const isOidcBridge = params.has('oidc_session_id');
if (isLoading) return null; // wait for auth state to resolve
if (isAuthenticated && !isCli && !isOidcBridge) {
// If the user hasn't set up an org yet, send them there first
return <Navigate to={isOrgMember ? "/profile" : "/org-setup"} replace />;
}
return <>{children}</>;
}
/** Blocks access to /admin/* for non-admin users. */
function RequireAdmin({ children }: { children: React.ReactNode }) {
const { isOrgAdmin, isLoading, isAuthenticated } = useAuth();
if (isLoading) return null;
if (!isAuthenticated) return <Navigate to="/login" replace />;
if (!isOrgAdmin) return <Navigate to="/profile" replace />;
return <>{children}</>;
}
/** Blocks access to /org/* for users who don't belong to any organisation. */
function RequireOrgMember({ children }: { children: React.ReactNode }) {
const { isOrgMember, isLoading, isAuthenticated } = useAuth();
if (isLoading) return null;
if (!isAuthenticated) return <Navigate to="/login" replace />;
if (!isOrgMember) return <Navigate to="/profile" replace />;
return <>{children}</>;
}
/**
* Used for /org-setup which lives inside PublicLayout */
function RequireAuth({ children }: { children: React.ReactNode }) {
const { isAuthenticated, isLoading } = useAuth();
if (isLoading) return null;
if (!isAuthenticated) return <Navigate to="/login" replace />;
return <>{children}</>;
}
function AppRoutes() { function AppRoutes() {
return ( return (
<AuthProvider> <AuthProvider>
<OrgProvider>
<Routes> <Routes>
{/* Index redirect */} {/* Index redirect */}
<Route path="/" element={<Index />} /> <Route path="/" element={<Index />} />
{/* Public routes */} {/* Public routes */}
<Route element={<PublicLayout />}> <Route element={<PublicLayout />}>
<Route path="/login" element={<LoginPage />} /> <Route path="/login" element={<GuestRoute><LoginPage /></GuestRoute>} />
<Route path="/register" element={<RegisterPage />} /> <Route path="/register" element={<RegisterPage />} />
<Route path="/verify-email" element={<VerifyEmailPage />} /> <Route path="/verify-email" element={<VerifyEmailPage />} />
<Route path="/forgot-password" element={<ForgotPasswordPage />} /> <Route path="/forgot-password" element={<ForgotPasswordPage />} />
<Route path="/reset-password" element={<ResetPasswordPage />} /> <Route path="/reset-password" element={<ResetPasswordPage />} />
<Route path="/invite" element={<InviteAcceptPage />} /> <Route path="/invite" element={<InviteAcceptPage />} />
<Route path="/consent" element={<OIDCConsentPage />} /> <Route path="/consent" element={<OIDCConsentPage />} />
<Route path="/oidc-login" element={<OIDCLoginPage />} />
<Route path="/error" element={<OIDCErrorPage />} /> <Route path="/error" element={<OIDCErrorPage />} />
<Route path="/oauth/callback" element={<OAuthCallbackPage />} /> <Route path="/oauth/callback" element={<OAuthCallbackPage />} />
<Route path="/activate" element={<ActivatePage />} />
{/* Org-setup uses the same full-screen centred layout as auth pages,
but requires a valid session token (RequireAuth guard below). */}
<Route path="/org-setup" element={<RequireAuth><OrgSetupPage /></RequireAuth>} />
</Route> </Route>
{/* Protected routes - handles auth and MFA enforcement */} {/* Protected routes - handles auth and MFA enforcement */}
@@ -94,14 +155,26 @@ function AppRoutes() {
<Route path="/security" element={<SecurityPage />} /> <Route path="/security" element={<SecurityPage />} />
<Route path="/linked-accounts" element={<LinkedAccountsPage />} /> <Route path="/linked-accounts" element={<LinkedAccountsPage />} />
<Route path="/activity" element={<ActivityPage />} /> <Route path="/activity" element={<ActivityPage />} />
<Route path="/ssh-keys" element={<SSHKeysPage />} />
{/* Organization routes */} {/* Organization routes — org members: overview + own memberships only */}
<Route path="/org" element={<OrgOverviewPage />} /> <Route path="/org" element={<RequireOrgMember><OrgOverviewPage /></RequireOrgMember>} />
<Route path="/org/members" element={<MembersPage />} /> <Route path="/org/my-memberships" element={<RequireOrgMember><MyMembershipsPage /></RequireOrgMember>} />
<Route path="/org/policies" element={<PoliciesPage />} />
<Route path="/org/policies/compliance" element={<CompliancePage />} /> {/* Organization management routes — org admins/owners only */}
<Route path="/org/audit" element={<OrgAuditPage />} /> <Route path="/org/members" element={<RequireAdmin><MembersPage /></RequireAdmin>} />
<Route path="/org/clients" element={<OIDCClientsPage />} /> <Route path="/org/departments" element={<RequireAdmin><DepartmentsPage /></RequireAdmin>} />
<Route path="/org/principals" element={<RequireAdmin><PrincipalsPage /></RequireAdmin>} />
<Route path="/org/policies" element={<RequireAdmin><PoliciesPage /></RequireAdmin>} />
<Route path="/org/policies/compliance" element={<RequireAdmin><CompliancePage /></RequireAdmin>} />
<Route path="/org/audit" element={<RequireAdmin><OrgAuditPage /></RequireAdmin>} />
<Route path="/org/clients" element={<RequireAdmin><OIDCClientsPage /></RequireAdmin>} />
<Route path="/org/cas" element={<RequireAdmin><CAsPage /></RequireAdmin>} />
{/* Admin routes — org admin/owner only */}
<Route path="/admin/audit" element={<RequireAdmin><SystemAuditPage /></RequireAdmin>} />
<Route path="/admin/users" element={<Navigate to="/org/members" replace />} />
<Route path="/admin/oauth" element={<RequireAdmin><OAuthProvidersPage /></RequireAdmin>} />
</Route> </Route>
{/* Catch-all */} {/* Catch-all */}
@@ -110,6 +183,7 @@ function AppRoutes() {
{/* Dev tools - only shown in development */} {/* Dev tools - only shown in development */}
<ApiDevTools /> <ApiDevTools />
</OrgProvider>
</AuthProvider> </AuthProvider>
); );
} }
+10 -5
View File
@@ -2,12 +2,14 @@ import { Navigate, Outlet } from 'react-router-dom';
import { useAuth } from '@/contexts/AuthContext'; import { useAuth } from '@/contexts/AuthContext';
import AuthenticatedLayout from './AuthenticatedLayout'; import AuthenticatedLayout from './AuthenticatedLayout';
import MfaEnforcementLayout from './MfaEnforcementLayout'; import MfaEnforcementLayout from './MfaEnforcementLayout';
import { useOrganizations } from '@/hooks/useOrganizations';
import { Loader2 } from 'lucide-react'; import { Loader2 } from 'lucide-react';
export default function ProtectedLayout() { export default function ProtectedLayout() {
const { isAuthenticated, isLoading, requiresMfaEnrollment } = useAuth(); const { isAuthenticated, isLoading, requiresMfaEnrollment, isOrgMember } = useAuth();
const { isLoading: isOrgsLoading } = useOrganizations();
if (isLoading) { if (isLoading || isOrgsLoading) {
return ( return (
<div className="min-h-screen flex items-center justify-center bg-background"> <div className="min-h-screen flex items-center justify-center bg-background">
<div className="flex flex-col items-center gap-4"> <div className="flex flex-col items-center gap-4">
@@ -22,13 +24,16 @@ export default function ProtectedLayout() {
return <Navigate to="/login" replace />; return <Navigate to="/login" replace />;
} }
// User is logged in but hasn't joined/created an org yet — send to org-setup
if (!isOrgMember) {
return <Navigate to="/org-setup" replace />;
}
if (requiresMfaEnrollment) { if (requiresMfaEnrollment) {
return <MfaEnforcementLayout />; return <MfaEnforcementLayout />;
} }
return ( return (
<AuthenticatedLayout> <AuthenticatedLayout />
<Outlet />
</AuthenticatedLayout>
); );
} }
+60 -24
View File
@@ -8,10 +8,15 @@ import {
Users, Users,
Settings, Settings,
FileText, FileText,
Key, Layers,
GitBranch,
ScrollText,
Terminal,
ShieldCheck,
} from "lucide-react"; } from "lucide-react";
import { GatehouseLogo } from "@/components/branding/GatehouseLogo"; import { GatehouseLogo } from "@/components/branding/GatehouseLogo";
import { NavLink } from "@/components/NavLink"; import { NavLink } from "@/components/NavLink";
import { useAuth } from "@/contexts/AuthContext";
import { import {
Sidebar, Sidebar,
SidebarContent, SidebarContent,
@@ -30,29 +35,41 @@ import { cn } from "@/lib/utils";
const userNavItems = [ const userNavItems = [
{ title: "Profile", url: "/profile", icon: User }, { title: "Profile", url: "/profile", icon: User },
{ title: "Security", url: "/security", icon: Shield }, { title: "Security", url: "/security", icon: Shield },
{ title: "SSH Keys", url: "/ssh-keys", icon: Terminal },
{ title: "Linked Accounts", url: "/linked-accounts", icon: Link2 }, { title: "Linked Accounts", url: "/linked-accounts", icon: Link2 },
{ title: "Activity", url: "/activity", icon: Activity }, { title: "Activity", url: "/activity", icon: Activity },
]; ];
const orgNavItems = [ // Visible to ALL org members
const orgMemberNavItems = [
{ title: "Overview", url: "/org", icon: Building2 },
{ title: "My Memberships", url: "/org/my-memberships", icon: Layers },
];
// Visible to org admins/owners only (management)
const orgAdminNavItems = [
{ title: "Overview", url: "/org", icon: Building2 }, { title: "Overview", url: "/org", icon: Building2 },
{ title: "Members", url: "/org/members", icon: Users }, { title: "Members", url: "/org/members", icon: Users },
{ title: "Departments", url: "/org/departments", icon: Layers },
{ title: "Principals", url: "/org/principals", icon: GitBranch },
{ title: "Policies", url: "/org/policies", icon: Settings }, { title: "Policies", url: "/org/policies", icon: Settings },
{ title: "Audit Log", url: "/org/audit", icon: FileText },
]; ];
const adminNavItems = [ const adminNavItems = [
{ title: "OIDC Clients", url: "/org/clients", icon: Key }, { title: "Certificate Auth.", url: "/org/cas", icon: ShieldCheck },
{ title: "Org Audit Log", url: "/org/audit", icon: FileText },
{ title: "System Logs", url: "/admin/audit", icon: ScrollText },
]; ];
export function AppSidebar() { export function AppSidebar() {
const { state } = useSidebar(); const { state } = useSidebar();
const collapsed = state === "collapsed"; const collapsed = state === "collapsed";
const location = useLocation(); const location = useLocation();
const { isOrgAdmin, isOrgMember } = useAuth();
const isActive = (path: string) => location.pathname === path; const isActive = (path: string) => location.pathname === path;
const isOrgActive = orgNavItems.some((item) => isActive(item.url)) || adminNavItems.some((item) => isActive(item.url)); const isOrgActive = orgAdminNavItems.some((item) => isActive(item.url)) || adminNavItems.some((item) => isActive(item.url));
const isUserActive = userNavItems.some((item) => isActive(item.url)); void isOrgActive; // used for future active state tracking
return ( return (
<Sidebar <Sidebar
@@ -77,9 +94,11 @@ export function AppSidebar() {
<SidebarContent className="py-4"> <SidebarContent className="py-4">
{/* User Section */} {/* User Section */}
<SidebarGroup> <SidebarGroup>
<SidebarGroupLabel className="px-4 text-xs font-medium text-sidebar-muted uppercase tracking-wider"> {!collapsed && (
{!collapsed && "Account"} <SidebarGroupLabel className="px-4 text-xs font-medium text-sidebar-muted uppercase tracking-wider">
</SidebarGroupLabel> Account
</SidebarGroupLabel>
)}
<SidebarGroupContent> <SidebarGroupContent>
<SidebarMenu> <SidebarMenu>
{userNavItems.map((item) => ( {userNavItems.map((item) => (
@@ -89,8 +108,11 @@ export function AppSidebar() {
to={item.url} to={item.url}
end end
className={cn( className={cn(
"flex items-center gap-3 px-4 py-2.5 text-sm text-sidebar-foreground rounded-lg mx-2 transition-colors", "flex items-center text-sm text-sidebar-foreground rounded-lg transition-colors",
"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground" "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
collapsed
? "justify-center w-10 h-10 mx-auto p-0"
: "gap-3 px-4 py-2.5 mx-2"
)} )}
activeClassName="bg-sidebar-accent text-sidebar-primary font-medium" activeClassName="bg-sidebar-accent text-sidebar-primary font-medium"
> >
@@ -104,22 +126,28 @@ export function AppSidebar() {
</SidebarGroupContent> </SidebarGroupContent>
</SidebarGroup> </SidebarGroup>
{/* Organization Section */} {/* Organization Section — content differs by role */}
{isOrgMember && (
<SidebarGroup className="mt-4"> <SidebarGroup className="mt-4">
<SidebarGroupLabel className="px-4 text-xs font-medium text-sidebar-muted uppercase tracking-wider"> {!collapsed && (
{!collapsed && "Organization"} <SidebarGroupLabel className="px-4 text-xs font-medium text-sidebar-muted uppercase tracking-wider">
</SidebarGroupLabel> Organization
</SidebarGroupLabel>
)}
<SidebarGroupContent> <SidebarGroupContent>
<SidebarMenu> <SidebarMenu>
{orgNavItems.map((item) => ( {(isOrgAdmin ? orgAdminNavItems : orgMemberNavItems).map((item) => (
<SidebarMenuItem key={item.title}> <SidebarMenuItem key={item.title}>
<SidebarMenuButton asChild> <SidebarMenuButton asChild>
<NavLink <NavLink
to={item.url} to={item.url}
end end
className={cn( className={cn(
"flex items-center gap-3 px-4 py-2.5 text-sm text-sidebar-foreground rounded-lg mx-2 transition-colors", "flex items-center text-sm text-sidebar-foreground rounded-lg transition-colors",
"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground" "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
collapsed
? "justify-center w-10 h-10 mx-auto p-0"
: "gap-3 px-4 py-2.5 mx-2"
)} )}
activeClassName="bg-sidebar-accent text-sidebar-primary font-medium" activeClassName="bg-sidebar-accent text-sidebar-primary font-medium"
> >
@@ -132,12 +160,16 @@ export function AppSidebar() {
</SidebarMenu> </SidebarMenu>
</SidebarGroupContent> </SidebarGroupContent>
</SidebarGroup> </SidebarGroup>
)}
{/* Admin Section */} {/* Admin Section — only visible to org admins/owners */}
{isOrgAdmin && (
<SidebarGroup className="mt-4"> <SidebarGroup className="mt-4">
<SidebarGroupLabel className="px-4 text-xs font-medium text-sidebar-muted uppercase tracking-wider"> {!collapsed && (
{!collapsed && "Admin"} <SidebarGroupLabel className="px-4 text-xs font-medium text-sidebar-muted uppercase tracking-wider">
</SidebarGroupLabel> Admin
</SidebarGroupLabel>
)}
<SidebarGroupContent> <SidebarGroupContent>
<SidebarMenu> <SidebarMenu>
{adminNavItems.map((item) => ( {adminNavItems.map((item) => (
@@ -147,8 +179,11 @@ export function AppSidebar() {
to={item.url} to={item.url}
end end
className={cn( className={cn(
"flex items-center gap-3 px-4 py-2.5 text-sm text-sidebar-foreground rounded-lg mx-2 transition-colors", "flex items-center text-sm text-sidebar-foreground rounded-lg transition-colors",
"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground" "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
collapsed
? "justify-center w-10 h-10 mx-auto p-0"
: "gap-3 px-4 py-2.5 mx-2"
)} )}
activeClassName="bg-sidebar-accent text-sidebar-primary font-medium" activeClassName="bg-sidebar-accent text-sidebar-primary font-medium"
> >
@@ -161,6 +196,7 @@ export function AppSidebar() {
</SidebarMenu> </SidebarMenu>
</SidebarGroupContent> </SidebarGroupContent>
</SidebarGroup> </SidebarGroup>
)}
</SidebarContent> </SidebarContent>
<SidebarFooter className="p-4 border-t border-sidebar-border"> <SidebarFooter className="p-4 border-t border-sidebar-border">
+7 -19
View File
@@ -1,4 +1,3 @@
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { Menu, ChevronDown, LogOut, User, Shield, Building2, Loader2 } from "lucide-react"; import { Menu, ChevronDown, LogOut, User, Shield, Building2, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -13,34 +12,23 @@ import {
} from "@/components/ui/dropdown-menu"; } from "@/components/ui/dropdown-menu";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useAuth } from "@/contexts/AuthContext"; import { useAuth } from "@/contexts/AuthContext";
import { Organization } from "@/lib/api"; import { useOrg } from "@/contexts/OrgContext";
import { useOrganizations } from "@/hooks/useOrganizations"; import { useOrganizations } from "@/hooks/useOrganizations";
import { ComplianceBanner } from "@/components/auth/ComplianceBanner"; import { ComplianceBanner } from "@/components/auth/ComplianceBanner";
export function TopBar() { export function TopBar() {
const navigate = useNavigate(); const navigate = useNavigate();
const { user, isAuthenticated, mfaCompliance } = useAuth(); const { user, mfaCompliance, logout } = useAuth();
const [currentOrg, setCurrentOrg] = useState<Organization | null>(null); const { selectedOrg, selectOrg } = useOrg();
// Use React Query hook for organizations with automatic caching and deduplication // Use React Query hook for organizations with automatic caching and deduplication
const { data: organizations = [], isLoading: orgsLoading } = useOrganizations(); const { data: organizations = [], isLoading: orgsLoading } = useOrganizations();
// Debug logging
console.log('[TopBar] organizations data:', organizations);
console.log('[TopBar] organizations is array:', Array.isArray(organizations));
// Ensure organizations is always an array (defensive check) // Ensure organizations is always an array (defensive check)
const organizationsArray = Array.isArray(organizations) ? organizations : []; const organizationsArray = Array.isArray(organizations) ? organizations : [];
// Set initial currentOrg when organizations are loaded const handleLogout = async () => {
useEffect(() => { await logout();
if (organizationsArray.length > 0 && !currentOrg) {
setCurrentOrg(organizationsArray[0]);
}
}, [organizationsArray, currentOrg]);
const handleLogout = () => {
navigate("/login");
}; };
const userInitials = user?.full_name const userInitials = user?.full_name
@@ -68,7 +56,7 @@ export function TopBar() {
<Building2 className="w-3.5 h-3.5 text-primary" /> <Building2 className="w-3.5 h-3.5 text-primary" />
</div> </div>
<span className="text-sm font-medium hidden sm:inline"> <span className="text-sm font-medium hidden sm:inline">
{orgsLoading ? "Loading..." : (currentOrg?.name || "No Organization")} {orgsLoading ? "Loading..." : (selectedOrg?.name || "No Organization")}
</span> </span>
<ChevronDown className="w-4 h-4 text-muted-foreground" /> <ChevronDown className="w-4 h-4 text-muted-foreground" />
</Button> </Button>
@@ -90,7 +78,7 @@ export function TopBar() {
organizationsArray.map((org) => ( organizationsArray.map((org) => (
<DropdownMenuItem <DropdownMenuItem
key={org.id} key={org.id}
onClick={() => setCurrentOrg(org)} onClick={() => selectOrg(org)}
className="flex items-center justify-between" className="flex items-center justify-between"
> >
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
+69 -61
View File
@@ -1,25 +1,32 @@
import { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react'; import { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { api, User, ApiError, tokenManager, MfaComplianceSummary } from '@/lib/api'; import { api, User, ApiError, tokenManager, MfaComplianceSummary, PendingInvite } from '@/lib/api';
interface LoginResult { interface LoginResult {
requiresTotp: boolean; requiresTotp: boolean;
requiresWebAuthn: boolean; requiresWebAuthn: boolean;
requiresMfaEnrollment?: boolean; requiresMfaEnrollment?: boolean;
requiresOrgSetup?: boolean;
pendingInvites?: PendingInvite[];
isFirstUser?: boolean;
} }
interface AuthContextType { interface AuthContextType {
user: User | null; user: User | null;
isLoading: boolean; isLoading: boolean;
isAuthenticated: boolean; isAuthenticated: boolean;
isOrgAdmin: boolean;
isOrgMember: boolean;
mfaCompliance: MfaComplianceSummary | null; mfaCompliance: MfaComplianceSummary | null;
requiresMfaEnrollment: boolean; requiresMfaEnrollment: boolean;
login: (email: string, password: string, rememberMe?: boolean) => Promise<LoginResult>; login: (email: string, password: string, rememberMe?: boolean, skipNavigate?: boolean) => Promise<LoginResult>;
verifyTotp: (code: string, isBackupCode?: boolean) => Promise<void>; verifyTotp: (code: string, isBackupCode?: boolean, skipNavigate?: boolean) => Promise<void>;
verifyWebAuthn: () => Promise<void>; verifyWebAuthn: () => Promise<void>;
logout: () => Promise<void>; logout: () => Promise<void>;
refreshUser: () => Promise<void>; refreshUser: () => Promise<void>;
refreshCompliance: () => Promise<void>; refreshCompliance: () => Promise<void>;
/** Re-check org membership & admin status. Exposed so post-setup pages can update the context. */
checkOrgAdmin: () => Promise<void>;
} }
const AuthContext = createContext<AuthContextType | null>(null); const AuthContext = createContext<AuthContextType | null>(null);
@@ -40,66 +47,61 @@ function persistMfaCompliance(compliance: MfaComplianceSummary | null): void {
function loadMfaCompliance(): MfaComplianceSummary | null { function loadMfaCompliance(): MfaComplianceSummary | null {
try { try {
const stored = localStorage.getItem(MFA_COMPLIANCE_KEY); const stored = localStorage.getItem(MFA_COMPLIANCE_KEY);
if (!stored) { if (!stored) return null;
console.log('[AuthContext] loadMfaCompliance: no stored data');
return null;
}
const parsed = JSON.parse(stored); const parsed = JSON.parse(stored);
console.log('[AuthContext] loadMfaCompliance: raw parsed:', parsed);
// Handle both direct format and legacy double-nested format // Handle both direct format and legacy double-nested format
// Legacy format: { mfa_compliance: { ... } } // Legacy format: { mfa_compliance: { ... } }
// Current format: { ... } // Current format: { ... }
let compliance: Record<string, unknown>; let compliance: Record<string, unknown>;
if (parsed.mfa_compliance && typeof parsed.mfa_compliance === 'object') { if (parsed.mfa_compliance && typeof parsed.mfa_compliance === 'object') {
console.log('[AuthContext] loadMfaCompliance: detected legacy double-nested format, unwrapping');
compliance = parsed.mfa_compliance as Record<string, unknown>; compliance = parsed.mfa_compliance as Record<string, unknown>;
} else { } else {
compliance = parsed; compliance = parsed;
} }
// Validate that the stored data has the required fields // Validate that the stored data has the required fields
if (!compliance || typeof compliance !== 'object') { if (!compliance || typeof compliance !== 'object') return null;
console.log('[AuthContext] loadMfaCompliance: invalid compliance object'); if (!Array.isArray(compliance.orgs)) return null;
return null;
}
if (!Array.isArray(compliance.orgs)) {
console.log('[AuthContext] loadMfaCompliance: orgs is not an array');
return null;
}
// Validate missing_methods exists and is an array
if (!Array.isArray(compliance.missing_methods)) {
console.log('[AuthContext] loadMfaCompliance: missing_methods is not an array or missing');
}
// Check if at least one org has effective_mode (new field from API) // Check if at least one org has effective_mode (new field from API)
// If not, treat as stale data and return null to fetch fresh data // If not, treat as stale data and return null to fetch fresh data
const hasEffectiveMode = compliance.orgs.some((org: Record<string, unknown>) => const hasEffectiveMode = compliance.orgs.some((org: Record<string, unknown>) =>
typeof org.effective_mode === 'string' typeof org.effective_mode === 'string'
); );
if (!hasEffectiveMode) return null;
if (!hasEffectiveMode) {
console.log('[AuthContext] loadMfaCompliance: no effective_mode found, treating as stale');
return null;
}
console.log('[AuthContext] loadMfaCompliance: loaded successfully');
return compliance as unknown as MfaComplianceSummary; return compliance as unknown as MfaComplianceSummary;
} catch (error) { } catch {
console.log('[AuthContext] loadMfaCompliance: error loading:', error);
return null; return null;
} }
} }
export function AuthProvider({ children }: { children: ReactNode }) { export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null); const [user, setUser] = useState<User | null>(null);
const [isOrgAdmin, setIsOrgAdmin] = useState(false);
const [isOrgMember, setIsOrgMember] = useState(false);
const [mfaCompliance, setMfaCompliance] = useState<MfaComplianceSummary | null>(loadMfaCompliance); const [mfaCompliance, setMfaCompliance] = useState<MfaComplianceSummary | null>(loadMfaCompliance);
const [requiresMfaEnrollment, setRequiresMfaEnrollment] = useState(false); const [requiresMfaEnrollment, setRequiresMfaEnrollment] = useState(false);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const navigate = useNavigate(); const navigate = useNavigate();
// Helper to check if user is admin/owner in any org
const checkOrgAdmin = useCallback(async () => {
try {
const data = await api.users.organizations();
const admin = data.organizations.some(
(org) => org.role === 'owner' || org.role === 'admin'
);
setIsOrgAdmin(admin);
setIsOrgMember(data.organizations.length > 0);
} catch {
setIsOrgAdmin(false);
setIsOrgMember(false);
}
}, []);
const refreshCompliance = useCallback(async () => { const refreshCompliance = useCallback(async () => {
try { try {
const compliance = await api.policies.getMyCompliance(); const compliance = await api.policies.getMyCompliance();
@@ -148,7 +150,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const response = await api.users.me(); const response = await api.users.me();
setUser(response.user); setUser(response.user);
// Also fetch compliance status // Also fetch compliance status and org role
try { try {
const compliance = await api.policies.getMyCompliance(); const compliance = await api.policies.getMyCompliance();
setMfaCompliance(compliance); setMfaCompliance(compliance);
@@ -159,8 +161,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setMfaCompliance(null); setMfaCompliance(null);
persistMfaCompliance(null); persistMfaCompliance(null);
} }
// Check org admin status
await checkOrgAdmin();
} catch { } catch {
setUser(null); setUser(null);
setIsOrgAdmin(false);
setIsOrgMember(false);
setMfaCompliance(null); setMfaCompliance(null);
persistMfaCompliance(null); persistMfaCompliance(null);
setRequiresMfaEnrollment(false); setRequiresMfaEnrollment(false);
@@ -172,32 +178,21 @@ export function AuthProvider({ children }: { children: ReactNode }) {
checkAuth(); checkAuth();
}, []); }, []);
const login = useCallback(async (email: string, password: string, rememberMe = false): Promise<LoginResult> => { const login = useCallback(async (email: string, password: string, rememberMe = false, skipNavigate = false): Promise<LoginResult> => {
console.log('[AuthContext] login() called');
const response = await api.auth.login(email, password, rememberMe); const response = await api.auth.login(email, password, rememberMe);
console.log('[AuthContext] login response:', {
requires_totp: response.requires_totp,
requires_webauthn: response.requires_webauthn,
requires_mfa_enrollment: response.requires_mfa_enrollment,
hasToken: !!response.token,
hasUser: !!response.user
});
// If WebAuthn is required, don't set user yet - wait for WebAuthn verification // If WebAuthn is required, don't set user yet - wait for WebAuthn verification
if (response.requires_webauthn) { if (response.requires_webauthn) {
console.log('[AuthContext] WebAuthn required, returning early');
return { requiresTotp: false, requiresWebAuthn: true }; return { requiresTotp: false, requiresWebAuthn: true };
} }
// If TOTP is required, don't set user yet - wait for TOTP verification // If TOTP is required, don't set user yet - wait for TOTP verification
if (response.requires_totp) { if (response.requires_totp) {
console.log('[AuthContext] TOTP required, returning early');
return { requiresTotp: true, requiresWebAuthn: false }; return { requiresTotp: true, requiresWebAuthn: false };
} }
// If MFA enrollment is required (past deadline), set compliance state // If MFA enrollment is required (past deadline), set compliance state
if (response.requires_mfa_enrollment) { if (response.requires_mfa_enrollment) {
console.log('[AuthContext] MFA enrollment required, setting compliance state');
if (response.token) { if (response.token) {
tokenManager.setToken(response.token, response.expires_at ?? null); tokenManager.setToken(response.token, response.expires_at ?? null);
} }
@@ -212,47 +207,52 @@ export function AuthProvider({ children }: { children: ReactNode }) {
return { requiresTotp: false, requiresWebAuthn: false, requiresMfaEnrollment: true }; return { requiresTotp: false, requiresWebAuthn: false, requiresMfaEnrollment: true };
} }
// Login complete: store token explicitly before setting user state
// This ensures the token is available for any subsequent API calls
// (e.g., when navigate('/profile') triggers refreshUser())
if (response.token) { if (response.token) {
console.log('[AuthContext] Storing token in localStorage');
tokenManager.setToken(response.token, response.expires_at ?? null); tokenManager.setToken(response.token, response.expires_at ?? null);
console.log('[AuthContext] Token stored, verifying:', tokenManager.getToken()?.substring(0, 20) + '...');
} }
// Set user and navigate
if (response.user) { if (response.user) {
console.log('[AuthContext] Setting user state and navigating to /profile');
setUser(response.user); setUser(response.user);
if (response.mfa_compliance) { if (response.mfa_compliance) {
setMfaCompliance(response.mfa_compliance); setMfaCompliance(response.mfa_compliance);
persistMfaCompliance(response.mfa_compliance); persistMfaCompliance(response.mfa_compliance);
} }
setRequiresMfaEnrollment(false); setRequiresMfaEnrollment(false);
navigate('/profile'); await checkOrgAdmin();
if (!skipNavigate) {
if (response.requires_org_setup) {
navigate('/org-setup', {
state: {
pendingInvites: response.pending_invites ?? [],
isFirstUser: false,
},
});
} else {
navigate('/profile');
}
}
} }
return { requiresTotp: false, requiresWebAuthn: false }; return {
}, [navigate]); requiresTotp: false,
requiresWebAuthn: false,
requiresOrgSetup: response.requires_org_setup,
pendingInvites: response.pending_invites,
};
}, [navigate, checkOrgAdmin]);
const verifyWebAuthn = useCallback(async () => { const verifyWebAuthn = useCallback(async () => {
// WebAuthn verification is handled directly in the LoginPage component // WebAuthn verification is handled directly in the LoginPage component
// This is a placeholder for consistency with the interface
console.log('[AuthContext] verifyWebAuthn called - verification handled in LoginPage');
}, []); }, []);
const verifyTotp = useCallback(async (code: string, isBackupCode = false) => { const verifyTotp = useCallback(async (code: string, isBackupCode = false, skipNavigate = false) => {
const response = await api.totp.verify(code, isBackupCode); const response = await api.totp.verify(code, isBackupCode);
// Store token explicitly before setting user state
// This ensures the token is available for any subsequent API calls
if (response.token) { if (response.token) {
tokenManager.setToken(response.token, response.expires_at ?? null); tokenManager.setToken(response.token, response.expires_at ?? null);
} }
setUser(response.user); setUser(response.user);
// Check for MFA compliance in response
try { try {
const compliance = await api.policies.getMyCompliance(); const compliance = await api.policies.getMyCompliance();
setMfaCompliance(compliance); setMfaCompliance(compliance);
@@ -263,14 +263,19 @@ export function AuthProvider({ children }: { children: ReactNode }) {
persistMfaCompliance(null); persistMfaCompliance(null);
} }
navigate('/profile'); await checkOrgAdmin();
}, [navigate]); if (!skipNavigate) {
navigate('/profile');
}
}, [navigate, checkOrgAdmin]);
const logout = useCallback(async () => { const logout = useCallback(async () => {
try { try {
await api.auth.logout(); await api.auth.logout();
} finally { } finally {
setUser(null); setUser(null);
setIsOrgAdmin(false);
setIsOrgMember(false);
setMfaCompliance(null); setMfaCompliance(null);
persistMfaCompliance(null); persistMfaCompliance(null);
setRequiresMfaEnrollment(false); setRequiresMfaEnrollment(false);
@@ -284,6 +289,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {
user, user,
isLoading, isLoading,
isAuthenticated: !!user, isAuthenticated: !!user,
isOrgAdmin,
isOrgMember,
mfaCompliance, mfaCompliance,
requiresMfaEnrollment, requiresMfaEnrollment,
login, login,
@@ -292,6 +299,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
logout, logout,
refreshUser, refreshUser,
refreshCompliance, refreshCompliance,
checkOrgAdmin,
}} }}
> >
{children} {children}
+76
View File
@@ -0,0 +1,76 @@
import {
createContext,
useContext,
useState,
useEffect,
useCallback,
ReactNode,
} from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Organization } from "@/lib/api";
import { useOrganizations } from "@/hooks/useOrganizations";
import { useAuth } from "@/contexts/AuthContext";
interface OrgContextType {
/** The currently selected organisation (null while loading or no memberships). */
selectedOrg: Organization | null;
/** Programmatically switch the active organisation and invalidate all org-scoped queries. */
selectOrg: (org: Organization) => void;
/** Convenience accessor for the selected org's ID. */
selectedOrgId: string | null;
}
const OrgContext = createContext<OrgContextType | null>(null);
export function OrgProvider({ children }: { children: ReactNode }) {
const { isAuthenticated } = useAuth();
const { data: organizations = [] } = useOrganizations();
const queryClient = useQueryClient();
const [selectedOrg, setSelectedOrg] = useState<Organization | null>(null);
// Auto-select the first org once the list arrives (or when the list changes
// and the previously selected org is no longer present, e.g. after deletion).
useEffect(() => {
if (!isAuthenticated) {
setSelectedOrg(null);
return;
}
if (organizations.length === 0) return;
setSelectedOrg((prev) => {
// Keep the current selection if it still exists in the updated list.
if (prev && organizations.some((o) => o.id === prev.id)) {
// Refresh the object in case name/role changed.
return organizations.find((o) => o.id === prev.id) ?? prev;
}
return organizations[0];
});
}, [organizations, isAuthenticated]);
const selectOrg = useCallback(
(org: Organization) => {
setSelectedOrg(org);
// Invalidate all organisation-scoped React Query caches so every page
// immediately re-fetches data for the newly selected org.
queryClient.invalidateQueries({ queryKey: ["organizations"] });
// Invalidate any queries keyed by the previous org id. The broadest
// approach is to remove all non-organisations queries so pages reload.
queryClient.invalidateQueries();
},
[queryClient],
);
return (
<OrgContext.Provider
value={{ selectedOrg, selectOrg, selectedOrgId: selectedOrg?.id ?? null }}
>
{children}
</OrgContext.Provider>
);
}
export function useOrg(): OrgContextType {
const ctx = useContext(OrgContext);
if (!ctx) throw new Error("useOrg must be used inside <OrgProvider>");
return ctx;
}
+34
View File
@@ -0,0 +1,34 @@
import { useParams } from "react-router-dom";
import { useOrganizations } from "@/hooks/useOrganizations";
import { useOrg } from "@/contexts/OrgContext";
/**
* Custom hook to get the current organization from URL params, or the
* globally-selected org from OrgContext (set via the TopBar org switcher).
*/
export function useCurrentOrganization() {
const params = useParams<{ orgId?: string }>();
const { data: organizations = [], isLoading } = useOrganizations();
const { selectedOrg } = useOrg();
// If orgId is in the URL params, use that specific org.
if (params.orgId) {
return {
org: organizations.find((org) => org.id === params.orgId) ?? organizations[0] ?? null,
isLoading,
};
}
// Otherwise use the org selected via the TopBar switcher (falls back to
// organizations[0] when OrgContext hasn't initialised yet).
return { org: selectedOrg ?? organizations[0] ?? null, isLoading };
}
/**
* Get the organization ID from URL params or the globally-selected org.
* Also returns isLoading so callers can distinguish "no org" from "still loading".
*/
export function useCurrentOrganizationId(): { orgId: string | null; isLoading: boolean } {
const { org, isLoading } = useCurrentOrganization();
return { orgId: org?.id || null, isLoading };
}
+1 -4
View File
@@ -14,11 +14,8 @@ export function useOrganizations() {
return useQuery<Organization[], ApiError>({ return useQuery<Organization[], ApiError>({
queryKey: ["organizations"], queryKey: ["organizations"],
queryFn: async () => { queryFn: async () => {
console.log('[useOrganizations] Fetching organizations...');
const response = await api.users.organizations(); const response = await api.users.organizations();
console.log('[useOrganizations] Response:', response); return Array.isArray(response.organizations) ? response.organizations : [];
console.log('[useOrganizations] Organizations array:', response.organizations);
return response.organizations;
}, },
// Only fetch when user is authenticated // Only fetch when user is authenticated
enabled: isAuthenticated, enabled: isAuthenticated,
+743 -16
View File
@@ -25,6 +25,10 @@ export interface User {
last_login_at: string | null; last_login_at: string | null;
created_at: string; created_at: string;
updated_at: string; updated_at: string;
// Fields present in admin list view
org_role?: string;
org_id?: string;
activated?: boolean;
} }
export interface Organization { export interface Organization {
@@ -80,6 +84,12 @@ export interface LoginResponse {
requires_webauthn?: boolean; requires_webauthn?: boolean;
requires_mfa_enrollment?: boolean; requires_mfa_enrollment?: boolean;
mfa_compliance?: MfaComplianceSummary; mfa_compliance?: MfaComplianceSummary;
/** Set on login when the user belongs to no organisations. */
requires_org_setup?: boolean;
/** Pending invitations for the user's email (present when requires_org_setup is true). */
pending_invites?: PendingInvite[];
/** True when the registering user is the very first user on this instance. */
is_first_user?: boolean;
} }
export interface TotpEnrollResponse { export interface TotpEnrollResponse {
@@ -167,6 +177,25 @@ export interface LinkedAccountsResponse {
unlink_available: boolean; unlink_available: boolean;
} }
export interface PrincipalOption {
id: string;
name: string;
description: string | null;
}
export interface MyPrincipalsOrg {
org_id: string;
org_name: string;
role: string;
is_admin: boolean;
my_principals: PrincipalOption[];
all_principals: PrincipalOption[]; // populated for admin/owner only
}
export interface MyPrincipalsResponse {
orgs: MyPrincipalsOrg[];
}
export interface OAuthAuthorizeResponse { export interface OAuthAuthorizeResponse {
authorization_url: string; authorization_url: string;
state: string; state: string;
@@ -211,42 +240,30 @@ export const tokenManager = {
if (token && expiry) { if (token && expiry) {
const expiryDate = new Date(expiry); const expiryDate = new Date(expiry);
if (expiryDate <= new Date()) { if (expiryDate <= new Date()) {
console.log('[TokenManager] Token expired, clearing');
tokenManager.clearToken(); tokenManager.clearToken();
return null; return null;
} }
} }
if (token) {
console.log('[TokenManager] Token retrieved:', token.substring(0, 20) + '...');
} else {
console.log('[TokenManager] No token found in localStorage');
}
return token; return token;
}, },
setToken: (token: string, expiresAt?: string | null): void => { setToken: (token: string, expiresAt?: string | null): void => {
console.log('[TokenManager] Setting token, expiresAt:', expiresAt);
localStorage.setItem(TOKEN_KEY, token); localStorage.setItem(TOKEN_KEY, token);
if (expiresAt) { if (expiresAt) {
localStorage.setItem(TOKEN_EXPIRY_KEY, expiresAt); localStorage.setItem(TOKEN_EXPIRY_KEY, expiresAt);
} else { } else {
localStorage.removeItem(TOKEN_EXPIRY_KEY); localStorage.removeItem(TOKEN_EXPIRY_KEY);
} }
console.log('[TokenManager] Token set successfully');
}, },
clearToken: (): void => { clearToken: (): void => {
console.log('[TokenManager] Clearing token from localStorage');
localStorage.removeItem(TOKEN_KEY); localStorage.removeItem(TOKEN_KEY);
localStorage.removeItem(TOKEN_EXPIRY_KEY); localStorage.removeItem(TOKEN_EXPIRY_KEY);
}, },
hasValidToken: (): boolean => { hasValidToken: (): boolean => {
const hasToken = tokenManager.getToken() !== null; return tokenManager.getToken() !== null;
console.log('[TokenManager] hasValidToken:', hasToken);
return hasToken;
}, },
}; };
@@ -292,9 +309,6 @@ async function request<T>(
const token = tokenManager.getToken(); const token = tokenManager.getToken();
if (token) { if (token) {
headers['Authorization'] = `Bearer ${token}`; headers['Authorization'] = `Bearer ${token}`;
console.log('[API] Added Authorization header for endpoint:', endpoint);
} else {
console.log('[API] WARNING: No token available for authenticated endpoint:', endpoint);
} }
} }
@@ -370,6 +384,55 @@ export const api = {
return response; return response;
}, },
register: async (email: string, password: string, full_name?: string): Promise<LoginResponse> => {
const response = await request<LoginResponse>('/auth/register', {
method: 'POST',
body: JSON.stringify({ email, password, password_confirm: password, full_name }),
}, false);
if (response.token) {
tokenManager.setToken(response.token, response.expires_at ?? null);
}
return response;
},
forgotPassword: (email: string): Promise<{ message: string }> =>
request<{ message: string }>('/auth/forgot-password', {
method: 'POST',
body: JSON.stringify({ email }),
}, false),
resetPassword: (token: string, password: string): Promise<{ message: string }> =>
request<{ message: string }>('/auth/reset-password', {
method: 'POST',
body: JSON.stringify({ token, password, password_confirm: password }),
}, false),
verifyEmail: (token: string): Promise<{ message: string }> =>
request<{ message: string }>('/auth/verify-email', {
method: 'POST',
body: JSON.stringify({ token }),
}, false),
resendVerification: (email: string): Promise<{ message: string }> =>
request<{ message: string }>('/auth/resend-verification', {
method: 'POST',
body: JSON.stringify({ email }),
}, false),
activate: (activation_key: string): Promise<{ message: string }> =>
request<{ message: string }>('/auth/activate', {
method: 'POST',
body: JSON.stringify({ activation_key }),
}, false),
resendActivation: (email: string): Promise<{ message: string }> =>
request<{ message: string }>('/auth/resend-activation', {
method: 'POST',
body: JSON.stringify({ email }),
}, false),
logout: async (): Promise<void> => { logout: async (): Promise<void> => {
try { try {
await request<void>('/auth/logout', { await request<void>('/auth/logout', {
@@ -392,9 +455,17 @@ export const api = {
body: JSON.stringify(data), body: JSON.stringify(data),
}), }),
// Delete the current user's own account (soft delete)
deleteMe: (requestConfig?: RequestConfig) =>
request<{ message: string }>('/users/me', { method: 'DELETE' }, true, requestConfig),
organizations: (requestConfig?: RequestConfig) => organizations: (requestConfig?: RequestConfig) =>
request<OrganizationsResponse>('/users/me/organizations', {}, true, requestConfig), request<OrganizationsResponse>('/users/me/organizations', {}, true, requestConfig),
// Get the current user's effective principals across all orgs
myPrincipals: (requestConfig?: RequestConfig) =>
request<MyPrincipalsResponse>('/users/me/principals', {}, true, requestConfig),
// Password change can return 401 for wrong current password - don't clear token // Password change can return 401 for wrong current password - don't clear token
changePassword: (currentPassword: string, newPassword: string, newPasswordConfirm: string) => changePassword: (currentPassword: string, newPassword: string, newPasswordConfirm: string) =>
request<{ message: string }>('/users/me/password', { request<{ message: string }>('/users/me/password', {
@@ -405,6 +476,101 @@ export const api = {
new_password_confirm: newPasswordConfirm, new_password_confirm: newPasswordConfirm,
}), }),
}, true, { clearTokenOn401: false }), }, true, { clearTokenOn401: false }),
// Get audit logs for the currently authenticated user
auditLogs: (params?: Record<string, string>, requestConfig?: RequestConfig) =>
request<{ audit_logs: AuditLogEntry[]; count: number; page: number; per_page: number; pages: number }>(
`/auth/audit-logs${params ? '?' + new URLSearchParams(params).toString() : ''}`,
{},
true,
requestConfig,
),
// Get pending (unaccepted) invitations for the logged-in user
getMyInvites: (requestConfig?: RequestConfig) =>
request<{ invites: PendingInvite[] }>('/users/me/invites', {}, true, requestConfig),
// Get the current user's department + principal memberships across all orgs
getMyMemberships: (requestConfig?: RequestConfig) =>
request<{ orgs: MyOrgMembership[] }>('/users/me/memberships', {}, true, requestConfig),
},
admin: {
// Get all system audit logs (admin view — returns all logs for org owners, own logs otherwise)
getAuditLogs: (params?: Record<string, string>, requestConfig?: RequestConfig) =>
request<{ audit_logs: AuditLogEntry[]; count: number; page: number; per_page: number; pages: number; is_admin_view: boolean }>(
`/audit-logs${params ? '?' + new URLSearchParams(params).toString() : ''}`,
{},
true,
requestConfig,
),
// List users visible to the calling admin
listUsers: (params?: Record<string, string>, requestConfig?: RequestConfig) =>
request<{ users: User[]; count: number; page: number; per_page: number; pages: number }>(
`/admin/users${params ? '?' + new URLSearchParams(params).toString() : ''}`,
{},
true,
requestConfig,
),
// Get a single user's profile + SSH keys (admin view)
getUser: (userId: string, requestConfig?: RequestConfig) =>
request<{ user: User; ssh_keys: SSHKey[] }>(`/admin/users/${userId}`, {}, true, requestConfig),
// Update a user's role in a shared org (admin action)
updateUserRole: (orgId: string, userId: string, role: string, requestConfig?: RequestConfig) =>
request<{ member: OrganizationMember }>(`/organizations/${orgId}/members/${userId}/role`, {
method: 'PATCH',
body: JSON.stringify({ role }),
}, true, requestConfig),
// List application-level OAuth provider configurations
listOAuthProviders: (requestConfig?: RequestConfig) =>
request<{ providers: { id: string; name: string; is_configured: boolean; is_enabled: boolean; client_id: string | null }[] }>(
'/admin/oauth/providers', {}, true, requestConfig,
),
// Create or update an application-level OAuth provider
configureOAuthProvider: (provider: string, clientId: string, clientSecret: string, isEnabled: boolean, requestConfig?: RequestConfig) =>
request<{ provider: { id: string; client_id: string; is_enabled: boolean } }>(
`/admin/oauth/providers/${provider}`,
{ method: 'PUT', body: JSON.stringify({ client_id: clientId, client_secret: clientSecret, is_enabled: isEnabled }) },
true,
requestConfig,
),
// Delete an application-level OAuth provider
deleteOAuthProvider: (provider: string, requestConfig?: RequestConfig) =>
request<Record<string, never>>(`/admin/oauth/providers/${provider}`, { method: 'DELETE' }, true, requestConfig),
// Suspend a user account (blocks login & CA issuance)
suspendUser: (userId: string, requestConfig?: RequestConfig) =>
request<{ user: User }>(`/admin/users/${userId}/suspend`, { method: 'POST' }, true, requestConfig),
// Restore a suspended user to active status
unsuspendUser: (userId: string, requestConfig?: RequestConfig) =>
request<{ user: User }>(`/admin/users/${userId}/unsuspend`, { method: 'POST' }, true, requestConfig),
// Permanently delete a user — revokes certs, cascades DB delete, unrecoverable
hardDeleteUser: (userId: string, requestConfig?: RequestConfig) =>
request<{ deleted_user_id: string; deleted_user_email: string; ssh_keys_deleted: number; certs_revoked: number }>(
`/admin/users/${userId}/delete`,
{ method: 'POST', body: JSON.stringify({ confirm: true }) },
true,
requestConfig,
),
// Get the cert policy for a department
getDeptCertPolicy: (orgId: string, deptId: string, requestConfig?: RequestConfig) =>
request<{ cert_policy: DeptCertPolicy }>(`/organizations/${orgId}/departments/${deptId}/cert-policy`, {}, true, requestConfig),
// Create or update the cert policy for a department
setDeptCertPolicy: (orgId: string, deptId: string, policy: Partial<DeptCertPolicy>, requestConfig?: RequestConfig) =>
request<{ cert_policy: DeptCertPolicy }>(`/organizations/${orgId}/departments/${deptId}/cert-policy`, {
method: 'PUT',
body: JSON.stringify(policy),
}, true, requestConfig),
}, },
totp: { totp: {
@@ -635,8 +801,477 @@ export const api = {
credentials: 'include', credentials: 'include',
}), }),
}, },
organizations: {
// Create a new organization (caller becomes owner)
create: (name: string, slug: string, description?: string) =>
request<{ organization: Organization }>('/organizations', {
method: 'POST',
body: JSON.stringify({ name, slug, description }),
}, true),
// Get organization by ID
getById: (orgId: string, requestConfig?: RequestConfig) =>
request<{ organization: Organization; member_count: number }>(`/organizations/${orgId}`, {}, true, requestConfig),
// Delete an organization (owner only; must have no other members)
deleteOrganization: (orgId: string, requestConfig?: RequestConfig) =>
request<{ message: string }>(`/organizations/${orgId}`, { method: 'DELETE' }, true, requestConfig),
// Get organization members
getMembers: (orgId: string, requestConfig?: RequestConfig) =>
request<{ members: OrganizationMember[]; count: number }>(`/organizations/${orgId}/members`, {}, true, requestConfig),
// Add member to organization
addMember: (orgId: string, email: string, role: string, requestConfig?: RequestConfig) =>
request<{ member: OrganizationMember }>(`/organizations/${orgId}/members`, {
method: 'POST',
body: JSON.stringify({ email, role }),
}, true, requestConfig),
// Remove member from organization
removeMember: (orgId: string, userId: string, requestConfig?: RequestConfig) =>
request<{ message: string }>(`/organizations/${orgId}/members/${userId}`, {
method: 'DELETE',
}, true, requestConfig),
// Update member role
updateMemberRole: (orgId: string, userId: string, role: string, requestConfig?: RequestConfig) =>
request<{ member: OrganizationMember }>(`/organizations/${orgId}/members/${userId}/role`, {
method: 'PATCH',
body: JSON.stringify({ role }),
}, true, requestConfig),
// Get organization audit logs
getAuditLogs: (orgId: string, params?: Record<string, string>, requestConfig?: RequestConfig) =>
request<{ audit_logs: AuditLogEntry[]; count: number }>(
`/organizations/${orgId}/audit-logs${params ? '?' + new URLSearchParams(params).toString() : ''}`,
{},
true,
requestConfig
),
// Get departments
getDepartments: (orgId: string, requestConfig?: RequestConfig) =>
request<{ departments: Department[]; count: number }>(`/organizations/${orgId}/departments`, {}, true, requestConfig),
// Create department
createDepartment: (orgId: string, name: string, description?: string, requestConfig?: RequestConfig) =>
request<{ department: Department }>(`/organizations/${orgId}/departments`, {
method: 'POST',
body: JSON.stringify({ name, description }),
}, true, requestConfig),
// Update department
updateDepartment: (orgId: string, deptId: string, data: { name?: string; description?: string }, requestConfig?: RequestConfig) =>
request<{ department: Department }>(`/organizations/${orgId}/departments/${deptId}`, {
method: 'PATCH',
body: JSON.stringify(data),
}, true, requestConfig),
// Delete department
deleteDepartment: (orgId: string, deptId: string, requestConfig?: RequestConfig) =>
request<{ message: string }>(`/organizations/${orgId}/departments/${deptId}`, {
method: 'DELETE',
}, true, requestConfig),
// Get department members
getDepartmentMembers: (orgId: string, deptId: string, requestConfig?: RequestConfig) =>
request<{ members: DepartmentMember[]; count: number }>(`/organizations/${orgId}/departments/${deptId}/members`, {}, true, requestConfig),
// Add member to department
addDepartmentMember: (orgId: string, deptId: string, email: string, requestConfig?: RequestConfig) =>
request<{ member: DepartmentMember }>(`/organizations/${orgId}/departments/${deptId}/members`, {
method: 'POST',
body: JSON.stringify({ email }),
}, true, requestConfig),
// Remove member from department
removeDepartmentMember: (orgId: string, deptId: string, userId: string, requestConfig?: RequestConfig) =>
request<{ message: string }>(`/organizations/${orgId}/departments/${deptId}/members/${userId}`, {
method: 'DELETE',
}, true, requestConfig),
// Get principals
getPrincipals: (orgId: string, requestConfig?: RequestConfig) =>
request<{ principals: Principal[]; count: number }>(`/organizations/${orgId}/principals`, {}, true, requestConfig),
// Create principal
createPrincipal: (orgId: string, name: string, description?: string, requestConfig?: RequestConfig) =>
request<{ principal: Principal }>(`/organizations/${orgId}/principals`, {
method: 'POST',
body: JSON.stringify({ name, description }),
}, true, requestConfig),
// Update principal
updatePrincipal: (orgId: string, principalId: string, data: { name?: string; description?: string }, requestConfig?: RequestConfig) =>
request<{ principal: Principal }>(`/organizations/${orgId}/principals/${principalId}`, {
method: 'PATCH',
body: JSON.stringify(data),
}, true, requestConfig),
// Delete principal
deletePrincipal: (orgId: string, principalId: string, requestConfig?: RequestConfig) =>
request<{ message: string }>(`/organizations/${orgId}/principals/${principalId}`, {
method: 'DELETE',
}, true, requestConfig),
// Get principal members
getPrincipalMembers: (orgId: string, principalId: string, requestConfig?: RequestConfig) =>
request<{ members: PrincipalMember[]; count: number }>(`/organizations/${orgId}/principals/${principalId}/members`, {}, true, requestConfig),
// Add member to principal
addPrincipalMember: (orgId: string, principalId: string, email: string, requestConfig?: RequestConfig) =>
request<{ member: PrincipalMember }>(`/organizations/${orgId}/principals/${principalId}/members`, {
method: 'POST',
body: JSON.stringify({ email }),
}, true, requestConfig),
// Remove member from principal
removePrincipalMember: (orgId: string, principalId: string, userId: string, requestConfig?: RequestConfig) =>
request<{ message: string }>(`/organizations/${orgId}/principals/${principalId}/members/${userId}`, {
method: 'DELETE',
}, true, requestConfig),
// Link principal to department
linkPrincipalToDepartment: (orgId: string, principalId: string, departmentId: string, requestConfig?: RequestConfig) =>
request<{ message: string }>(`/organizations/${orgId}/principals/${principalId}/departments/${departmentId}`, {
method: 'POST',
}, true, requestConfig),
// Unlink principal from department
unlinkPrincipalFromDepartment: (orgId: string, principalId: string, departmentId: string, requestConfig?: RequestConfig) =>
request<{ message: string }>(`/organizations/${orgId}/principals/${principalId}/departments/${departmentId}`, {
method: 'DELETE',
}, true, requestConfig),
// Get departments linked to a principal
getPrincipalDepartments: (orgId: string, principalId: string, requestConfig?: RequestConfig) =>
request<{ departments: Department[]; count: number }>(`/organizations/${orgId}/principals/${principalId}/departments`, {}, true, requestConfig),
// Get principals linked to a department
getDepartmentPrincipals: (orgId: string, deptId: string, requestConfig?: RequestConfig) =>
request<{ principals: Principal[]; count: number }>(`/organizations/${orgId}/departments/${deptId}/principals`, {}, true, requestConfig),
// Create invite token
createInvite: (orgId: string, email: string, role: string, requestConfig?: RequestConfig) =>
request<{ invite: OrgInvite }>(`/organizations/${orgId}/invites`, {
method: 'POST',
body: JSON.stringify({ email, role }),
}, true, requestConfig),
// List pending invites for an organization
getInvites: (orgId: string, requestConfig?: RequestConfig) =>
request<{ invites: OrgInvite[] }>(`/organizations/${orgId}/invites`, {}, true, requestConfig),
// Cancel (delete) an invite
cancelInvite: (orgId: string, inviteId: string, requestConfig?: RequestConfig) =>
request<{ message: string }>(`/organizations/${orgId}/invites/${inviteId}`, {
method: 'DELETE',
}, true, requestConfig),
// List OIDC clients
getClients: (orgId: string, requestConfig?: RequestConfig) =>
request<{ clients: OIDCClient[]; count: number }>(`/organizations/${orgId}/clients`, {}, true, requestConfig),
// Create OIDC client
createClient: (orgId: string, name: string, redirect_uris: string[], requestConfig?: RequestConfig) =>
request<{ client: OIDCClientWithSecret }>(`/organizations/${orgId}/clients`, {
method: 'POST',
body: JSON.stringify({ name, redirect_uris }),
}, true, requestConfig),
// Delete OIDC client
deleteClient: (orgId: string, clientId: string, requestConfig?: RequestConfig) =>
request<{ message: string }>(`/organizations/${orgId}/clients/${clientId}`, {
method: 'DELETE',
}, true, requestConfig),
// Send MFA reminder to a member
sendMfaReminder: (orgId: string, userId: string, requestConfig?: RequestConfig) =>
request<{ message: string }>(`/organizations/${orgId}/members/${userId}/send-mfa-reminder`, {
method: 'POST',
}, true, requestConfig),
// Transfer organization ownership to another member
transferOwnership: (orgId: string, newOwnerUserId: string, requestConfig?: RequestConfig) =>
request<{ previous_owner: OrganizationMember; new_owner: OrganizationMember }>(
`/organizations/${orgId}/transfer-ownership`,
{ method: 'POST', body: JSON.stringify({ new_owner_user_id: newOwnerUserId }) },
true,
requestConfig,
),
// List Certificate Authorities for an org
getCAs: (orgId: string, requestConfig?: RequestConfig) =>
request<{ cas: OrgCA[]; count: number }>(`/organizations/${orgId}/cas`, {}, true, requestConfig),
// Create a new Certificate Authority for an org
createCA: (orgId: string, data: { name: string; description?: string; ca_type?: 'user' | 'host'; key_type?: 'ed25519' | 'rsa' | 'ecdsa'; default_cert_validity_hours?: number; max_cert_validity_hours?: number }, requestConfig?: RequestConfig) =>
request<{ ca: OrgCA }>(`/organizations/${orgId}/cas`, {
method: 'POST',
body: JSON.stringify(data),
}, true, requestConfig),
// Update CA configuration
updateCA: (orgId: string, caId: string, data: { default_cert_validity_hours?: number; max_cert_validity_hours?: number }, requestConfig?: RequestConfig) =>
request<{ ca: OrgCA }>(`/organizations/${orgId}/cas/${caId}`, {
method: 'PATCH',
body: JSON.stringify(data),
}, true, requestConfig),
// Rotate (replace) a CA's key pair — returns updated CA + old_fingerprint
rotateCA: (orgId: string, caId: string, data?: { key_type?: 'ed25519' | 'rsa' | 'ecdsa'; reason?: string }, requestConfig?: RequestConfig) =>
request<{ ca: OrgCA; old_fingerprint: string }>(`/organizations/${orgId}/cas/${caId}/rotate`, {
method: 'POST',
body: JSON.stringify(data ?? {}),
}, true, requestConfig),
// Soft-delete a CA
deleteCA: (orgId: string, caId: string, requestConfig?: RequestConfig) =>
request<{ ca_id: string }>(`/organizations/${orgId}/cas/${caId}`, {
method: 'DELETE',
}, true, requestConfig),
},
invites: {
// Get invite details by token (unauthenticated)
getInfo: (token: string) =>
request<{ email: string; organization: { id: string; name: string }; role: string; user_exists?: boolean }>(
`/invites/${token}`,
{},
false,
),
// Accept invite (unauthenticated) — password/name only needed for new accounts
accept: (token: string, full_name?: string, password?: string) =>
request<LoginResponse>(
`/invites/${token}/accept`,
{
method: 'POST',
body: JSON.stringify({ full_name, password, password_confirm: password }),
},
false,
),
},
ssh: {
// List all SSH keys for the current user
listKeys: (requestConfig?: RequestConfig) =>
request<SSHKeysResponse>('/ssh/keys', {}, true, requestConfig),
// Add a new SSH public key
addKey: (public_key: string, description?: string, requestConfig?: RequestConfig) =>
request<SSHKey>('/ssh/keys', {
method: 'POST',
body: JSON.stringify({ public_key, description }),
}, true, requestConfig),
// Delete an SSH key
deleteKey: (keyId: string, requestConfig?: RequestConfig) =>
request<{ status: string }>(`/ssh/keys/${keyId}`, {
method: 'DELETE',
}, true, requestConfig),
// Update SSH key description
updateKeyDescription: (keyId: string, description: string, requestConfig?: RequestConfig) =>
request<SSHKey>(`/ssh/keys/${keyId}/update-description`, {
method: 'PATCH',
body: JSON.stringify({ description }),
}, true, requestConfig),
// Get a verification challenge for a key
getChallenge: (keyId: string, requestConfig?: RequestConfig) =>
request<SSHChallengeResponse>(`/ssh/keys/${keyId}/verify`, {}, true, requestConfig),
// Submit signature to verify key ownership
verifyKey: (keyId: string, signature: string, requestConfig?: RequestConfig) =>
request<SSHVerifyResponse>(`/ssh/keys/${keyId}/verify`, {
method: 'POST',
body: JSON.stringify({ signature, action: 'verify_signature' }),
}, true, requestConfig),
// Sign a certificate for the given key
signCertificate: (key_id: string, principals?: string[], cert_type?: 'user' | 'host', expiry_hours?: number, requestConfig?: RequestConfig) =>
request<SSHSignResponse>('/ssh/sign', {
method: 'POST',
body: JSON.stringify({ key_id, principals, cert_type, expiry_hours }),
}, true, requestConfig),
// Get the merged department certificate policy for the current user (used in sign dialog)
getMyDeptCertPolicy: (requestConfig?: RequestConfig) =>
request<{ policy: DeptCertPolicy }>('/ssh/dept-cert-policy', {}, true, requestConfig),
// List issued certificates for the current user
listCertificates: (requestConfig?: RequestConfig) =>
request<{ certificates: SSHCertificate[]; count: number }>('/ssh/certificates', {}, true, requestConfig),
// Get a single certificate (includes full cert text)
getCertificate: (certId: string, requestConfig?: RequestConfig) =>
request<SSHCertificate>(`/ssh/certificates/${certId}`, {}, true, requestConfig),
// Revoke a certificate
revokeCertificate: (certId: string, reason?: string, requestConfig?: RequestConfig) =>
request<{ status: string; cert_id: string; reason: string }>(`/ssh/certificates/${certId}/revoke`, {
method: 'POST',
body: JSON.stringify({ reason }),
}, true, requestConfig),
// Get the CA public key for the current user's org
getCaPublicKey: (requestConfig?: RequestConfig) =>
request<{ public_key: string; fingerprint: string; ca_name: string; source: string }>('/ssh/ca/public-key', {}, true, requestConfig),
// Add SSH key on behalf of another user (admin)
adminAddKey: (userId: string, public_key: string, description?: string, requestConfig?: RequestConfig) =>
request<SSHKey>(`/ssh/keys/admin/${userId}`, {
method: 'POST',
body: JSON.stringify({ public_key, description }),
}, true, requestConfig),
// List CA permissions for a CA
listCaPermissions: (caId: string, requestConfig?: RequestConfig) =>
request<{ ca_id: string; permissions: CAPermission[]; open_to_all: boolean }>(`/ssh/ca/${caId}/permissions`, {}, true, requestConfig),
// Grant a user permission on a CA
addCaPermission: (caId: string, user_id: string, permission: 'sign' | 'admin', requestConfig?: RequestConfig) =>
request<{ message: string; permission: CAPermission }>(`/ssh/ca/${caId}/permissions`, {
method: 'POST',
body: JSON.stringify({ user_id, permission }),
}, true, requestConfig),
// Revoke a user's CA permission
removeCaPermission: (caId: string, userId: string, requestConfig?: RequestConfig) =>
request<{ message: string }>(`/ssh/ca/${caId}/permissions/${userId}`, {
method: 'DELETE',
}, true, requestConfig),
},
}; };
// Organization types
export interface OrganizationMember {
id: string;
user_id: string;
organization_id: string;
role: string;
created_at: string;
updated_at: string;
user?: User;
}
export interface AuditLogEntry {
id: string;
action: string;
user_id: string | null;
organization_id: string | null;
resource_type: string | null;
resource_id: string | null;
ip_address: string | null;
user_agent: string | null;
request_id: string | null;
description: string | null;
success: boolean;
error_message: string | null;
metadata?: Record<string, unknown>;
created_at: string;
updated_at: string;
user?: User;
}
export interface Department {
id: string;
organization_id: string;
name: string;
description: string | null;
created_at: string;
updated_at: string;
deleted_at: string | null;
}
export const STANDARD_SSH_EXTENSIONS = [
'permit-X11-forwarding',
'permit-agent-forwarding',
'permit-pty',
'permit-port-forwarding',
'permit-user-rc',
] as const;
export interface DeptCertPolicy {
department_id: string;
allow_user_expiry: boolean;
default_expiry_hours: number;
max_expiry_hours: number;
allowed_extensions: string[];
custom_extensions: string[];
all_extensions?: string[];
standard_extensions?: string[];
}
export interface PendingInvite {
token: string;
organization: { id: string; name: string };
role: string;
expires_at: string;
}
export interface MyOrgMembership {
org_id: string;
org_name: string;
role: string;
departments: { id: string; name: string; description: string | null }[];
principals: { id: string; name: string; description: string | null; via_department: boolean }[];
}
export interface DepartmentMember {
id: string;
user_id: string;
department_id: string;
created_at: string;
updated_at: string;
user?: User;
}
export interface Principal {
id: string;
organization_id: string;
name: string;
description: string | null;
created_at: string;
updated_at: string;
deleted_at: string | null;
}
export interface PrincipalMember {
id: string;
user_id: string;
principal_id: string;
created_at: string;
updated_at: string;
user?: User;
}
export interface OrgInvite {
id: string;
email: string;
role: string;
expires_at: string;
invite_link?: string; // only present on create response (dev/when email disabled)
}
export interface OIDCClient {
id: string;
name: string;
client_id: string;
redirect_uris: string[];
scopes: string[];
grant_types: string[];
is_active: boolean;
created_at: string;
}
export interface OIDCClientWithSecret extends OIDCClient {
client_secret: string;
}
// Policy types // Policy types
export interface OrgPolicyResponse { export interface OrgPolicyResponse {
security_policy: { security_policy: {
@@ -673,6 +1308,98 @@ export interface OrgComplianceMember {
export { ApiError }; export { ApiError };
// SSH Key types
export interface SSHKey {
id: string;
user_id: string;
public_key: string;
description: string | null;
key_type: string | null;
fingerprint: string | null;
verified: boolean;
verified_at: string | null;
created_at: string;
updated_at: string;
}
export interface SSHKeysResponse {
keys: SSHKey[];
count: number;
}
export interface SSHChallengeResponse {
challenge_text: string;
validationText: string;
key_id: string;
}
export interface SSHVerifyResponse {
verified: boolean;
}
export interface SSHCertificate {
id: string;
user_id: string;
ssh_key_id: string | null;
certificate: string;
serial: number | null;
key_id: string | null;
cert_type: string;
principals: string[];
valid_after: string;
valid_before: string;
revoked: boolean;
status: string;
created_at: string;
}
export interface SSHSignResponse {
certificate: string;
serial: number;
principals: string[];
valid_after: string;
valid_before: string;
cert_id?: string;
}
export interface CAPermission {
id: string;
ca_id: string;
user_id: string;
user_email: string | null;
permission: 'sign' | 'admin';
created_at: string;
}
export interface OrgCA {
id: string;
organization_id: string | null;
name: string;
description: string | null;
ca_type: 'user' | 'host';
key_type: string;
public_key: string;
fingerprint: string;
is_active: boolean;
/** True when this entry represents the server-wide config-file CA.
* System CAs are read-only — they cannot be edited, deleted, or replaced
* from the UI. */
is_system?: boolean;
default_cert_validity_hours: number;
max_cert_validity_hours: number;
total_certs: number;
active_certs: number;
revoked_certs: number;
/** Next serial number that will be assigned when a certificate is issued. */
next_serial_number: number | null;
created_at: string | null;
updated_at: string | null;
/** Set when the key was last rotated. */
rotated_at: string | null;
/** Reason provided when the key was last rotated. */
rotation_reason: string | null;
}
// Reusable 403 error handler for API calls // Reusable 403 error handler for API calls
// Shows a user-friendly toast message when access is denied // Shows a user-friendly toast message when access is denied
export function create403Handler(toastFn: (options: { title: string; description: string; variant: "destructive" }) => void) { export function create403Handler(toastFn: (options: { title: string; description: string; variant: "destructive" }) => void) {
+11 -3
View File
@@ -1,13 +1,21 @@
import { useEffect } from "react"; import { useEffect } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { useAuth } from "@/contexts/AuthContext";
const Index = () => { const Index = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const { isAuthenticated, isOrgMember, isLoading } = useAuth();
useEffect(() => { useEffect(() => {
// Redirect to login for now - will be replaced with auth check if (isLoading) return; // Wait for auth check to complete
navigate("/login");
}, [navigate]); if (isAuthenticated) {
// If the user has no org yet, send them to the org-setup page first
navigate(isOrgMember ? "/profile" : "/org-setup", { replace: true });
} else {
navigate("/login");
}
}, [isLoading, isAuthenticated, isOrgMember, navigate]);
return null; return null;
}; };
+733
View File
@@ -0,0 +1,733 @@
import { useState, useCallback, useEffect } from "react";
import {
Search,
User,
CheckCircle,
XCircle,
Key,
Loader2,
Plus,
ChevronRight,
ShieldCheck,
Shield,
Ban,
UserCheck,
AlertTriangle,
Trash2,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Textarea } from "@/components/ui/textarea";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { api, User as ApiUser, SSHKey, ApiError } from "@/lib/api";
import { useAuth } from "@/contexts/AuthContext";
function formatDate(d: string | null) {
if (!d) return "—";
return new Date(d).toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });
}
function isSuspended(status: string | undefined) {
return status === "suspended" || status === "compliance_suspended";
}
function RoleBadge({ role }: { role: string }) {
const r = (role || "").toLowerCase();
if (r === "owner") {
return (
<Badge className="bg-purple-500/10 text-purple-600 border-purple-200 text-xs">
<ShieldCheck className="w-3 h-3 mr-1" />Owner
</Badge>
);
}
if (r === "admin") {
return (
<Badge className="bg-blue-500/10 text-blue-600 border-blue-200 text-xs">
<Shield className="w-3 h-3 mr-1" />Admin
</Badge>
);
}
return (
<Badge variant="outline" className="text-xs text-muted-foreground">
Member
</Badge>
);
}
export default function AdminUsersPage() {
const { toast } = useToast();
const { user: currentUser } = useAuth();
// User list
const [users, setUsers] = useState<ApiUser[]>([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [pages, setPages] = useState(1);
const [isLoading, setIsLoading] = useState(false);
const [search, setSearch] = useState("");
const [debouncedSearch, setDebouncedSearch] = useState("");
const [roleFilter, setRoleFilter] = useState("all");
// Debounce search
useEffect(() => {
const t = setTimeout(() => setDebouncedSearch(search), 300);
return () => clearTimeout(t);
}, [search]);
// User detail drawer
const [selectedUser, setSelectedUser] = useState<ApiUser | null>(null);
const [userSshKeys, setUserSshKeys] = useState<SSHKey[]>([]);
const [isDrawerLoading, setIsDrawerLoading] = useState(false);
// Role update
const [isUpdatingRole, setIsUpdatingRole] = useState(false);
// Admin add SSH key dialog
const [showAddKey, setShowAddKey] = useState(false);
const [addKeyPublicKey, setAddKeyPublicKey] = useState("");
const [addKeyDescription, setAddKeyDescription] = useState("");
const [isAddingKey, setIsAddingKey] = useState(false);
const [addKeyError, setAddKeyError] = useState<string | null>(null);
// Suspend / unsuspend
const [isSuspending, setIsSuspending] = useState(false);
const [showSuspendConfirm, setShowSuspendConfirm] = useState(false);
// Hard delete
const [showHardDelete, setShowHardDelete] = useState(false);
const [hardDeleteConfirmEmail, setHardDeleteConfirmEmail] = useState("");
const [isHardDeleting, setIsHardDeleting] = useState(false);
// ── Fetch users ─────────────────────────────────────────────────────────────
const fetchUsers = useCallback(async (q: string, pg: number) => {
setIsLoading(true);
try {
const params: Record<string, string> = { page: String(pg), per_page: "50" };
if (q) params.q = q;
const data = await api.admin.listUsers(params);
setUsers(data.users);
setTotal(data.count);
setPages(data.pages);
} catch (err) {
if (err instanceof ApiError && err.code === 403) {
toast({
variant: "destructive",
title: "Access denied",
description: "Admin or owner role required to view all users.",
});
} else {
toast({ variant: "destructive", title: "Failed to load users" });
}
} finally {
setIsLoading(false);
}
}, [toast]);
useEffect(() => {
setPage(1);
fetchUsers(debouncedSearch, 1);
}, [debouncedSearch, fetchUsers]);
useEffect(() => {
fetchUsers(debouncedSearch, page);
}, [page]); // eslint-disable-line react-hooks/exhaustive-deps
// ── Open user drawer ─────────────────────────────────────────────────────────
const openUserDrawer = async (user: ApiUser) => {
setSelectedUser(user);
setUserSshKeys([]);
setIsDrawerLoading(true);
try {
const data = await api.admin.getUser(user.id);
setUserSshKeys(data.ssh_keys);
} catch {
// Non-fatal — drawer still shows basic user info
} finally {
setIsDrawerLoading(false);
}
};
// ── Update role ──────────────────────────────────────────────────────────────
const handleRoleChange = async (newRole: string) => {
if (!selectedUser || !selectedUser.org_id) return;
setIsUpdatingRole(true);
try {
await api.admin.updateUserRole(selectedUser.org_id, selectedUser.id, newRole.toUpperCase());
const updated = { ...selectedUser, org_role: newRole };
setSelectedUser(updated);
setUsers((prev) =>
prev.map((u) => (u.id === selectedUser.id ? { ...u, org_role: newRole } : u))
);
toast({
title: "Role updated",
description: `${selectedUser.full_name || selectedUser.email} is now a ${newRole}.`,
});
} catch (err) {
toast({
variant: "destructive",
title: "Failed to update role",
description: err instanceof ApiError ? err.message : "Something went wrong",
});
} finally {
setIsUpdatingRole(false);
}
};
// ── Admin add SSH key ────────────────────────────────────────────────────────
const handleAddKey = async () => {
if (!selectedUser) return;
setAddKeyError(null);
if (!addKeyPublicKey.trim()) {
setAddKeyError("Public key is required");
return;
}
setIsAddingKey(true);
try {
const key = await api.ssh.adminAddKey(selectedUser.id, addKeyPublicKey.trim(), addKeyDescription.trim() || undefined);
setUserSshKeys((prev) => [...prev, key]);
toast({ title: "SSH key added", description: `Key added for ${selectedUser.email}` });
setShowAddKey(false);
setAddKeyPublicKey("");
setAddKeyDescription("");
} catch (err) {
setAddKeyError(err instanceof ApiError ? err.message : "Failed to add key");
} finally {
setIsAddingKey(false);
}
};
// ── Suspend / Unsuspend user ─────────────────────────────────────────────────
const handleSuspend = async () => {
if (!selectedUser) return;
setIsSuspending(true);
try {
const data = await api.admin.suspendUser(selectedUser.id);
const updated = { ...selectedUser, status: data.user.status };
setSelectedUser(updated);
setUsers((prev) => prev.map((u) => u.id === selectedUser.id ? { ...u, status: data.user.status } : u));
setShowSuspendConfirm(false);
toast({ title: "User suspended", description: `${selectedUser.full_name || selectedUser.email} has been suspended.` });
} catch (err) {
setShowSuspendConfirm(false);
if (err instanceof ApiError && err.type === "OWNER_PROTECTION") {
toast({
variant: "destructive",
title: "Cannot suspend organization owner",
description: "Transfer ownership to another member before suspending this account.",
});
} else {
toast({ variant: "destructive", title: "Failed to suspend user", description: err instanceof ApiError ? err.message : "Something went wrong" });
}
} finally {
setIsSuspending(false);
}
};
const handleUnsuspend = async () => {
if (!selectedUser) return;
setIsSuspending(true);
try {
const data = await api.admin.unsuspendUser(selectedUser.id);
const updated = { ...selectedUser, status: data.user.status };
setSelectedUser(updated);
setUsers((prev) => prev.map((u) => u.id === selectedUser.id ? { ...u, status: data.user.status } : u));
toast({ title: "User unsuspended", description: `${selectedUser.full_name || selectedUser.email} is now active.` });
} catch (err) {
toast({ variant: "destructive", title: "Failed to unsuspend user", description: err instanceof ApiError ? err.message : "Something went wrong" });
} finally {
setIsSuspending(false);
}
};
// ── Hard delete user ─────────────────────────────────────────────────────────
const handleHardDelete = async () => {
if (!selectedUser) return;
setIsHardDeleting(true);
try {
const result = await api.admin.hardDeleteUser(selectedUser.id);
setUsers((prev) => prev.filter((u) => u.id !== selectedUser.id));
setTotal((t) => t - 1);
setShowHardDelete(false);
setSelectedUser(null);
toast({
title: "User permanently deleted",
description: `${result.deleted_user_email}${result.certs_revoked} cert(s) revoked, ${result.ssh_keys_deleted} key(s) deleted.`,
});
} catch (err) {
toast({
variant: "destructive",
title: "Failed to delete user",
description: err instanceof ApiError ? err.message : "Something went wrong",
});
} finally {
setIsHardDeleting(false);
}
};
// Filter by role client-side
const filteredUsers = users.filter((u) => {
if (roleFilter === "all") return true;
const r = (u.org_role || "member").toLowerCase();
return r === roleFilter;
});
// ──────────────────────────────────────────────────────────────────────────────
return (
<div className="page-container">
<div className="page-header">
<h1 className="page-title">User Management</h1>
<p className="page-description">
View and manage users across your organizations
</p>
</div>
{/* Search + filter bar */}
<div className="flex gap-3 mb-4">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
className="pl-9"
placeholder="Search by name or email…"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</div>
<Select value={roleFilter} onValueChange={setRoleFilter}>
<SelectTrigger className="w-[160px]">
<SelectValue placeholder="All roles" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All roles</SelectItem>
<SelectItem value="owner">Owner</SelectItem>
<SelectItem value="admin">Admin</SelectItem>
<SelectItem value="member">Member</SelectItem>
</SelectContent>
</Select>
</div>
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<User className="w-4 h-4" />
Users
{!isLoading && <Badge variant="secondary" className="ml-1">{total}</Badge>}
</CardTitle>
<CardDescription>Click a user to view details and manage their role or SSH keys</CardDescription>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
) : filteredUsers.length === 0 ? (
<div className="text-center py-12 text-muted-foreground">
<User className="w-10 h-10 mx-auto mb-3 opacity-40" />
<p className="text-sm">{debouncedSearch ? "No users match your search" : "No users found"}</p>
</div>
) : (
<div className="space-y-1">
{filteredUsers.map((user) => (
<button
key={user.id}
className="w-full flex items-center justify-between p-3 rounded-lg border hover:bg-accent/50 transition-colors text-left"
onClick={() => openUserDrawer(user)}
>
<div className="flex items-center gap-3 min-w-0">
<div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0">
<User className="w-4 h-4 text-primary" />
</div>
<div className="min-w-0">
<p className="text-sm font-medium truncate">{user.full_name || user.email}</p>
<p className="text-xs text-muted-foreground truncate">{user.email}</p>
</div>
</div>
<div className="flex items-center gap-2 flex-shrink-0">
<RoleBadge role={user.org_role || "member"} />
{isSuspended(user.status) && (
<Badge variant="outline" className="text-xs text-red-600 border-red-300 bg-red-50">
<Ban className="w-3 h-3 mr-1" />Suspended
</Badge>
)}
{user.activated === false && (
<Badge variant="outline" className="text-xs text-amber-600 border-amber-300">
Not activated
</Badge>
)}
<ChevronRight className="w-4 h-4 text-muted-foreground" />
</div>
</button>
))}
</div>
)}
{/* Pagination */}
{pages > 1 && (
<div className="flex items-center justify-between mt-4 pt-4 border-t">
<p className="text-xs text-muted-foreground">
Page {page} of {pages} · {total} total
</p>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setPage((p) => Math.max(1, p - 1))}
disabled={page === 1}
>
Previous
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setPage((p) => Math.min(pages, p + 1))}
disabled={page === pages}
>
Next
</Button>
</div>
</div>
)}
</CardContent>
</Card>
{/* ── User detail drawer ─────────────────────────────────────────────────── */}
<Sheet open={!!selectedUser} onOpenChange={(open) => { if (!open) setSelectedUser(null); }}>
<SheetContent className="w-full sm:max-w-lg overflow-y-auto">
{selectedUser && (
<>
<SheetHeader className="mb-4">
<SheetTitle className="flex items-center gap-2">
<User className="w-5 h-5" />
{selectedUser.full_name || selectedUser.email}
</SheetTitle>
<SheetDescription>{selectedUser.email}</SheetDescription>
</SheetHeader>
{/* Basic info */}
<div className="space-y-3 mb-6">
<div className="grid grid-cols-2 gap-2 text-sm">
<span className="text-muted-foreground">Status</span>
<span className="flex items-center gap-1">
{isSuspended(selectedUser.status) ? (
<><Ban className="w-4 h-4 text-red-500" /><span className="text-red-600 font-medium">Suspended{selectedUser.status === "compliance_suspended" ? " (compliance)" : ""}</span></>
) : (
<><CheckCircle className="w-4 h-4 text-green-500" /><span className="text-green-600">Active</span></>
)}
</span>
<span className="text-muted-foreground">Joined</span>
<span>{formatDate(selectedUser.created_at)}</span>
<span className="text-muted-foreground">Activated</span>
<span className="flex items-center gap-1">
{selectedUser.activated === false ? (
<><XCircle className="w-4 h-4 text-amber-500" /> No</>
) : (
<><CheckCircle className="w-4 h-4 text-green-500" /> Yes</>
)}
</span>
<span className="text-muted-foreground">Last login</span>
<span>{formatDate(selectedUser.last_login_at)}</span>
</div>
</div>
{/* Suspend / Unsuspend — only for other users */}
{selectedUser.id !== currentUser?.id && (
<div className="mb-6 p-4 border rounded-lg space-y-3">
<h3 className="text-sm font-semibold flex items-center gap-2">
<Ban className="w-4 h-4" />
Account Access
</h3>
{isSuspended(selectedUser.status) ? (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">
{selectedUser.status === "compliance_suspended"
? "This account is suspended due to MFA compliance. The user cannot log in or request certificates."
: "This account is suspended. The user cannot log in or request certificates."}
</p>
<Button
size="sm"
variant="outline"
onClick={handleUnsuspend}
disabled={isSuspending}
className="text-green-600 border-green-300 hover:bg-green-50"
>
{isSuspending ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <UserCheck className="w-4 h-4 mr-2" />}
Restore account
</Button>
</div>
) : (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">Suspending blocks this user from logging in and requesting SSH certificates.</p>
<Button
size="sm"
variant="outline"
onClick={() => setShowSuspendConfirm(true)}
disabled={isSuspending}
className="text-red-600 border-red-300 hover:bg-red-50"
>
<Ban className="w-4 h-4 mr-2" />
Suspend account
</Button>
</div>
)}
</div>
)}
{/* Role management — only if not viewing yourself and user has org_id */}
{selectedUser.org_id && selectedUser.id !== currentUser?.id && (
<div className="mb-6 p-4 border rounded-lg space-y-3">
<h3 className="text-sm font-semibold flex items-center gap-2">
<Shield className="w-4 h-4" />
Organization Role
</h3>
<div className="flex items-center gap-3">
<Select
value={(selectedUser.org_role || "member").toLowerCase()}
onValueChange={handleRoleChange}
disabled={isUpdatingRole || (selectedUser.org_role || "").toLowerCase() === "owner"}
>
<SelectTrigger className="flex-1">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="member">Member</SelectItem>
<SelectItem value="admin">Admin</SelectItem>
<SelectItem value="owner">Owner</SelectItem>
</SelectContent>
</Select>
{isUpdatingRole && <Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />}
</div>
{(selectedUser.org_role || "").toLowerCase() === "owner" && (
<p className="text-xs text-muted-foreground">Owner role cannot be changed here. Transfer ownership from the Members page.</p>
)}
</div>
)}
{/* SSH Keys section */}
<div className="space-y-3">
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold flex items-center gap-2">
<Key className="w-4 h-4" />
SSH Keys
</h3>
<Button size="sm" variant="outline" onClick={() => setShowAddKey(true)}>
<Plus className="w-3 h-3 mr-1" />
Add key
</Button>
</div>
{isDrawerLoading ? (
<div className="flex items-center justify-center py-6">
<Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
</div>
) : userSshKeys.length === 0 ? (
<div className="text-center py-6 text-muted-foreground text-sm">
No SSH keys registered
</div>
) : (
<div className="space-y-2">
{userSshKeys.map((k) => (
<div key={k.id} className="p-3 border rounded-lg text-sm">
<div className="flex items-center gap-2 mb-1">
<span className="font-medium">{k.description || <em className="text-muted-foreground">No description</em>}</span>
{k.verified ? (
<Badge className="bg-green-500/10 text-green-600 border-0 text-xs">
<CheckCircle className="w-3 h-3 mr-1" />Verified
</Badge>
) : (
<Badge variant="outline" className="text-xs text-amber-600 border-amber-300">
Unverified
</Badge>
)}
</div>
<div className="text-xs text-muted-foreground font-mono truncate">
{k.fingerprint ?? k.public_key.slice(0, 64) + "…"}
</div>
<div className="text-xs text-muted-foreground mt-1">
Added {formatDate(k.created_at)}
</div>
</div>
))}
</div>
)}
</div>
{/* Danger zone — Hard delete */}
{selectedUser.id !== currentUser?.id && (
<div className="mt-6 p-4 border border-destructive/30 rounded-lg space-y-3">
<h3 className="text-sm font-semibold flex items-center gap-2 text-destructive">
<Trash2 className="w-4 h-4" />
Danger Zone
</h3>
<p className="text-sm text-muted-foreground">
Permanently delete this account. This cannot be undone all SSH keys and certificates will be revoked immediately.
</p>
<Button
size="sm"
variant="outline"
onClick={() => { setHardDeleteConfirmEmail(""); setShowHardDelete(true); }}
className="text-destructive border-destructive/40 hover:bg-destructive/10"
>
<Trash2 className="w-4 h-4 mr-2" />
Permanently delete account
</Button>
</div>
)}
</>
)}
</SheetContent>
</Sheet>
{/* ── Admin add SSH key dialog ───────────────────────────────────────────── */}
<Dialog open={showAddKey} onOpenChange={(open) => { setShowAddKey(open); setAddKeyError(null); }}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Add SSH Key for {selectedUser?.email}</DialogTitle>
<DialogDescription>
Add an SSH public key on behalf of this user (admin action).
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2">
{addKeyError && (
<div className="p-3 rounded-md bg-destructive/10 text-destructive text-sm">{addKeyError}</div>
)}
<div className="space-y-2">
<Label>Public key</Label>
<Textarea
placeholder="ssh-ed25519 AAAA..."
value={addKeyPublicKey}
onChange={(e) => setAddKeyPublicKey(e.target.value)}
className="font-mono text-xs min-h-[80px]"
disabled={isAddingKey}
/>
</div>
<div className="space-y-2">
<Label>Description <span className="text-muted-foreground">(optional)</span></Label>
<Input
placeholder="Laptop key"
value={addKeyDescription}
onChange={(e) => setAddKeyDescription(e.target.value)}
disabled={isAddingKey}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setShowAddKey(false)} disabled={isAddingKey}>
Cancel
</Button>
<Button onClick={handleAddKey} disabled={isAddingKey || !addKeyPublicKey.trim()}>
{isAddingKey && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
Add key
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* ── Suspend confirmation dialog ───────────────────────────────────────── */}
<Dialog open={showSuspendConfirm} onOpenChange={setShowSuspendConfirm}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2 text-red-600">
<AlertTriangle className="w-5 h-5" />
Suspend account?
</DialogTitle>
<DialogDescription>
<strong>{selectedUser?.full_name || selectedUser?.email}</strong> will be blocked from logging in and requesting SSH certificates. You can restore their access at any time.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setShowSuspendConfirm(false)} disabled={isSuspending}>
Cancel
</Button>
<Button
variant="destructive"
onClick={handleSuspend}
disabled={isSuspending}
>
{isSuspending && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
Suspend
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* ── Hard delete confirmation ──────────────────────────────────────────── */}
<Dialog
open={showHardDelete}
onOpenChange={(open) => { setShowHardDelete(open); if (!open) setHardDeleteConfirmEmail(""); }}
>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2 text-destructive">
<Trash2 className="w-5 h-5" />
Permanently delete account?
</DialogTitle>
<DialogDescription>
This will <strong>permanently</strong> delete{" "}
<strong>{selectedUser?.full_name || selectedUser?.email}</strong>,
revoke all their SSH certificates, and remove all their SSH keys. This action cannot be undone.
</DialogDescription>
</DialogHeader>
<div className="py-2 space-y-2">
<Label className="text-sm">
Type <span className="font-mono font-semibold">{selectedUser?.email}</span> to confirm
</Label>
<Input
value={hardDeleteConfirmEmail}
onChange={(e) => setHardDeleteConfirmEmail(e.target.value)}
placeholder={selectedUser?.email ?? ""}
disabled={isHardDeleting}
className="font-mono"
/>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => setShowHardDelete(false)}
disabled={isHardDeleting}
>
Cancel
</Button>
<Button
variant="destructive"
onClick={handleHardDelete}
disabled={isHardDeleting || hardDeleteConfirmEmail !== selectedUser?.email}
>
{isHardDeleting && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
Delete permanently
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
+312
View File
@@ -0,0 +1,312 @@
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { api } from "@/lib/api";
import { useToast } from "@/hooks/use-toast";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Loader2, Settings, Trash2, Plus, Eye, EyeOff } from "lucide-react";
interface OAuthProvider {
id: string;
name: string;
is_configured: boolean;
is_enabled: boolean;
client_id: string | null;
}
const PROVIDER_LOGOS: Record<string, string> = {
google: "https://www.google.com/favicon.ico",
github: "https://github.com/favicon.ico",
microsoft: "https://www.microsoft.com/favicon.ico",
};
const PROVIDER_HELP: Record<string, { docsUrl: string; callbackNote: string }> = {
google: {
docsUrl: "https://console.cloud.google.com/apis/credentials",
callbackNote: "Authorized redirect URI: http://localhost:5000/api/v1/auth/external/google/callback",
},
github: {
docsUrl: "https://github.com/settings/applications/new",
callbackNote: "Authorization callback URL: http://localhost:5000/api/v1/auth/external/github/callback",
},
microsoft: {
docsUrl: "https://portal.azure.com/#view/Microsoft_AAD_RegisteredApps",
callbackNote: "Redirect URI: http://localhost:5000/api/v1/auth/external/microsoft/callback",
},
};
export default function OAuthProvidersPage() {
const { toast } = useToast();
const queryClient = useQueryClient();
const [configDialog, setConfigDialog] = useState<{ open: boolean; provider: OAuthProvider | null }>({
open: false,
provider: null,
});
const [deleteDialog, setDeleteDialog] = useState<{ open: boolean; provider: OAuthProvider | null }>({
open: false,
provider: null,
});
const [clientId, setClientId] = useState("");
const [clientSecret, setClientSecret] = useState("");
const [isEnabled, setIsEnabled] = useState(true);
const [showSecret, setShowSecret] = useState(false);
const { data, isLoading } = useQuery({
queryKey: ["admin", "oauthProviders"],
queryFn: () => api.admin.listOAuthProviders(),
});
const configureMutation = useMutation({
mutationFn: ({ provider, cid, cs, enabled }: { provider: string; cid: string; cs: string; enabled: boolean }) =>
api.admin.configureOAuthProvider(provider, cid, cs, enabled),
onSuccess: (_, { provider }) => {
queryClient.invalidateQueries({ queryKey: ["admin", "oauthProviders"] });
toast({ title: `${provider} configured`, description: "OAuth provider settings saved." });
setConfigDialog({ open: false, provider: null });
},
onError: (err: Error) => {
toast({ title: "Failed to save", description: err.message, variant: "destructive" });
},
});
const deleteMutation = useMutation({
mutationFn: (provider: string) => api.admin.deleteOAuthProvider(provider),
onSuccess: (_, provider) => {
queryClient.invalidateQueries({ queryKey: ["admin", "oauthProviders"] });
toast({ title: `${provider} removed`, description: "OAuth provider configuration deleted." });
setDeleteDialog({ open: false, provider: null });
},
onError: (err: Error) => {
toast({ title: "Failed to delete", description: err.message, variant: "destructive" });
},
});
const openConfig = (provider: OAuthProvider) => {
setClientId(provider.client_id ?? "");
setClientSecret("");
setIsEnabled(provider.is_enabled);
setShowSecret(false);
setConfigDialog({ open: true, provider });
};
const handleSave = () => {
if (!configDialog.provider) return;
configureMutation.mutate({
provider: configDialog.provider.id,
cid: clientId,
cs: clientSecret,
enabled: isEnabled,
});
};
const providers: OAuthProvider[] = data?.providers ?? [];
return (
<div className="container max-w-3xl py-8 space-y-6">
<div>
<h1 className="text-2xl font-bold tracking-tight">OAuth Providers</h1>
<p className="text-sm text-muted-foreground mt-1">
Configure application-level OAuth provider credentials. Users can link their accounts via these providers.
</p>
</div>
{isLoading && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
Loading providers
</div>
)}
<div className="space-y-4">
{providers.map((p) => {
const help = PROVIDER_HELP[p.id];
return (
<Card key={p.id}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<img
src={PROVIDER_LOGOS[p.id]}
alt={p.name}
className="h-5 w-5"
onError={(e) => (e.currentTarget.style.display = "none")}
/>
<CardTitle className="text-base">{p.name}</CardTitle>
{p.is_configured ? (
<Badge variant={p.is_enabled ? "default" : "secondary"}>
{p.is_enabled ? "Enabled" : "Disabled"}
</Badge>
) : (
<Badge variant="outline" className="text-orange-600 border-orange-300">
Not configured
</Badge>
)}
</div>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={() => openConfig(p)}>
{p.is_configured ? (
<><Settings className="h-3.5 w-3.5 mr-1" /> Edit</>
) : (
<><Plus className="h-3.5 w-3.5 mr-1" /> Configure</>
)}
</Button>
{p.is_configured && (
<Button
variant="ghost"
size="sm"
className="text-destructive hover:text-destructive"
onClick={() => setDeleteDialog({ open: true, provider: p })}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
)}
</div>
</div>
</CardHeader>
{p.is_configured && p.client_id && (
<CardContent className="pt-0">
<CardDescription className="font-mono text-xs">
Client ID: {p.client_id.slice(0, 24)}
</CardDescription>
</CardContent>
)}
{!p.is_configured && (
<CardContent className="pt-0">
<CardDescription className="text-xs">
{help.callbackNote}
</CardDescription>
</CardContent>
)}
</Card>
);
})}
</div>
{/* Configure Dialog */}
<Dialog open={configDialog.open} onOpenChange={(o) => setConfigDialog((s) => ({ ...s, open: o }))}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>
{configDialog.provider?.is_configured ? "Edit" : "Configure"}{" "}
{configDialog.provider?.name} OAuth
</DialogTitle>
<DialogDescription>
{configDialog.provider && PROVIDER_HELP[configDialog.provider.id]?.callbackNote}
{" "}
<a
href={configDialog.provider ? PROVIDER_HELP[configDialog.provider.id]?.docsUrl : "#"}
target="_blank"
rel="noopener noreferrer"
className="underline text-primary"
>
Open provider console
</a>
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2">
<div className="space-y-1.5">
<Label htmlFor="client-id">Client ID</Label>
<Input
id="client-id"
value={clientId}
onChange={(e) => setClientId(e.target.value)}
placeholder="Enter Client ID"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="client-secret">
Client Secret{" "}
{configDialog.provider?.is_configured && (
<span className="text-muted-foreground text-xs">(leave blank to keep existing)</span>
)}
</Label>
<div className="relative">
<Input
id="client-secret"
type={showSecret ? "text" : "password"}
value={clientSecret}
onChange={(e) => setClientSecret(e.target.value)}
placeholder={configDialog.provider?.is_configured ? "••••••••" : "Enter Client Secret"}
className="pr-10"
/>
<button
type="button"
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
onClick={() => setShowSecret((v) => !v)}
>
{showSecret ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</button>
</div>
</div>
<div className="flex items-center justify-between">
<Label htmlFor="is-enabled">Enable this provider</Label>
<Switch id="is-enabled" checked={isEnabled} onCheckedChange={setIsEnabled} />
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setConfigDialog({ open: false, provider: null })}>
Cancel
</Button>
<Button onClick={handleSave} disabled={!clientId || configureMutation.isPending}>
{configureMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Save
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Delete Confirm Dialog */}
<AlertDialog
open={deleteDialog.open}
onOpenChange={(o) => setDeleteDialog((s) => ({ ...s, open: o }))}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Remove {deleteDialog.provider?.name}?</AlertDialogTitle>
<AlertDialogDescription>
This will remove the OAuth credentials for {deleteDialog.provider?.name}. Users will no longer be able
to sign in or link accounts via this provider.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={() => deleteDialog.provider && deleteMutation.mutate(deleteDialog.provider.id)}
>
{deleteMutation.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : "Remove"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
+373
View File
@@ -0,0 +1,373 @@
import { useState, useEffect, useCallback } from "react";
import {
Search,
Filter,
RefreshCw,
ChevronLeft,
ChevronRight,
LogIn,
LogOut,
Key,
UserPlus,
Shield,
Settings,
AlertTriangle,
Fingerprint,
Smartphone,
Terminal,
Loader2,
CheckCircle2,
XCircle,
Globe,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { api, AuditLogEntry } from "@/lib/api";
// ─── category helpers ────────────────────────────────────────────────────────
type Category = "auth" | "ssh" | "org" | "user" | "security" | "token" | "other";
const getCategory = (action: string): Category => {
const a = action.toLowerCase();
if (a.startsWith("session") || a.includes("login") || a.includes("logout") || a.includes("external_auth"))
return "auth";
if (a.startsWith("ssh"))
return "ssh";
if (a.startsWith("org") || a.includes("member") || a.includes("department") || a.includes("invite"))
return "org";
if (a.startsWith("user"))
return "user";
if (a.includes("mfa") || a.includes("totp") || a.includes("webauthn") || a.includes("passkey") || a.includes("password"))
return "security";
if (a.includes("token") || a.includes("oidc") || a.includes("client"))
return "token";
return "other";
};
const CATEGORY_META: Record<Category, { label: string; color: string }> = {
auth: { label: "Auth", color: "bg-blue-500/10 text-blue-600 dark:text-blue-400" },
ssh: { label: "SSH", color: "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400" },
org: { label: "Org", color: "bg-violet-500/10 text-violet-600 dark:text-violet-400" },
user: { label: "User", color: "bg-amber-500/10 text-amber-600 dark:text-amber-400" },
security: { label: "Security", color: "bg-orange-500/10 text-orange-600 dark:text-orange-400" },
token: { label: "Token", color: "bg-cyan-500/10 text-cyan-600 dark:text-cyan-400" },
other: { label: "Other", color: "bg-muted text-muted-foreground" },
};
const getCategoryIcon = (category: Category) => {
const cls = "w-4 h-4";
switch (category) {
case "auth": return <LogIn className={cls} />;
case "ssh": return <Terminal className={cls} />;
case "org": return <Settings className={cls} />;
case "user": return <UserPlus className={cls} />;
case "security": return <Shield className={cls} />;
case "token": return <Key className={cls} />;
default: return <Globe className={cls} />;
}
};
const getActionLabel = (action: string) =>
action
.replace(/_/g, " ")
.replace(/\./g, " ")
.replace(/\b\w/g, (c) => c.toUpperCase());
// ─── component ───────────────────────────────────────────────────────────────
const ACTION_FILTER_OPTIONS = [
{ value: "all", label: "All actions" },
{ value: "SESSION_CREATE", label: "Login" },
{ value: "SESSION_REVOKE", label: "Logout" },
{ value: "EXTERNAL_AUTH_LOGIN", label: "OAuth Login" },
{ value: "EXTERNAL_AUTH_LOGIN_FAILED", label: "OAuth Failed" },
{ value: "USER_REGISTER", label: "Register" },
{ value: "SSH_KEY_ADDED", label: "SSH Key Added" },
{ value: "SSH_KEY_VERIFIED", label: "SSH Key Verified" },
{ value: "SSH_CERT_ISSUED", label: "SSH Cert Issued" },
{ value: "SSH_CERT_REVOKED", label: "SSH Cert Revoked" },
{ value: "SSH_CERT_FAILED", label: "SSH Cert Failed" },
{ value: "ORG_CREATE", label: "Org Created" },
{ value: "ORG_MEMBER_ADD", label: "Member Added" },
{ value: "ORG_MEMBER_ROLE_CHANGE", label: "Role Changed" },
];
export default function SystemAuditPage() {
const [logs, setLogs] = useState<AuditLogEntry[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [isAdminView, setIsAdminView] = useState(false);
// filters
const [search, setSearch] = useState("");
const [debouncedSearch, setDebouncedSearch] = useState("");
const [actionFilter, setActionFilter] = useState("all");
const [successFilter, setSuccessFilter] = useState("all");
// pagination
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const [totalCount, setTotalCount] = useState(0);
const PER_PAGE = 50;
// debounce search
useEffect(() => {
const t = setTimeout(() => setDebouncedSearch(search), 400);
return () => clearTimeout(t);
}, [search]);
const fetchLogs = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
const params: Record<string, string> = {
page: String(page),
per_page: String(PER_PAGE),
};
if (actionFilter !== "all") params.action = actionFilter;
if (successFilter !== "all") params.success = successFilter;
if (debouncedSearch) params.q = debouncedSearch;
const resp = await api.admin.getAuditLogs(params);
setLogs(resp.audit_logs ?? []);
setTotalCount(resp.count ?? 0);
setTotalPages(resp.pages ?? 1);
setIsAdminView(resp.is_admin_view ?? false);
} catch (err) {
console.error("Failed to fetch system audit logs:", err);
setError("Failed to load audit logs. Please try again.");
} finally {
setIsLoading(false);
}
}, [page, actionFilter, successFilter, debouncedSearch]);
useEffect(() => {
fetchLogs();
}, [fetchLogs]);
// reset to page 1 when filters change
useEffect(() => {
setPage(1);
}, [actionFilter, successFilter, debouncedSearch]);
const formatDate = (dateString: string) => {
const d = new Date(dateString);
return new Intl.DateTimeFormat("en-US", {
month: "short",
day: "numeric",
hour: "numeric",
minute: "2-digit",
second: "2-digit",
hour12: false,
}).format(d);
};
const formatUserAgent = (ua: string | null) => {
if (!ua) return null;
const m = ua.match(/\(([^)]+)\)/);
if (m) return m[1].split(";")[0].trim();
return ua.slice(0, 40);
};
return (
<div className="page-container">
{/* Header */}
<div className="page-header flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<h1 className="page-title">System Audit Log</h1>
<p className="page-description">
{isAdminView
? `All system events — ${totalCount.toLocaleString()} total`
: "Your account events"}
</p>
</div>
<Button
variant="outline"
size="sm"
onClick={() => fetchLogs()}
disabled={isLoading}
>
<RefreshCw className={`w-4 h-4 mr-2 ${isLoading ? "animate-spin" : ""}`} />
Refresh
</Button>
</div>
{/* Filters */}
<div className="flex flex-col sm:flex-row gap-3 mb-4">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
placeholder="Search descriptions…"
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10"
/>
</div>
<Select value={actionFilter} onValueChange={setActionFilter}>
<SelectTrigger className="w-[200px]">
<Filter className="w-4 h-4 mr-2" />
<SelectValue placeholder="Filter by action" />
</SelectTrigger>
<SelectContent>
{ACTION_FILTER_OPTIONS.map((o) => (
<SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
))}
</SelectContent>
</Select>
<Select value={successFilter} onValueChange={setSuccessFilter}>
<SelectTrigger className="w-[150px]">
<SelectValue placeholder="Status" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All statuses</SelectItem>
<SelectItem value="true">Success only</SelectItem>
<SelectItem value="false">Failures only</SelectItem>
</SelectContent>
</Select>
</div>
{/* Table */}
<Card>
<CardContent className="p-0">
{isLoading ? (
<div className="flex items-center justify-center py-16">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
<span className="ml-2 text-muted-foreground">Loading</span>
</div>
) : error ? (
<div className="py-12 text-center text-destructive">
<AlertTriangle className="w-8 h-8 mx-auto mb-2" />
<p>{error}</p>
</div>
) : logs.length === 0 ? (
<div className="py-12 text-center text-muted-foreground">
No audit events match the current filters.
</div>
) : (
<div className="divide-y">
{logs.map((log) => {
const cat = getCategory(log.action);
const meta = CATEGORY_META[cat];
return (
<div key={log.id} className="flex items-start gap-4 px-4 py-3 hover:bg-muted/30 transition-colors">
{/* Icon */}
<div
className={`mt-0.5 w-9 h-9 rounded-lg flex items-center justify-center flex-shrink-0 ${
log.success ? meta.color : "bg-destructive/10 text-destructive"
}`}
>
{log.success ? getCategoryIcon(cat) : <XCircle className="w-4 h-4" />}
</div>
{/* Body */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium text-sm text-foreground">
{getActionLabel(log.action)}
</span>
<Badge variant="secondary" className={`text-xs px-1.5 py-0 ${meta.color}`}>
{meta.label}
</Badge>
{!log.success && (
<Badge variant="destructive" className="text-xs px-1.5 py-0">
Failed
</Badge>
)}
{log.resource_type && (
<Badge variant="outline" className="text-xs px-1.5 py-0 font-mono">
{log.resource_type}
</Badge>
)}
</div>
{/* Description */}
{log.description && (
<p className="mt-0.5 text-sm text-muted-foreground">{log.description}</p>
)}
{log.error_message && (
<p className="mt-0.5 text-xs text-destructive">{log.error_message}</p>
)}
{/* Meta row */}
<div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-xs text-muted-foreground">
{log.user?.email ? (
<span className="font-medium text-foreground/70">{log.user.email}</span>
) : log.user_id ? (
<span className="font-mono">{log.user_id.slice(0, 8)}</span>
) : (
<span className="italic">System</span>
)}
{log.ip_address && (
<span className="font-mono">{log.ip_address}</span>
)}
{log.user_agent && (
<span className="truncate max-w-[220px]" title={log.user_agent}>
{formatUserAgent(log.user_agent)}
</span>
)}
{log.resource_id && (
<span className="font-mono">{log.resource_id.slice(0, 8)}</span>
)}
</div>
</div>
{/* Timestamp */}
<div className="flex flex-col items-end gap-1 flex-shrink-0">
<p className="text-xs text-muted-foreground whitespace-nowrap">
{formatDate(log.created_at)}
</p>
{log.success ? (
<CheckCircle2 className="w-3.5 h-3.5 text-emerald-500" />
) : (
<XCircle className="w-3.5 h-3.5 text-destructive" />
)}
</div>
</div>
);
})}
</div>
)}
</CardContent>
</Card>
{/* Pagination */}
{totalPages > 1 && (
<div className="flex items-center justify-between mt-4">
<p className="text-sm text-muted-foreground">
Page {page} of {totalPages} &nbsp;·&nbsp; {totalCount.toLocaleString()} events
</p>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
disabled={page <= 1 || isLoading}
onClick={() => setPage((p) => p - 1)}
>
<ChevronLeft className="w-4 h-4" />
Prev
</Button>
<Button
variant="outline"
size="sm"
disabled={page >= totalPages || isLoading}
onClick={() => setPage((p) => p + 1)}
>
Next
<ChevronRight className="w-4 h-4" />
</Button>
</div>
</div>
)}
</div>
);
}
+97
View File
@@ -0,0 +1,97 @@
import { useEffect, useState } from "react";
import { useSearchParams, useNavigate } from "react-router-dom";
import { CheckCircle, XCircle, Loader2, Mail } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { GatehouseLogo } from "@/components/branding/GatehouseLogo";
import { api, ApiError } from "@/lib/api";
type Status = "loading" | "success" | "error" | "missing";
export default function ActivatePage() {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const [status, setStatus] = useState<Status>("loading");
const [message, setMessage] = useState<string>("");
useEffect(() => {
const code = searchParams.get("code") || searchParams.get("activation_key") || searchParams.get("key");
if (!code) {
setStatus("missing");
return;
}
api.auth
.activate(code)
.then(() => {
setStatus("success");
setMessage("Your account has been activated. You can now sign in.");
})
.catch((err) => {
const msg =
err instanceof ApiError
? err.message
: "Activation failed. The link may have expired or already been used.";
setMessage(msg);
setStatus("error");
});
}, [searchParams]);
return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
<div className="w-full max-w-md space-y-6">
{/* Logo */}
<div className="flex justify-center">
<GatehouseLogo size="md" />
</div>
<Card>
<CardContent className="pt-8 pb-8 px-6 flex flex-col items-center gap-4 text-center">
{status === "loading" && (
<>
<Loader2 className="w-12 h-12 animate-spin text-primary" />
<p className="text-sm text-muted-foreground">Activating your account</p>
</>
)}
{status === "success" && (
<>
<CheckCircle className="w-12 h-12 text-green-500" />
<h1 className="text-xl font-semibold">Account Activated</h1>
<p className="text-sm text-muted-foreground">{message}</p>
<Button className="w-full" onClick={() => navigate("/login")}>
Sign in
</Button>
</>
)}
{status === "error" && (
<>
<XCircle className="w-12 h-12 text-destructive" />
<h1 className="text-xl font-semibold">Activation Failed</h1>
<p className="text-sm text-muted-foreground">{message}</p>
<Button variant="outline" className="w-full" onClick={() => navigate("/login")}>
Back to sign in
</Button>
</>
)}
{status === "missing" && (
<>
<Mail className="w-12 h-12 text-muted-foreground" />
<h1 className="text-xl font-semibold">Invalid Activation Link</h1>
<p className="text-sm text-muted-foreground">
No activation code was found in this link. Please check your email and use the
link provided.
</p>
<Button variant="outline" className="w-full" onClick={() => navigate("/login")}>
Back to sign in
</Button>
</>
)}
</CardContent>
</Card>
</div>
</div>
);
}
+7 -3
View File
@@ -5,6 +5,7 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { BannerAlert } from "@/components/auth/BannerAlert"; import { BannerAlert } from "@/components/auth/BannerAlert";
import { api } from "@/lib/api";
export default function ForgotPasswordPage() { export default function ForgotPasswordPage() {
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
@@ -15,11 +16,14 @@ export default function ForgotPasswordPage() {
e.preventDefault(); e.preventDefault();
setIsLoading(true); setIsLoading(true);
// Mock API call - POST /api/auth/forgot-password try {
setTimeout(() => { await api.auth.forgotPassword(email);
} catch {
// Always show success to avoid leaking account existence
} finally {
setIsLoading(false); setIsLoading(false);
setIsSubmitted(true); setIsSubmitted(true);
}, 1000); }
}; };
// Success state - always show neutral message (don't leak account existence) // Success state - always show neutral message (don't leak account existence)
+163 -86
View File
@@ -1,36 +1,106 @@
import { useState } from "react"; import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate, useSearchParams, Link } from "react-router-dom";
import { User, Lock, Upload, ArrowRight, Building2 } from "lucide-react"; import { User, Lock, ArrowRight, Building2, Loader2, AlertCircle, CheckCircle } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { Avatar, AvatarFallback } from "@/components/ui/avatar"; import { api, ApiError } from "@/lib/api";
import { useAuth } from "@/contexts/AuthContext";
export default function InviteAcceptPage() { export default function InviteAcceptPage() {
const navigate = useNavigate(); const navigate = useNavigate();
const [searchParams] = useSearchParams();
const token = searchParams.get("token") || "";
const { login } = useAuth();
const [name, setName] = useState(""); const [name, setName] = useState("");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState("");
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [isTokenLoading, setIsTokenLoading] = useState(true);
const [tokenError, setTokenError] = useState("");
const [submitError, setSubmitError] = useState("");
const [inviteData, setInviteData] = useState<{
email: string;
organization: { id: string; name: string };
role: string;
user_exists?: boolean;
} | null>(null);
// Mock invite data - will be fetched from URL token useEffect(() => {
const inviteData = { if (!token) {
email: "invited@example.com", setTokenError("No invite token found in the URL.");
organization: "Acme Corp", setIsTokenLoading(false);
}; return;
}
api.invites.getInfo(token)
.then((data) => {
setInviteData(data);
})
.catch(() => {
setTokenError("This invitation link is invalid or has expired.");
})
.finally(() => setIsTokenLoading(false));
}, [token]);
const handleSubmit = async (e: React.FormEvent) => { const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
if (password !== confirmPassword) { setSubmitError("");
return; if (!inviteData?.user_exists) {
if (password !== confirmPassword) {
setSubmitError("Passwords do not match.");
return;
}
if (password.length < 8) {
setSubmitError("Password must be at least 8 characters.");
return;
}
} }
setIsLoading(true); setIsLoading(true);
setTimeout(() => { try {
setIsLoading(false); const result = await api.invites.accept(token, name || undefined, inviteData?.user_exists ? undefined : password);
if (result.token) {
// Store the token manually since we're not using the normal login flow
localStorage.setItem("gatehouse_token", result.token);
}
navigate("/profile"); navigate("/profile");
}, 1000); } catch (err: unknown) {
const msg = err instanceof ApiError ? err.message : "Failed to accept invite.";
setSubmitError(msg);
} finally {
setIsLoading(false);
}
}; };
if (isTokenLoading) {
return (
<div className="auth-card flex items-center justify-center py-12">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
);
}
if (tokenError) {
return (
<div className="auth-card">
<div className="text-center">
<div className="w-12 h-12 rounded-lg bg-destructive/10 flex items-center justify-center mx-auto mb-4">
<AlertCircle className="w-6 h-6 text-destructive" />
</div>
<h1 className="text-2xl font-semibold text-foreground tracking-tight mb-2">
Invalid Invitation
</h1>
<p className="text-muted-foreground">{tokenError}</p>
<Link to="/login" className="inline-block mt-4 text-sm text-primary hover:underline">
Back to sign in
</Link>
</div>
</div>
);
}
const isExistingUser = !!inviteData?.user_exists;
return ( return (
<div className="auth-card"> <div className="auth-card">
<div className="text-center mb-8"> <div className="text-center mb-8">
@@ -41,95 +111,102 @@ export default function InviteAcceptPage() {
You're invited! You're invited!
</h1> </h1>
<p className="text-muted-foreground mt-2"> <p className="text-muted-foreground mt-2">
<span className="font-medium text-foreground">{inviteData.organization}</span> has <span className="font-medium text-foreground">{inviteData?.organization.name}</span> has
invited you to join their organization invited you to join as <span className="font-medium text-foreground capitalize">{inviteData?.role}</span>
</p> </p>
</div> </div>
<form onSubmit={handleSubmit} className="space-y-4"> <form onSubmit={handleSubmit} className="space-y-4">
{/* Avatar upload */} <div className="space-y-2">
<div className="flex flex-col items-center mb-6"> <Label>Email</Label>
<Avatar className="w-20 h-20 mb-3"> <Input type="email" value={inviteData?.email ?? ""} disabled className="bg-muted" />
<AvatarFallback className="bg-primary text-primary-foreground text-xl">
{name ? name.split(" ").map(n => n[0]).join("").slice(0, 2).toUpperCase() : "?"}
</AvatarFallback>
</Avatar>
<Button type="button" variant="outline" size="sm">
<Upload className="w-4 h-4 mr-2" />
Upload photo
</Button>
</div> </div>
<div className="space-y-2"> {isExistingUser ? (
<Label htmlFor="email">Email</Label> <div className="rounded-lg bg-accent/10 border border-accent/20 p-4 flex items-start gap-3">
<Input <CheckCircle className="w-5 h-5 text-accent flex-shrink-0 mt-0.5" />
id="email" <div className="text-sm">
type="email" <p className="font-medium text-foreground">Account found</p>
value={inviteData.email} <p className="text-muted-foreground">You already have a Gatehouse account. Click below to join the organization.</p>
disabled </div>
className="bg-muted"
/>
</div>
<div className="space-y-2">
<Label htmlFor="name">Full name</Label>
<div className="relative">
<User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
id="name"
type="text"
placeholder="John Doe"
value={name}
onChange={(e) => setName(e.target.value)}
className="pl-10"
required
/>
</div> </div>
</div> ) : (
<>
<div className="space-y-2">
<Label htmlFor="name">Full name</Label>
<div className="relative">
<User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
id="name"
type="text"
placeholder="John Doe"
value={name}
onChange={(e) => setName(e.target.value)}
className="pl-10"
required
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="password">Password</Label>
<div className="relative">
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
id="password"
type="password"
placeholder="••••••••"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="pl-10"
required
minLength={8}
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="confirmPassword">Confirm password</Label>
<div className="relative">
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
id="confirmPassword"
type="password"
placeholder="••••••••"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className="pl-10"
required
/>
</div>
</div>
</>
)}
<div className="space-y-2"> {submitError && (
<Label htmlFor="password">Password</Label> <p className="text-sm text-destructive flex items-center gap-2">
<div className="relative"> <AlertCircle className="w-4 h-4 flex-shrink-0" />
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" /> {submitError}
<Input </p>
id="password" )}
type="password"
placeholder="••••••••"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="pl-10"
required
minLength={8}
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="confirmPassword">Confirm password</Label>
<div className="relative">
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
id="confirmPassword"
type="password"
placeholder="••••••••"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className="pl-10"
required
/>
</div>
</div>
<Button type="submit" className="w-full" disabled={isLoading}> <Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? ( {isLoading ? (
"Joining..." <><Loader2 className="w-4 h-4 mr-2 animate-spin" />Joining...</>
) : ( ) : (
<> <>
Join {inviteData.organization} Join {inviteData?.organization.name}
<ArrowRight className="w-4 h-4 ml-2" /> <ArrowRight className="w-4 h-4 ml-2" />
</> </>
)} )}
</Button> </Button>
{isExistingUser && (
<p className="text-center text-sm text-muted-foreground">
Not you?{" "}
<Link to="/login" className="text-primary hover:underline">
Sign in with a different account
</Link>
</p>
)}
</form> </form>
</div> </div>
); );
+87 -11
View File
@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback } from "react"; import { useState, useEffect, useCallback, useRef } from "react";
import { Link, useNavigate, useSearchParams } from "react-router-dom"; import { Link, useNavigate, useSearchParams } from "react-router-dom";
import { Mail, Lock, ArrowRight, Fingerprint, ArrowLeft, ShieldCheck, Loader2, Smartphone, AlertTriangle } from "lucide-react"; import { Mail, Lock, ArrowRight, Fingerprint, ArrowLeft, ShieldCheck, Loader2, Smartphone, AlertTriangle, Terminal } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
@@ -49,7 +49,7 @@ async function completeOidcFlow(oidcSessionId: string, token: string): Promise<s
} }
export default function LoginPage() { export default function LoginPage() {
const { login, verifyTotp, refreshUser } = useAuth(); const { login, verifyTotp, refreshUser, user, isLoading: authLoading } = useAuth();
const navigate = useNavigate(); const navigate = useNavigate();
const { toast } = useToast(); const { toast } = useToast();
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
@@ -69,6 +69,46 @@ export default function LoginPage() {
const oidcSessionId = searchParams.get('oidc_session_id'); const oidcSessionId = searchParams.get('oidc_session_id');
const oidcError = searchParams.get('error'); const oidcError = searchParams.get('error');
// CLI bridge: if cli_token or cli_redirect is present the login was triggered
// by the Gatehouse CLI tool. After successful auth the token is delivered
// directly to the CLI's local callback server.
const cliToken = searchParams.get('cli_token');
const cliRedirectParam = searchParams.get('cli_redirect');
const [cliRedirectUrl, setCliRedirectUrl] = useState<string | null>(cliRedirectParam);
const cliFetchedRef = useRef(false);
// Exchange cli_token for the real redirect URL (keeps the URL clean)
useEffect(() => {
if (!cliToken || cliFetchedRef.current) return;
cliFetchedRef.current = true;
fetch(`${GATEHOUSE_API}/cli/redirect-url?token=${encodeURIComponent(cliToken)}`)
.then((r) => r.json())
.then((body) => {
if (body?.data?.redirect_url) {
setCliRedirectUrl(body.data.redirect_url);
}
})
.catch(() => {/* ignore — user will just land on normal login */});
}, [cliToken]);
const finishCliFlow = useCallback((token: string) => {
if (!cliRedirectUrl) return false;
// cliRedirectUrl already ends with "token=" — just append the value
window.location.href = cliRedirectUrl + encodeURIComponent(token);
return true;
}, [cliRedirectUrl]);
// If the user is already authenticated and we're in CLI mode, deliver the
// token immediately — no need to show the login form at all.
useEffect(() => {
if (authLoading) return; // wait until auth state is known
if (!cliRedirectUrl) return;
const existingToken = tokenManager.getToken();
if (user && existingToken) {
finishCliFlow(existingToken);
}
}, [authLoading, user, cliRedirectUrl, finishCliFlow]);
const finishOidcFlow = useCallback(async (token: string) => { const finishOidcFlow = useCallback(async (token: string) => {
if (!oidcSessionId) return false; if (!oidcSessionId) return false;
try { try {
@@ -110,8 +150,12 @@ export default function LoginPage() {
e.preventDefault(); e.preventDefault();
setIsLoading(true); setIsLoading(true);
// In CLI or OIDC mode we need to handle post-auth navigation ourselves,
// so tell AuthContext not to navigate to /profile automatically.
const needsCustomNav = !!(cliRedirectUrl || oidcSessionId);
try { try {
const result = await login(email, password, rememberMe); const result = await login(email, password, rememberMe, needsCustomNav);
if (result.requiresWebAuthn) { if (result.requiresWebAuthn) {
setStep('webauthn'); setStep('webauthn');
} else if (result.requiresTotp) { } else if (result.requiresTotp) {
@@ -119,13 +163,17 @@ export default function LoginPage() {
setTotpCode(""); setTotpCode("");
} else if (result.requiresMfaEnrollment) { } else if (result.requiresMfaEnrollment) {
// MFA enrollment required - will be handled by ProtectedLayout // MFA enrollment required - will be handled by ProtectedLayout
// Navigation happens in AuthContext // Navigation happens in AuthContext (MFA path always navigates)
} else if (oidcSessionId) { } else if (oidcSessionId) {
// OIDC bridge: send token back to the Gatehouse backend to complete the flow // OIDC bridge: send token back to the Gatehouse backend to complete the flow
const token = tokenManager.getToken(); const token = tokenManager.getToken();
if (token) await finishOidcFlow(token); if (token) await finishOidcFlow(token);
} else if (cliRedirectUrl) {
// CLI bridge: deliver the token directly to the CLI's local server
const token = tokenManager.getToken();
if (token) finishCliFlow(token);
} }
// If no TOTP, WebAuthn, or MFA enrollment required, navigation happens in AuthContext // Normal login: navigation already handled by AuthContext (skipNavigate=false)
} catch (error) { } catch (error) {
if (import.meta.env.DEV) { if (import.meta.env.DEV) {
console.error("[Gatehouse] Login failed:", error); console.error("[Gatehouse] Login failed:", error);
@@ -178,16 +226,22 @@ export default function LoginPage() {
// OIDC bridge: finish the flow if this is an OIDC login // OIDC bridge: finish the flow if this is an OIDC login
if (oidcSessionId && response.token) { if (oidcSessionId && response.token) {
await finishOidcFlow(response.token); await finishOidcFlow(response.token);
} else if (cliRedirectUrl && response.token) {
finishCliFlow(response.token);
} else { } else {
await refreshUser(); await refreshUser();
navigate('/profile'); navigate('/profile');
} }
} else { } else {
// Fallback to regular TOTP verification // Fallback to regular TOTP verification
await verifyTotp(totpCode, useBackupCode); const needsCustomNav = !!(cliRedirectUrl || oidcSessionId);
await verifyTotp(totpCode, useBackupCode, needsCustomNav);
if (oidcSessionId) { if (oidcSessionId) {
const token = tokenManager.getToken(); const token = tokenManager.getToken();
if (token) await finishOidcFlow(token); if (token) await finishOidcFlow(token);
} else if (cliRedirectUrl) {
const token = tokenManager.getToken();
if (token) finishCliFlow(token);
} }
} }
} catch (error) { } catch (error) {
@@ -227,13 +281,17 @@ export default function LoginPage() {
setIsLoading(true); setIsLoading(true);
try { try {
await verifyTotp(totpCode, useBackupCode); const needsCustomNav = !!(cliRedirectUrl || oidcSessionId);
await verifyTotp(totpCode, useBackupCode, needsCustomNav);
// OIDC bridge: finish the flow if this is an OIDC login // OIDC bridge: finish the flow if this is an OIDC login
if (oidcSessionId) { if (oidcSessionId) {
const token = tokenManager.getToken(); const token = tokenManager.getToken();
if (token) await finishOidcFlow(token); if (token) await finishOidcFlow(token);
} else if (cliRedirectUrl) {
const token = tokenManager.getToken();
if (token) finishCliFlow(token);
} }
// Otherwise navigation happens in AuthContext // Normal login: navigation already handled by AuthContext (skipNavigate=false)
} catch (error) { } catch (error) {
if (import.meta.env.DEV) { if (import.meta.env.DEV) {
console.error("[Gatehouse] TOTP verification failed:", error); console.error("[Gatehouse] TOTP verification failed:", error);
@@ -292,6 +350,9 @@ export default function LoginPage() {
if (oidcSessionId) { if (oidcSessionId) {
const token = tokenManager.getToken(); const token = tokenManager.getToken();
if (token) await finishOidcFlow(token); if (token) await finishOidcFlow(token);
} else if (cliRedirectUrl) {
const token = tokenManager.getToken();
if (token) finishCliFlow(token);
} else { } else {
navigate('/profile'); navigate('/profile');
} }
@@ -364,6 +425,9 @@ export default function LoginPage() {
if (oidcSessionId) { if (oidcSessionId) {
const token = tokenManager.getToken(); const token = tokenManager.getToken();
if (token) await finishOidcFlow(token); if (token) await finishOidcFlow(token);
} else if (cliRedirectUrl) {
const token = tokenManager.getToken();
if (token) finishCliFlow(token);
} else { } else {
await refreshUser(); await refreshUser();
navigate('/profile'); navigate('/profile');
@@ -444,6 +508,11 @@ export default function LoginPage() {
...(oidcSessionId ? { oidc_session_id: oidcSessionId } : {}), ...(oidcSessionId ? { oidc_session_id: oidcSessionId } : {}),
}); });
// CLI bridge: stash the redirect URL so OAuthCallbackPage can deliver the token
if (cliRedirectUrl) {
sessionStorage.setItem('cli_redirect_url', cliRedirectUrl);
}
// Redirect browser to provider // Redirect browser to provider
window.location.href = response.authorization_url; window.location.href = response.authorization_url;
@@ -860,11 +929,18 @@ export default function LoginPage() {
return ( return (
<div className="auth-card"> <div className="auth-card">
<div className="text-center mb-8"> <div className="text-center mb-8">
{cliRedirectUrl && (
<div className="mx-auto w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center mb-4">
<Terminal className="w-6 h-6 text-primary" />
</div>
)}
<h1 className="text-2xl font-semibold text-foreground tracking-tight"> <h1 className="text-2xl font-semibold text-foreground tracking-tight">
{oidcSessionId ? "Sign in to continue" : "Welcome back"} {cliRedirectUrl ? "Authorize CLI access" : oidcSessionId ? "Sign in to continue" : "Welcome back"}
</h1> </h1>
<p className="text-muted-foreground mt-2"> <p className="text-muted-foreground mt-2">
{oidcSessionId {cliRedirectUrl
? "Sign in to grant the Gatehouse CLI access to your account"
: oidcSessionId
? "An application is requesting access to your account" ? "An application is requesting access to your account"
: "Sign in to your account to continue"} : "Sign in to your account to continue"}
</p> </p>
+32 -3
View File
@@ -75,10 +75,30 @@ export default function OAuthCallbackPage() {
return; return;
} }
// Organisation creation required // Organisation creation required — store the token and send to /org-setup
if (requiresOrgCreation) { if (requiresOrgCreation) {
setStatus('error'); const orgSetupToken = searchParams.get("token");
setError("No organization found for your account. Please ask an administrator to add you to an organization."); const orgSetupExpiresIn = searchParams.get("expires_in");
const pendingInvitesRaw = searchParams.get("pending_invites");
if (orgSetupToken) {
const expiresAt = orgSetupExpiresIn
? new Date(Date.now() + parseInt(orgSetupExpiresIn, 10) * 1000).toISOString()
: null;
tokenManager.setToken(orgSetupToken, expiresAt);
}
let pendingInvites: Array<{ token: string; organization: { id: string; name: string }; role: string; expires_at: string }> = [];
try {
if (pendingInvitesRaw) pendingInvites = JSON.parse(pendingInvitesRaw);
} catch {
// ignore parse errors
}
navigate('/org-setup', {
replace: true,
state: { pendingInvites, isFirstUser: false },
});
return; return;
} }
@@ -97,6 +117,15 @@ export default function OAuthCallbackPage() {
tokenManager.setToken(token, expiresAt); tokenManager.setToken(token, expiresAt);
await refreshUser(); await refreshUser();
// ── CLI bridge: deliver token to the local CLI server ─────────────────
const cliCallbackUrl = sessionStorage.getItem('cli_redirect_url');
if (cliCallbackUrl) {
sessionStorage.removeItem('cli_redirect_url');
// cliCallbackUrl already ends with "token=" — append the value
window.location.href = cliCallbackUrl + encodeURIComponent(token);
return;
}
// ── OIDC bridge: complete the flow and redirect back to the OIDC client ── // ── OIDC bridge: complete the flow and redirect back to the OIDC client ──
if (oidcSessionId) { if (oidcSessionId) {
try { try {
+141 -43
View File
@@ -1,39 +1,122 @@
import { useState } from "react"; import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate, useSearchParams } from "react-router-dom";
import { CheckCircle, XCircle, Shield, User, Mail, Building2 } from "lucide-react"; import { CheckCircle, XCircle, Shield, User, Mail, Building2, Loader2, Key } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card"; import { Card } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator";
import { tokenManager } from "@/lib/api";
const GATEHOUSE_API = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:5000/api/v1';
const GATEHOUSE_OIDC = GATEHOUSE_API.replace(/\/api\/v1\/?$/, '');
const SCOPE_META: Record<string, { icon: typeof Shield; label: string; description: string }> = {
openid: { icon: Shield, label: "OpenID", description: "Verify your identity" },
profile: { icon: User, label: "Profile", description: "Access your name and profile picture" },
email: { icon: Mail, label: "Email", description: "Access your email address" },
groups: { icon: Building2, label: "Groups", description: "Access your group memberships" },
offline_access: { icon: Key, label: "Offline Access", description: "Access your data while you are not logged in" },
};
interface ConsentContext {
oidc_session_id: string;
client_name: string;
scopes: string[];
redirect_uri: string;
}
export default function OIDCConsentPage() { export default function OIDCConsentPage() {
const navigate = useNavigate(); const navigate = useNavigate();
const [searchParams] = useSearchParams();
const oidcSessionId = searchParams.get("oidc_session_id");
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [context, setContext] = useState<ConsentContext | null>(null);
const [fetchError, setFetchError] = useState<string | null>(null);
// Mock OIDC client data - will be fetched from auth flow useEffect(() => {
const clientData = { if (!oidcSessionId) {
name: "GitLab", setFetchError("No OIDC session provided.");
logo: null, return;
redirectUri: "https://gitlab.example.com/callback", }
scopes: [
{ id: "openid", name: "OpenID", description: "Verify your identity" },
{ id: "profile", name: "Profile", description: "Access your name and profile picture" },
{ id: "email", name: "Email", description: "Access your email address" },
],
};
const handleAllow = () => { (async () => {
try {
const res = await fetch(`${GATEHOUSE_OIDC}/oidc/begin`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ oidc_session_id: oidcSessionId }),
});
const body = await res.json();
if (!res.ok || !body.success) {
setFetchError(body.message || "Failed to load consent context.");
return;
}
setContext(body.data as ConsentContext);
} catch {
setFetchError("Failed to connect to authentication server.");
}
})();
}, [oidcSessionId]);
const handleAllow = async () => {
if (!context) return;
setIsLoading(true); setIsLoading(true);
// Mock consent - will redirect to client callback try {
setTimeout(() => { const token = tokenManager.getToken();
if (!token) {
navigate(`/login?oidc_session_id=${context.oidc_session_id}`);
return;
}
const res = await fetch(`${GATEHOUSE_OIDC}/oidc/complete`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ oidc_session_id: context.oidc_session_id, token }),
});
const body = await res.json();
if (!res.ok || !body.success) {
setFetchError(body.message || "Authorization failed.");
return;
}
window.location.href = body.data.redirect_url;
} catch {
setFetchError("Failed to complete authorization.");
} finally {
setIsLoading(false); setIsLoading(false);
// In real implementation: redirect to redirectUri with auth code }
}, 500);
}; };
const handleDeny = () => { const handleDeny = () => {
navigate(-1); if (context?.redirect_uri) {
window.location.href = `${context.redirect_uri}?error=access_denied&error_description=User+denied+access`;
} else {
navigate(-1);
}
}; };
if (fetchError) {
return (
<div className="auth-card text-center">
<div className="w-16 h-16 rounded-full bg-destructive/10 flex items-center justify-center mx-auto mb-6">
<XCircle className="w-8 h-8 text-destructive" />
</div>
<h1 className="text-xl font-semibold text-foreground">Authorization Error</h1>
<p className="text-muted-foreground mt-2">{fetchError}</p>
<Button variant="outline" className="mt-6 w-full" onClick={() => navigate("/")}>
Return to home
</Button>
</div>
);
}
if (!context) {
return (
<div className="auth-card text-center">
<Loader2 className="w-8 h-8 text-accent animate-spin mx-auto mb-4" />
<p className="text-muted-foreground">Loading authorization request</p>
</div>
);
}
return ( return (
<div className="auth-card"> <div className="auth-card">
<div className="text-center mb-6"> <div className="text-center mb-6">
@@ -41,7 +124,7 @@ export default function OIDCConsentPage() {
<Shield className="w-7 h-7 text-primary" /> <Shield className="w-7 h-7 text-primary" />
</div> </div>
<h1 className="text-xl font-semibold text-foreground tracking-tight"> <h1 className="text-xl font-semibold text-foreground tracking-tight">
Authorize {clientData.name} Authorize {context.client_name}
</h1> </h1>
<p className="text-sm text-muted-foreground mt-2"> <p className="text-sm text-muted-foreground mt-2">
This application wants to access your account This application wants to access your account
@@ -50,31 +133,42 @@ export default function OIDCConsentPage() {
<Card className="p-4 bg-secondary/30 border-0 mb-6"> <Card className="p-4 bg-secondary/30 border-0 mb-6">
<p className="text-sm text-foreground font-medium mb-3"> <p className="text-sm text-foreground font-medium mb-3">
{clientData.name} is requesting access to: {context.client_name} is requesting access to:
</p> </p>
<ul className="space-y-3"> <ul className="space-y-3">
{clientData.scopes.map((scope) => ( {context.scopes.map((scope) => {
<li key={scope.id} className="flex items-start gap-3"> const meta = SCOPE_META[scope];
<div className="w-8 h-8 rounded-lg bg-card flex items-center justify-center flex-shrink-0"> const Icon = meta?.icon ?? Key;
{scope.id === "openid" && <Shield className="w-4 h-4 text-accent" />} return (
{scope.id === "profile" && <User className="w-4 h-4 text-accent" />} <li key={scope} className="flex items-start gap-3">
{scope.id === "email" && <Mail className="w-4 h-4 text-accent" />} <div className="w-8 h-8 rounded-lg bg-card flex items-center justify-center flex-shrink-0">
</div> <Icon className="w-4 h-4 text-accent" />
<div> </div>
<p className="text-sm font-medium text-foreground">{scope.name}</p> <div>
<p className="text-xs text-muted-foreground">{scope.description}</p> <p className="text-sm font-medium text-foreground">
</div> {meta?.label ?? scope}
</li> </p>
))} <p className="text-xs text-muted-foreground">
{meta?.description ?? scope}
</p>
</div>
</li>
);
})}
</ul> </ul>
</Card> </Card>
<div className="flex items-center gap-2 text-xs text-muted-foreground mb-6"> {context.redirect_uri && (
<Building2 className="w-4 h-4" /> <div className="flex items-center gap-2 text-xs text-muted-foreground mb-6">
<span> <Building2 className="w-4 h-4" />
Redirecting to: <span className="font-mono text-foreground">{clientData.redirectUri}</span> <span>
</span> Redirecting to:{" "}
</div> <span className="font-mono text-foreground">
{new URL(context.redirect_uri).origin}
</span>
</span>
</div>
)}
<Separator className="mb-6" /> <Separator className="mb-6" />
@@ -93,8 +187,12 @@ export default function OIDCConsentPage() {
className="flex-1" className="flex-1"
disabled={isLoading} disabled={isLoading}
> >
<CheckCircle className="w-4 h-4 mr-2" /> {isLoading ? (
{isLoading ? "Authorizing..." : "Allow"} <Loader2 className="w-4 h-4 mr-2 animate-spin" />
) : (
<CheckCircle className="w-4 h-4 mr-2" />
)}
{isLoading ? "Authorizing…" : "Allow"}
</Button> </Button>
</div> </div>
+23 -10
View File
@@ -1,14 +1,26 @@
import { AlertTriangle, ArrowLeft, Home } from "lucide-react"; import { AlertTriangle, ArrowLeft, Home } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Link } from "react-router-dom"; import { Link, useSearchParams } from "react-router-dom";
const ERROR_DESCRIPTIONS: Record<string, string> = {
invalid_request: "The request was missing a required parameter or was otherwise malformed.",
unauthorized_client: "The client is not authorized to request an authorization code using this method.",
access_denied: "The resource owner or authorization server denied the request.",
unsupported_response_type: "The authorization server does not support obtaining an authorization code using this method.",
invalid_scope: "The requested scope is invalid, unknown, or malformed.",
server_error: "The authorization server encountered an unexpected condition that prevented it from fulfilling the request.",
temporarily_unavailable: "The authorization server is temporarily unavailable. Please try again later.",
};
export default function OIDCErrorPage() { export default function OIDCErrorPage() {
// Mock error data - will be parsed from URL params const [searchParams] = useSearchParams();
const errorData = {
error: "invalid_request", const error = searchParams.get("error") || "server_error";
description: "The request was missing a required parameter or was otherwise malformed.", const errorDescription =
clientName: "Unknown Application", searchParams.get("error_description") ||
}; ERROR_DESCRIPTIONS[error] ||
"An unexpected error occurred during authentication.";
const clientName = searchParams.get("client") || "the application";
return ( return (
<div className="auth-card text-center"> <div className="auth-card text-center">
@@ -20,15 +32,16 @@ export default function OIDCErrorPage() {
Authentication Error Authentication Error
</h1> </h1>
<p className="text-muted-foreground mt-2 mb-4"> <p className="text-muted-foreground mt-2 mb-4">
There was a problem with the authentication request. There was a problem with the authentication request from{" "}
<span className="font-medium text-foreground">{clientName}</span>.
</p> </p>
<div className="bg-destructive/5 border border-destructive/20 rounded-lg p-4 mb-6 text-left"> <div className="bg-destructive/5 border border-destructive/20 rounded-lg p-4 mb-6 text-left">
<p className="text-sm font-medium text-foreground mb-1"> <p className="text-sm font-medium text-foreground mb-1">
Error: <code className="text-destructive">{errorData.error}</code> Error: <code className="text-destructive">{error}</code>
</p> </p>
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
{errorData.description} {decodeURIComponent(errorDescription)}
</p> </p>
</div> </div>
+455
View File
@@ -0,0 +1,455 @@
/**
* OIDCLoginPage Standalone OIDC proxy login UI
*
* Unified entry point for OIDC authorization flows via the Gatehouse OIDC bridge.
* Handles:
* 1. Unauthenticated users shows an email/password login form
* 2. Already-authenticated users shows a consent/approval screen directly
*
* Route: /oidc-login?oidc_session_id=<id>
*
* Configure your oauth2-proxy / OIDC client's login_url to:
* https://<gatehouse-ui>/oidc-login
*/
import { useState, useEffect, useCallback } from "react";
import { useSearchParams, useNavigate } from "react-router-dom";
import {
Shield,
Mail,
Lock,
ArrowRight,
Loader2,
XCircle,
CheckCircle,
AlertTriangle,
User,
Building2,
Key,
LogOut,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { Badge } from "@/components/ui/badge";
import { useAuth } from "@/contexts/AuthContext";
import { ApiError, tokenManager } from "@/lib/api";
// ── Configuration ─────────────────────────────────────────────────────────────
const GATEHOUSE_OIDC = (import.meta.env.VITE_API_BASE_URL ?? "http://localhost:5000/api/v1")
.replace(/\/api\/v1\/?$/, "");
// ── Scope display metadata ────────────────────────────────────────────────────
const SCOPE_META: Record<string, { icon: typeof Shield; label: string; description: string }> = {
openid: { icon: Shield, label: "Identity", description: "Verify your identity" },
profile: { icon: User, label: "Profile", description: "Your name and username" },
email: { icon: Mail, label: "Email", description: "Your email address" },
groups: { icon: Building2, label: "Groups", description: "Your organization memberships" },
roles: { icon: Shield, label: "Roles", description: "Your roles in the organization" },
offline_access: { icon: Key, label: "Offline Access", description: "Access data while you're away" },
};
// ── Types ─────────────────────────────────────────────────────────────────────
interface OIDCContext {
oidc_session_id: string;
client_name: string;
scopes: string[];
redirect_uri: string;
}
type PageStep = "loading" | "login" | "consent" | "error";
// ── API helpers ───────────────────────────────────────────────────────────────
async function fetchOIDCContext(oidcSessionId: string): Promise<OIDCContext> {
const res = await fetch(`${GATEHOUSE_OIDC}/oidc/begin`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ oidc_session_id: oidcSessionId }),
});
const body = await res.json();
if (!res.ok || !body.success) {
throw new Error(body.message || "Failed to load authorization context.");
}
return body.data as OIDCContext;
}
async function completeOIDCFlow(oidcSessionId: string, token: string): Promise<string> {
const res = await fetch(`${GATEHOUSE_OIDC}/oidc/complete`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ oidc_session_id: oidcSessionId, token }),
});
const body = await res.json();
if (!res.ok || !body.success) {
throw new Error(body.message || "Authorization failed.");
}
return body.data.redirect_url as string;
}
// ── Main component ────────────────────────────────────────────────────────────
export default function OIDCLoginPage() {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const { user, isLoading: authLoading, login, logout } = useAuth();
const oidcSessionId = searchParams.get("oidc_session_id");
const [step, setStep] = useState<PageStep>("loading");
const [context, setContext] = useState<OIDCContext | null>(null);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [isCompleting, setIsCompleting] = useState(false);
// Login form state
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [loginError, setLoginError] = useState<string | null>(null);
// ── Load OIDC context on mount ─────────────────────────────────────────────
useEffect(() => {
if (!oidcSessionId) {
setErrorMsg("Missing oidc_session_id. This page must be accessed from an OIDC authorization flow.");
setStep("error");
return;
}
fetchOIDCContext(oidcSessionId)
.then((ctx) => {
setContext(ctx);
// Determine initial step once we have context and auth state is known
})
.catch((err: Error) => {
setErrorMsg(err.message);
setStep("error");
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [oidcSessionId]);
// ── Determine step once both context and auth state are ready ───────────────
useEffect(() => {
if (authLoading || !context || step !== "loading") return;
const token = tokenManager.getToken();
setStep(token ? "consent" : "login");
}, [authLoading, context, step]);
// ── Complete OIDC flow ──────────────────────────────────────────────────────
const handleComplete = useCallback(async () => {
if (!context) return;
const token = tokenManager.getToken();
if (!token) {
setStep("login");
return;
}
setIsCompleting(true);
try {
const redirectUrl = await completeOIDCFlow(context.oidc_session_id, token);
window.location.href = redirectUrl;
} catch (err) {
setErrorMsg(err instanceof Error ? err.message : "Could not complete authorization.");
setStep("error");
} finally {
setIsCompleting(false);
}
}, [context]);
// ── Login form submit ───────────────────────────────────────────────────────
const handleLoginSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!context) return;
setLoginError(null);
setIsSubmitting(true);
try {
// skipNavigate=true so we control post-login navigation
const result = await login(email, password, false, true);
if (result.requiresTotp || result.requiresWebAuthn) {
// MFA required — hand off to main login page which already handles this
navigate(`/login?oidc_session_id=${context.oidc_session_id}`);
return;
}
// Login succeeded — move to consent step
setStep("consent");
} catch (err) {
const message =
err instanceof ApiError ? err.message
: err instanceof Error ? err.message
: "Invalid email or password.";
setLoginError(message);
} finally {
setIsSubmitting(false);
}
};
// ── Deny / cancel ───────────────────────────────────────────────────────────
const handleDeny = () => {
if (context?.redirect_uri) {
window.location.href = `${context.redirect_uri}?error=access_denied&error_description=User+denied+access`;
} else {
navigate("/");
}
};
// ── Switch account ──────────────────────────────────────────────────────────
const handleSwitchAccount = async () => {
await logout();
setStep("login");
setEmail("");
setPassword("");
setLoginError(null);
};
// ── Render: loading ──────────────────────────────────────────────────────────
if (step === "loading") {
return (
<div className="auth-card text-center">
<Loader2 className="w-8 h-8 text-accent animate-spin mx-auto mb-4" />
<p className="text-sm text-muted-foreground">Loading authorization request</p>
</div>
);
}
// ── Render: error ─────────────────────────────────────────────────────────────
if (step === "error") {
return (
<div className="auth-card text-center space-y-4">
<div className="w-14 h-14 rounded-full bg-destructive/10 flex items-center justify-center mx-auto">
<XCircle className="w-7 h-7 text-destructive" />
</div>
<h1 className="text-lg font-semibold text-foreground">Authorization Error</h1>
<p className="text-sm text-muted-foreground">{errorMsg}</p>
{context?.redirect_uri && (
<Button
variant="outline"
className="w-full"
onClick={() => {
window.location.href = `${context.redirect_uri}?error=server_error&error_description=${encodeURIComponent(errorMsg ?? "Unknown error")}`;
}}
>
Return to application
</Button>
)}
<Button variant="ghost" className="w-full" onClick={() => navigate("/")}>
Go to dashboard
</Button>
</div>
);
}
// ── Render: login form ────────────────────────────────────────────────────────
if (step === "login") {
return (
<div className="auth-card space-y-6">
{/* Header */}
<div className="text-center space-y-3">
<div className="w-14 h-14 rounded-xl bg-primary/10 flex items-center justify-center mx-auto">
<Shield className="w-7 h-7 text-primary" />
</div>
<div>
<h1 className="text-xl font-semibold text-foreground tracking-tight">
Sign in to continue
</h1>
{context && (
<p className="text-sm text-muted-foreground mt-1">
<span className="font-medium text-foreground">{context.client_name}</span>
{" "}is requesting access to your account
</p>
)}
</div>
</div>
{/* Requested scopes preview */}
{context && context.scopes.length > 0 && (
<Card className="p-3 bg-secondary/30 border-0">
<p className="text-xs text-muted-foreground mb-2">This application will access:</p>
<div className="flex flex-wrap gap-1.5">
{context.scopes.map((scope) => {
const meta = SCOPE_META[scope];
return (
<Badge key={scope} variant="secondary" className="text-xs gap-1">
{meta?.label ?? scope}
</Badge>
);
})}
</div>
</Card>
)}
{/* Login form */}
<form onSubmit={handleLoginSubmit} className="space-y-4">
{loginError && (
<div className="flex items-start gap-2 p-3 rounded-lg bg-destructive/10 border border-destructive/20">
<AlertTriangle className="w-4 h-4 text-destructive flex-shrink-0 mt-0.5" />
<p className="text-sm text-destructive">{loginError}</p>
</div>
)}
<div className="space-y-2">
<Label htmlFor="oidc-email">Email</Label>
<div className="relative">
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
id="oidc-email"
type="email"
placeholder="you@example.com"
className="pl-9"
value={email}
onChange={(e) => setEmail(e.target.value)}
autoComplete="email"
autoFocus
required
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="oidc-password">Password</Label>
<div className="relative">
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
id="oidc-password"
type="password"
placeholder="••••••••"
className="pl-9"
value={password}
onChange={(e) => setPassword(e.target.value)}
autoComplete="current-password"
required
/>
</div>
</div>
<Button type="submit" className="w-full" disabled={isSubmitting}>
{isSubmitting ? (
<><Loader2 className="w-4 h-4 animate-spin mr-2" />Signing in</>
) : (
<><ArrowRight className="w-4 h-4 mr-2" />Sign in</>
)}
</Button>
</form>
<Separator />
<div className="text-center space-y-2">
<p className="text-xs text-muted-foreground">
Need an account?{" "}
<a href="/register" className="text-primary hover:underline">Register here</a>
</p>
<p className="text-xs text-muted-foreground">
Forgot your password?{" "}
<a href="/forgot-password" className="text-primary hover:underline">Reset it</a>
</p>
</div>
<div className="text-center">
<button
type="button"
onClick={handleDeny}
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
>
Cancel and return to application
</button>
</div>
</div>
);
}
// ── Render: consent screen (user is authenticated) ────────────────────────────
if (step === "consent" && context) {
return (
<div className="auth-card space-y-6">
{/* Header */}
<div className="text-center space-y-3">
<div className="w-14 h-14 rounded-xl bg-primary/10 flex items-center justify-center mx-auto">
<Shield className="w-7 h-7 text-primary" />
</div>
<div>
<h1 className="text-xl font-semibold text-foreground tracking-tight">
Authorize {context.client_name}
</h1>
<p className="text-sm text-muted-foreground mt-1">
This application is requesting access to your account
</p>
</div>
</div>
{/* Signed-in-as banner */}
{user && (
<Card className="p-3 bg-secondary/30 border-0 flex items-center justify-between gap-3">
<div className="flex items-center gap-2 min-w-0">
<div className="w-7 h-7 rounded-full bg-primary/20 flex items-center justify-center flex-shrink-0">
<User className="w-4 h-4 text-primary" />
</div>
<div className="min-w-0">
<p className="text-sm font-medium text-foreground truncate">{user.email}</p>
<p className="text-xs text-muted-foreground">Signed in</p>
</div>
</div>
<button
type="button"
onClick={handleSwitchAccount}
className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-1 flex-shrink-0 transition-colors"
>
<LogOut className="w-3 h-3" />
Switch
</button>
</Card>
)}
{/* Requested permissions */}
<Card className="p-4 bg-secondary/30 border-0">
<p className="text-sm font-medium text-foreground mb-3">
{context.client_name} is requesting:
</p>
<ul className="space-y-3">
{context.scopes.map((scope) => {
const meta = SCOPE_META[scope];
const Icon = meta?.icon ?? Key;
return (
<li key={scope} className="flex items-start gap-3">
<div className="w-8 h-8 rounded-lg bg-card flex items-center justify-center flex-shrink-0">
<Icon className="w-4 h-4 text-accent" />
</div>
<div>
<p className="text-sm font-medium text-foreground">
{meta?.label ?? scope}
</p>
<p className="text-xs text-muted-foreground">
{meta?.description ?? scope}
</p>
</div>
</li>
);
})}
</ul>
</Card>
{/* Action buttons */}
<div className="space-y-2">
<Button
className="w-full"
onClick={handleComplete}
disabled={isCompleting}
>
{isCompleting ? (
<><Loader2 className="w-4 h-4 animate-spin mr-2" />Completing</>
) : (
<><CheckCircle className="w-4 h-4 mr-2" />Allow access</>
)}
</Button>
<Button variant="outline" className="w-full" onClick={handleDeny} disabled={isCompleting}>
<XCircle className="w-4 h-4 mr-2" />
Deny
</Button>
</div>
<p className="text-xs text-center text-muted-foreground">
By allowing, you agree to share the above information with{" "}
<span className="font-medium text-foreground">{context.client_name}</span>.
</p>
</div>
);
}
return null;
}
+337
View File
@@ -0,0 +1,337 @@
/**
* OrgSetupPage shown after registration or first login when the user has no org.
*
* Layout:
* - If the user has pending invitations show each invite card with a "Join" button.
* Only one org can be joined (once joined, redirect immediately).
* - Always show a "Create a new organisation" expandable section below.
*/
import { useState, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { Building2, Plus, ArrowRight, Loader2, Mail, ChevronDown, ChevronUp } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { BannerAlert } from "@/components/auth/BannerAlert";
import { api, ApiError, PendingInvite, tokenManager } from "@/lib/api";
import { useAuth } from "@/contexts/AuthContext";
function toSlug(name: string): string {
return name
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 64);
}
interface LocationState {
pendingInvites?: PendingInvite[];
isFirstUser?: boolean;
}
export default function OrgSetupPage() {
const navigate = useNavigate();
const location = useLocation();
const { refreshUser, checkOrgAdmin, isOrgMember, isLoading } = useAuth();
// If the user already belongs to an org (e.g. they bookmarked /org-setup),
// redirect them straight to their profile so they don't get stuck.
useEffect(() => {
if (!isLoading && isOrgMember) {
navigate("/profile", { replace: true });
}
}, [isLoading, isOrgMember, navigate]);
// Seed from navigation state on first render (avoids flicker), then always
// fetch from the API so refreshing the page still shows the real invites.
const locationState = (location.state ?? {}) as LocationState;
const [pendingInvites, setPendingInvites] = useState<PendingInvite[]>(
locationState.pendingInvites ?? []
);
const [invitesLoading, setInvitesLoading] = useState(true);
useEffect(() => {
let cancelled = false;
api.users.getMyInvites()
.then((res) => {
if (!cancelled) {
setPendingInvites(res.invites);
setInvitesLoading(false);
}
})
.catch(() => {
if (!cancelled) setInvitesLoading(false);
});
return () => { cancelled = true; };
}, []);
const hasInvites = pendingInvites.length > 0;
// Invite acceptance
const [joiningToken, setJoiningToken] = useState<string | null>(null);
const [joinError, setJoinError] = useState<string | null>(null);
// Create org form — open by default; collapses once we know there are invites
const [createOpen, setCreateOpen] = useState(false);
// Once invite fetch resolves: if no invites, open the create form automatically
useEffect(() => {
if (!invitesLoading) {
setCreateOpen(pendingInvites.length === 0);
}
}, [invitesLoading, pendingInvites.length]);
const [orgName, setOrgName] = useState("");
const [orgSlug, setOrgSlug] = useState("");
const [slugTouched, setSlugTouched] = useState(false);
const [isCreating, setIsCreating] = useState(false);
const [createError, setCreateError] = useState<string | null>(null);
const handleNameChange = (value: string) => {
setOrgName(value);
if (!slugTouched) setOrgSlug(toSlug(value));
};
const handleSlugChange = (value: string) => {
setSlugTouched(true);
setOrgSlug(value.toLowerCase().replace(/[^a-z0-9-]/g, ""));
};
const done = async () => {
await refreshUser();
await checkOrgAdmin();
navigate("/profile", { replace: true });
};
// ── Accept an invite ───────────────────────────────────────────────────────
const handleJoinOrg = async (invite: PendingInvite) => {
setJoinError(null);
setJoiningToken(invite.token);
try {
const result = await api.invites.accept(invite.token);
if (result.token) tokenManager.setToken(result.token, result.expires_at ?? null);
await done();
} catch (err) {
setJoinError(err instanceof ApiError ? err.message : "Failed to join organisation. Please try again.");
setJoiningToken(null);
}
};
// ── Create a new org ───────────────────────────────────────────────────────
const handleCreateOrg = async (e: React.FormEvent) => {
e.preventDefault();
setCreateError(null);
if (!orgName.trim()) { setCreateError("Organisation name is required."); return; }
if (!orgSlug.trim()) { setCreateError("Slug is required."); return; }
setIsCreating(true);
try {
await api.organizations.create(orgName.trim(), orgSlug.trim());
await done();
} catch (err) {
setCreateError(err instanceof ApiError ? err.message : "Failed to create organisation. Please try again.");
} finally {
setIsCreating(false);
}
};
return (
<div className="auth-card" data-testid="org-setup-page">
{/* Header */}
<div className="text-center mb-8">
<div className="w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center mx-auto mb-4">
<Building2 className="w-6 h-6 text-primary" />
</div>
<h1 className="text-2xl font-semibold text-foreground tracking-tight">
{hasInvites ? "You have an invitation!" : "Set up your organisation"}
</h1>
<p className="text-muted-foreground mt-2 text-sm">
{hasInvites
? "Join an existing organisation or create your own."
: "Create your organisation to get started. You'll be set as the Owner."}
</p>
</div>
{/* Loading skeleton while fetching invites */}
{invitesLoading ? (
<div className="flex items-center justify-center py-10">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
) : (
<>
{/* ── Pending invitations ────────────────────────────────────────────── */}
{hasInvites && (
<div className="mb-6 space-y-3">
<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-1">
<Mail className="w-3.5 h-3.5" />
Invitation{pendingInvites.length > 1 ? "s" : ""} for your email
</div>
{joinError && <BannerAlert type="error" message={joinError} className="mb-2" />}
{pendingInvites.map((invite) => (
<div
key={invite.token}
className="flex items-center justify-between rounded-xl border border-border bg-muted/40 px-4 py-3 gap-4"
data-testid="invite-card"
>
<div className="min-w-0">
<p className="text-sm font-semibold text-foreground truncate">
{invite.organization.name}
</p>
<p className="text-xs text-muted-foreground mt-0.5">
You were invited as{" "}
<span className="font-medium capitalize">{invite.role}</span>
</p>
</div>
<Button
size="sm"
className="shrink-0"
disabled={joiningToken !== null}
onClick={() => handleJoinOrg(invite)}
data-testid="join-org-btn"
>
{joiningToken === invite.token ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
"Join"
)}
</Button>
</div>
))}
</div>
)}
{/* ── Divider ───────────────────────────────────────────────────────── */}
{hasInvites && (
<div className="relative my-5">
<div className="absolute inset-0 flex items-center">
<span className="w-full border-t border-border" />
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-card px-2 text-muted-foreground">or</span>
</div>
</div>
)}
{/* ── Create organisation (collapsible when invites are present) ─────── */}
{hasInvites ? (
<div className="rounded-xl border border-border overflow-hidden">
{/* Toggle header */}
<button
type="button"
className="w-full flex items-center justify-between px-4 py-3 text-sm font-medium text-foreground hover:bg-muted/50 transition-colors"
onClick={() => setCreateOpen((o) => !o)}
data-testid="create-org-toggle"
>
<span className="flex items-center gap-2">
<Plus className="w-4 h-4 text-primary" />
Create a new organisation
</span>
{createOpen
? <ChevronUp className="w-4 h-4 text-muted-foreground" />
: <ChevronDown className="w-4 h-4 text-muted-foreground" />
}
</button>
{/* Collapsible form */}
{createOpen && (
<div className="border-t border-border px-4 py-4">
<CreateOrgForm
orgName={orgName}
orgSlug={orgSlug}
isCreating={isCreating}
createError={createError}
onNameChange={handleNameChange}
onSlugChange={handleSlugChange}
onSubmit={handleCreateOrg}
/>
</div>
)}
</div>
) : (
/* No invites — show the form directly */
<CreateOrgForm
orgName={orgName}
orgSlug={orgSlug}
isCreating={isCreating}
createError={createError}
onNameChange={handleNameChange}
onSlugChange={handleSlugChange}
onSubmit={handleCreateOrg}
/>
)}
</>
)}
</div>
);
}
// ── Reusable create-org form ─────────────────────────────────────────────────
interface CreateOrgFormProps {
orgName: string;
orgSlug: string;
isCreating: boolean;
createError: string | null;
onNameChange: (v: string) => void;
onSlugChange: (v: string) => void;
onSubmit: (e: React.FormEvent) => void;
}
function CreateOrgForm({
orgName, orgSlug, isCreating, createError,
onNameChange, onSlugChange, onSubmit,
}: CreateOrgFormProps) {
return (
<form onSubmit={onSubmit} className="space-y-4" data-testid="org-setup-create">
{createError && <BannerAlert type="error" message={createError} />}
<div className="space-y-1.5">
<Label htmlFor="orgName">Organisation name</Label>
<Input
id="orgName"
type="text"
placeholder="Acme Corp"
value={orgName}
onChange={(e) => onNameChange(e.target.value)}
required
autoFocus
data-testid="org-name-input"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="orgSlug">
Slug{" "}
<span className="text-xs text-muted-foreground font-normal">
used in URLs, lowercase &amp; hyphens only
</span>
</Label>
<Input
id="orgSlug"
type="text"
placeholder="acme-corp"
value={orgSlug}
onChange={(e) => onSlugChange(e.target.value)}
required
pattern="[a-z0-9][a-z0-9\-]*"
title="Lowercase letters, numbers, and hyphens only"
data-testid="org-slug-input"
/>
</div>
<Button
type="submit"
className="w-full"
disabled={isCreating || !orgName.trim() || !orgSlug.trim()}
data-testid="create-org-btn"
>
{isCreating
? <><Loader2 className="w-4 h-4 mr-2 animate-spin" />Creating</>
: <><ArrowRight className="w-4 h-4 mr-2" />Create organisation</>
}
</Button>
</form>
);
}
+30 -53
View File
@@ -6,8 +6,9 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { PasswordStrengthMeter, isPasswordValid } from "@/components/auth/PasswordStrengthMeter"; import { PasswordStrengthMeter, isPasswordValid } from "@/components/auth/PasswordStrengthMeter";
import { BannerAlert } from "@/components/auth/BannerAlert"; import { BannerAlert } from "@/components/auth/BannerAlert";
import { api, ApiError, tokenManager } from "@/lib/api";
type RegistrationState = "form" | "success" | "disabled"; type RegistrationState = "form" | "disabled";
export default function RegisterPage() { export default function RegisterPage() {
const navigate = useNavigate(); const navigate = useNavigate();
@@ -42,22 +43,36 @@ export default function RegisterPage() {
setIsLoading(true); setIsLoading(true);
// Mock registration - will be replaced with actual API call try {
// POST /api/auth/register const response = await api.auth.register(email, password, name.trim() || undefined);
setTimeout(() => {
setIsLoading(false);
// Simulate different responses // Store the session token so ProtectedLayout lets the user through
const mockResponse = "success" as RegistrationState | "error"; if (response.token) {
tokenManager.setToken(response.token, response.expires_at ?? null);
if (mockResponse === "disabled") {
setState("disabled");
} else if (mockResponse === "error") {
setError("An error occurred. Please try again.");
} else {
setState("success");
} }
}, 1000);
// Navigate to org-setup so the user can name their org or accept an invite
navigate("/org-setup", {
state: {
pendingInvites: response.pending_invites ?? [],
isFirstUser: response.is_first_user ?? false,
},
});
} catch (err) {
if (err instanceof ApiError) {
if (err.code === 409) {
setError("An account with this email already exists.");
} else if (err.code === 403 || (err.message && err.message.toLowerCase().includes("disabled"))) {
setState("disabled");
} else {
setError(err.message || "An error occurred. Please try again.");
}
} else {
setError("An error occurred. Please try again.");
}
} finally {
setIsLoading(false);
}
}; };
// Registration disabled state // Registration disabled state
@@ -85,44 +100,6 @@ export default function RegisterPage() {
); );
} }
// Success state - email sent
if (state === "success") {
return (
<div className="auth-card text-center">
<div className="w-16 h-16 rounded-full bg-success/10 flex items-center justify-center mx-auto mb-6">
<Mail className="w-8 h-8 text-success" />
</div>
<h1 className="text-2xl font-semibold text-foreground tracking-tight">
Check your email
</h1>
<p className="text-muted-foreground mt-2 mb-6">
We've sent a verification link to <span className="font-medium text-foreground">{email}</span>.
Click the link to verify your account and get started.
</p>
<div className="space-y-3">
<Link to="/login">
<Button className="w-full">
Continue to sign in
<ArrowRight className="w-4 h-4 ml-2" />
</Button>
</Link>
</div>
<p className="text-sm text-muted-foreground mt-6">
Didn't receive the email?{" "}
<button
onClick={() => setState("form")}
className="text-accent hover:underline font-medium"
>
Try again
</button>
</p>
</div>
);
}
// Registration form // Registration form
return ( return (
<div className="auth-card"> <div className="auth-card">
+29 -6
View File
@@ -1,27 +1,43 @@
import { useState } from "react"; import { useState } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate, useSearchParams } from "react-router-dom";
import { Lock, ArrowRight, CheckCircle } from "lucide-react"; import { Lock, ArrowRight, CheckCircle, AlertCircle, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { api } from "@/lib/api";
export default function ResetPasswordPage() { export default function ResetPasswordPage() {
const navigate = useNavigate(); const navigate = useNavigate();
const [searchParams] = useSearchParams();
const token = searchParams.get("token") || "";
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState("");
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [isSuccess, setIsSuccess] = useState(false); const [isSuccess, setIsSuccess] = useState(false);
const [error, setError] = useState("");
const handleSubmit = async (e: React.FormEvent) => { const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
setError("");
if (password !== confirmPassword) { if (password !== confirmPassword) {
setError("Passwords do not match.");
return;
}
if (!token) {
setError("Invalid reset link. Please request a new one.");
return; return;
} }
setIsLoading(true); setIsLoading(true);
setTimeout(() => { try {
setIsLoading(false); await api.auth.resetPassword(token, password);
setIsSuccess(true); setIsSuccess(true);
}, 1000); } catch (err: unknown) {
const msg = err instanceof Error ? err.message : "Failed to reset password. The link may be expired.";
setError(msg);
} finally {
setIsLoading(false);
}
}; };
if (isSuccess) { if (isSuccess) {
@@ -96,7 +112,7 @@ export default function ResetPasswordPage() {
<Button type="submit" className="w-full" disabled={isLoading}> <Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? ( {isLoading ? (
"Resetting..." <><Loader2 className="w-4 h-4 mr-2 animate-spin" />Resetting...</>
) : ( ) : (
<> <>
Reset password Reset password
@@ -104,6 +120,13 @@ export default function ResetPasswordPage() {
</> </>
)} )}
</Button> </Button>
{error && (
<p className="text-sm text-destructive flex items-center gap-2">
<AlertCircle className="w-4 h-4 flex-shrink-0" />
{error}
</p>
)}
</form> </form>
</div> </div>
); );
+16 -13
View File
@@ -5,6 +5,7 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { BannerAlert } from "@/components/auth/BannerAlert"; import { BannerAlert } from "@/components/auth/BannerAlert";
import { api, ApiError } from "@/lib/api";
type VerificationState = "verifying" | "success" | "error" | "resend"; type VerificationState = "verifying" | "success" | "error" | "resend";
@@ -22,21 +23,20 @@ export default function VerifyEmailPage() {
if (token && state === "verifying") { if (token && state === "verifying") {
verifyToken(token); verifyToken(token);
} }
}, [token, state]); }, [token]);
const verifyToken = async (verificationToken: string) => { const verifyToken = async (verificationToken: string) => {
// Mock verification - POST /api/auth/verify-email?token=... try {
setTimeout(() => { await api.auth.verifyEmail(verificationToken);
// Simulate different responses setState("success");
const mockSuccess = Math.random() > 0.3; // 70% success rate for demo } catch (err) {
setState("error");
if (mockSuccess) { if (err instanceof ApiError) {
setState("success"); setErrorMessage(err.message || "This verification link has expired or is invalid.");
} else { } else {
setState("error");
setErrorMessage("This verification link has expired or is invalid."); setErrorMessage("This verification link has expired or is invalid.");
} }
}, 1500); }
}; };
const handleResendVerification = async (e: React.FormEvent) => { const handleResendVerification = async (e: React.FormEvent) => {
@@ -44,11 +44,14 @@ export default function VerifyEmailPage() {
setIsResending(true); setIsResending(true);
setResendSuccess(false); setResendSuccess(false);
// Mock resend - POST /api/auth/request-email-verification try {
setTimeout(() => { await api.auth.resendVerification(resendEmail);
} catch {
// Always show success to avoid leaking account existence
} finally {
setIsResending(false); setIsResending(false);
setResendSuccess(true); setResendSuccess(true);
}, 1000); }
}; };
// Loading / Verifying state // Loading / Verifying state
+785
View File
@@ -0,0 +1,785 @@
import { useState, useEffect } from "react";
import {
Shield,
ShieldAlert,
Copy,
CheckCircle,
Loader2,
Terminal,
Plus,
User,
Server,
Settings,
AlertCircle,
ServerCog,
RefreshCw,
ShieldOff,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { useParams } from "react-router-dom";
import { useCurrentOrganizationId } from "@/hooks/useCurrentOrganization";
import { api, OrgCA, ApiError } from "@/lib/api";
function CopyButton({ text }: { text: string }) {
const [copied, setCopied] = useState(false);
const { toast } = useToast();
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
toast({ title: "Copied to clipboard" });
setTimeout(() => setCopied(false), 2000);
} catch {
toast({ variant: "destructive", title: "Copy failed" });
}
};
return (
<Button variant="ghost" size="icon" className="h-8 w-8 flex-shrink-0" onClick={handleCopy}>
{copied ? <CheckCircle className="w-4 h-4 text-green-500" /> : <Copy className="w-4 h-4" />}
</Button>
);
}
function formatDate(d: string | null) {
if (!d) return "—";
return new Date(d).toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });
}
// ─── CA Detail Card ───────────────────────────────────────────────────────────
interface CADetailCardProps {
ca: OrgCA;
onEdit: (ca: OrgCA) => void;
onRotate: (ca: OrgCA) => void;
onDelete: (ca: OrgCA) => void;
}
function CADetailCard({ ca, onEdit, onRotate, onDelete }: CADetailCardProps) {
const isUser = ca.ca_type === "user";
const isSystem = !!ca.is_system;
const sshConfig = isUser
? `# /etc/ssh/sshd_config:\nTrustedUserCAKeys /etc/ssh/trusted_user_ca_keys\n\n# Add public key:\necho '${ca.public_key.trim()}' \\\n >> /etc/ssh/trusted_user_ca_keys`
: `# /etc/ssh/sshd_config:\nHostCertificate /etc/ssh/ssh_host_ed25519_key-cert.pub\n\n# Add to known_hosts (clients):\n@cert-authority * ${ca.public_key.trim()}`;
return (
<div className="space-y-4">
<Card>
<CardHeader>
<div className="flex items-start justify-between">
<div>
<CardTitle className="text-base flex items-center gap-2">
{isSystem ? <ServerCog className="w-4 h-4" /> : isUser ? <User className="w-4 h-4" /> : <Server className="w-4 h-4" />}
{ca.name}
{isSystem ? (
<Badge variant="secondary" className="text-xs flex items-center gap-1">
<ServerCog className="w-3 h-3" />
System
</Badge>
) : ca.is_active ? (
<Badge className="bg-green-500/10 text-green-600 border-0 text-xs">Active</Badge>
) : (
<Badge variant="secondary" className="text-xs">Inactive</Badge>
)}
</CardTitle>
{ca.description && (
<CardDescription className="mt-1">{ca.description}</CardDescription>
)}
</div>
<Badge variant="outline" className="text-xs font-mono">{ca.key_type}</Badge>
</div>
</CardHeader>
<CardContent className="space-y-4">
{/* Stats — hidden for system CAs (we have no cert records for them) */}
{!isSystem && (
<div className="grid grid-cols-4 gap-3 text-center">
<div className="p-2 bg-muted rounded-lg">
<p className="text-lg font-semibold">{ca.active_certs}</p>
<p className="text-xs text-muted-foreground">Active certs</p>
</div>
<div className="p-2 bg-muted rounded-lg">
<p className="text-lg font-semibold">{ca.total_certs}</p>
<p className="text-xs text-muted-foreground">Total issued</p>
</div>
<div className="p-2 bg-muted rounded-lg">
<p className="text-lg font-semibold">{ca.default_cert_validity_hours}h</p>
<p className="text-xs text-muted-foreground">Default validity</p>
</div>
<div className="p-2 bg-muted rounded-lg">
<p className="text-lg font-semibold">{ca.next_serial_number ?? '—'}</p>
<p className="text-xs text-muted-foreground">Next serial</p>
</div>
</div>
)}
{/* Fingerprint */}
<div>
<p className="text-xs text-muted-foreground mb-1">Fingerprint</p>
<code className="text-xs font-mono bg-muted px-2 py-1 rounded break-all">{ca.fingerprint}</code>
</div>
{/* Public key */}
<div>
<div className="flex items-center justify-between mb-1">
<p className="text-xs text-muted-foreground">Public key</p>
<CopyButton text={ca.public_key} />
</div>
<Textarea readOnly value={ca.public_key} className="font-mono text-xs min-h-[60px]" />
</div>
{/* Setup instructions */}
<div className="rounded-lg bg-muted p-3">
<p className="text-xs font-semibold flex items-center gap-1 mb-1">
<Terminal className="w-3 h-3" />
{isUser ? "Add to SSH servers (sshd_config)" : "Host certificate setup"}
</p>
<pre className="text-xs font-mono whitespace-pre-wrap break-all">{sshConfig}</pre>
</div>
{ca.created_at && (
<p className="text-xs text-muted-foreground">Created {formatDate(ca.created_at)}</p>
)}
{ca.rotated_at && (
<p className="text-xs text-muted-foreground">
Key rotated {formatDate(ca.rotated_at)}
{ca.rotation_reason && <> {ca.rotation_reason}</>}
</p>
)}
{!isSystem && (
<div className="pt-2 border-t space-y-2">
<Button variant="outline" size="sm" onClick={() => onEdit(ca)} className="w-full">
<Settings className="w-3 h-3 mr-2" />
Edit Configuration
</Button>
<div className="grid grid-cols-2 gap-2">
<Button variant="outline" size="sm" onClick={() => onRotate(ca)} className="w-full">
<RefreshCw className="w-3 h-3 mr-2" />
Rotate Key
</Button>
<Button
variant="outline"
size="sm"
onClick={() => onDelete(ca)}
className="w-full text-destructive hover:text-destructive border-destructive/30 hover:border-destructive/60"
>
<ShieldOff className="w-3 h-3 mr-2" />
Delete CA
</Button>
</div>
</div>
)}
</CardContent>
</Card>
</div>
);
}
// ─── CA Section (one per type) ────────────────────────────────────────────────
interface CASectionProps {
caType: "user" | "host";
ca: OrgCA | null;
onCreateClick: (caType: "user" | "host") => void;
onEdit: (ca: OrgCA) => void;
onRotate: (ca: OrgCA) => void;
onDelete: (ca: OrgCA) => void;
}
function CASection({ caType, ca, onCreateClick, onEdit, onRotate, onDelete }: CASectionProps) {
const isUser = caType === "user";
const title = isUser ? "User Signing Key" : "Host Signing Key";
const subtitle = isUser
? "Signs SSH user certificates so users can authenticate to servers."
: "Signs SSH host certificates so clients can verify server identity.";
const Icon = isUser ? User : Server;
const isSystem = !!ca?.is_system;
return (
<div className="space-y-3">
<div className="flex items-center gap-2">
<Icon className="w-4 h-4 text-muted-foreground" />
<h2 className="text-sm font-semibold">{title}</h2>
{ca ? (
isSystem ? (
<Badge variant="secondary" className="text-xs flex items-center gap-1">
<ServerCog className="w-3 h-3" />
System (read-only)
</Badge>
) : (
<Badge className="bg-green-500/10 text-green-600 border-0 text-xs">Configured</Badge>
)
) : (
<Badge variant="secondary" className="text-xs flex items-center gap-1">
<AlertCircle className="w-3 h-3" />
Not configured
</Badge>
)}
</div>
{ca ? (
<>
<CADetailCard ca={ca} onEdit={onEdit} onRotate={onRotate} onDelete={onDelete} />
{/* When only a system CA is present, offer to generate a managed replacement */}
{isSystem && (
<div className="flex items-start gap-3 rounded-lg border border-amber-200 bg-amber-50 dark:border-amber-900 dark:bg-amber-950/30 p-3 text-xs text-amber-800 dark:text-amber-300">
<AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
<div className="flex-1">
<p className="font-semibold mb-1">Using server-configured CA</p>
<p>
Certificates are being signed by a CA key loaded from the server configuration,
not managed through this UI. Generate a managed key below to take full control
of certificate issuance from Gatehouse.
</p>
</div>
<Button onClick={() => onCreateClick(caType)} size="sm" variant="outline" className="flex-shrink-0">
<Plus className="w-3 h-3 mr-1" />
Generate managed key
</Button>
</div>
)}
</>
) : (
<Card className="border-dashed">
<CardContent className="flex flex-col items-center py-10 text-muted-foreground">
<ShieldAlert className="w-10 h-10 mb-3 opacity-30" />
<p className="text-sm font-medium mb-1">No {title} configured</p>
<p className="text-xs text-center mb-4 max-w-sm">{subtitle}</p>
<Button onClick={() => onCreateClick(caType)} size="sm" variant="outline">
<Plus className="w-4 h-4 mr-2" />
Generate {title}
</Button>
</CardContent>
</Card>
)}
</div>
);
}
// ─── Main Page ────────────────────────────────────────────────────────────────
export default function CAsPage() {
const params = useParams<{ orgId?: string }>();
const { orgId: fallbackOrgId } = useCurrentOrganizationId();
const orgId = params.orgId || fallbackOrgId;
const { toast } = useToast();
const [cas, setCAs] = useState<OrgCA[]>([]);
const [isLoading, setIsLoading] = useState(true);
// Create CA dialog
const [isCreateOpen, setIsCreateOpen] = useState(false);
const [createCaType, setCreateCaType] = useState<"user" | "host">("user");
const [createForm, setCreateForm] = useState({
name: "",
description: "",
key_type: "ed25519" as "ed25519" | "rsa" | "ecdsa",
default_cert_validity_hours: 8,
max_cert_validity_hours: 720,
});
const [isCreating, setIsCreating] = useState(false);
const [createError, setCreateError] = useState<string | null>(null);
// Edit CA dialog
const [editingCA, setEditingCA] = useState<OrgCA | null>(null);
const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
const [editFormData, setEditFormData] = useState({
default_cert_validity_hours: 1,
max_cert_validity_hours: 24,
});
const [isEditSaving, setIsEditSaving] = useState(false);
const [editError, setEditError] = useState<string | null>(null);
// Rotate CA dialog
const [rotatingCA, setRotatingCA] = useState<OrgCA | null>(null);
const [isRotateDialogOpen, setIsRotateDialogOpen] = useState(false);
const [rotateKeyType, setRotateKeyType] = useState<"ed25519" | "rsa" | "ecdsa">("ed25519");
const [rotateReason, setRotateReason] = useState("");
const [isRotating, setIsRotating] = useState(false);
const [rotateError, setRotateError] = useState<string | null>(null);
// Delete CA dialog
const [deletingCA, setDeletingCA] = useState<OrgCA | null>(null);
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
useEffect(() => {
if (!orgId) { setIsLoading(false); return; }
(async () => {
setIsLoading(true);
try {
const data = await api.organizations.getCAs(orgId);
setCAs(data.cas);
} catch (err) {
if (err instanceof ApiError && err.code === 403) {
toast({ variant: "destructive", title: "Access denied", description: "Admin or owner role required." });
} else {
toast({ variant: "destructive", title: "Failed to load CAs" });
}
} finally {
setIsLoading(false);
}
})();
}, [orgId, toast]);
const userCA = cas.find((c) => c.ca_type === "user") ?? null;
const hostCA = cas.find((c) => c.ca_type === "host") ?? null;
const handleOpenCreate = (caType: "user" | "host") => {
setCreateCaType(caType);
setCreateForm({
name: caType === "user" ? "User CA" : "Host CA",
description: "",
key_type: "ed25519",
default_cert_validity_hours: caType === "user" ? 8 : 720,
max_cert_validity_hours: caType === "user" ? 720 : 8760,
});
setCreateError(null);
setIsCreateOpen(true);
};
const handleCreateCA = async () => {
if (!orgId) return;
if (!createForm.name.trim()) { setCreateError("Name is required"); return; }
if (createForm.default_cert_validity_hours <= 0 || createForm.max_cert_validity_hours <= 0) {
setCreateError("Validity hours must be greater than 0"); return;
}
if (createForm.default_cert_validity_hours > createForm.max_cert_validity_hours) {
setCreateError("Default validity must be ≤ maximum validity"); return;
}
setIsCreating(true);
setCreateError(null);
try {
const result = await api.organizations.createCA(orgId, {
name: createForm.name.trim(),
description: createForm.description.trim() || undefined,
ca_type: createCaType,
key_type: createForm.key_type,
default_cert_validity_hours: createForm.default_cert_validity_hours,
max_cert_validity_hours: createForm.max_cert_validity_hours,
});
setCAs((prev) => [...prev, result.ca]);
setIsCreateOpen(false);
toast({
title: `${createCaType === "user" ? "User" : "Host"} CA created`,
description: result.ca.name,
});
} catch (err) {
if (err instanceof ApiError) {
setCreateError(err.message);
} else {
setCreateError("Failed to create CA — please try again");
}
} finally {
setIsCreating(false);
}
};
const handleEditCA = (ca: OrgCA) => {
setEditingCA(ca);
setEditFormData({
default_cert_validity_hours: ca.default_cert_validity_hours,
max_cert_validity_hours: ca.max_cert_validity_hours,
});
setEditError(null);
setIsEditDialogOpen(true);
};
const handleSaveCA = async () => {
if (!orgId || !editingCA) return;
if (editFormData.default_cert_validity_hours <= 0 || editFormData.max_cert_validity_hours <= 0) {
setEditError("Validity hours must be greater than 0"); return;
}
if (editFormData.default_cert_validity_hours > editFormData.max_cert_validity_hours) {
setEditError("Default validity must be less than or equal to maximum validity"); return;
}
setIsEditSaving(true);
try {
const updated = await api.organizations.updateCA(orgId, editingCA.id, editFormData);
setCAs(cas.map((ca) => (ca.id === editingCA.id ? updated.ca : ca)));
setIsEditDialogOpen(false);
setEditingCA(null);
toast({ title: "CA configuration updated" });
} catch (err) {
setEditError(err instanceof ApiError ? err.message : "Failed to update CA");
} finally {
setIsEditSaving(false);
}
};
// ── Rotate handlers ──
const handleRotateCA = (ca: OrgCA) => {
setRotatingCA(ca);
setRotateKeyType((ca.key_type as "ed25519" | "rsa" | "ecdsa") || "ed25519");
setRotateReason("");
setRotateError(null);
setIsRotateDialogOpen(true);
};
const handleConfirmRotate = async () => {
if (!orgId || !rotatingCA) return;
setIsRotating(true);
setRotateError(null);
try {
const result = await api.organizations.rotateCA(orgId, rotatingCA.id, {
key_type: rotateKeyType,
reason: rotateReason.trim() || undefined,
});
setCAs(cas.map((ca) => (ca.id === rotatingCA.id ? result.ca : ca)));
setIsRotateDialogOpen(false);
setRotatingCA(null);
toast({
title: "CA key rotated successfully",
description: `Old fingerprint: ${result.old_fingerprint}. Update TrustedUserCAKeys / known_hosts on your servers.`,
});
} catch (err) {
setRotateError(err instanceof ApiError ? err.message : "Failed to rotate CA key");
} finally {
setIsRotating(false);
}
};
// ── Delete handlers ──
const handleDeleteCA = (ca: OrgCA) => {
setDeletingCA(ca);
setIsDeleteDialogOpen(true);
};
const handleConfirmDelete = async () => {
if (!orgId || !deletingCA) return;
setIsDeleting(true);
try {
await api.organizations.deleteCA(orgId, deletingCA.id);
setCAs(cas.filter((ca) => ca.id !== deletingCA.id));
setIsDeleteDialogOpen(false);
setDeletingCA(null);
toast({ title: "CA deleted", description: "Existing certificates remain valid until they expire." });
} catch (err) {
toast({ variant: "destructive", title: "Failed to delete CA", description: err instanceof ApiError ? err.message : "" });
} finally {
setIsDeleting(false);
}
}; return (
<div className="page-container">
<div className="page-header">
<div>
<h1 className="page-title">Certificate Authorities</h1>
<p className="page-description">
Manage your organization's SSH certificate authorities and access controls
</p>
</div>
</div>
{isLoading ? (
<div className="flex items-center justify-center py-20">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
) : (
<div className="space-y-8">
<CASection caType="user" ca={userCA} onCreateClick={handleOpenCreate} onEdit={handleEditCA} onRotate={handleRotateCA} onDelete={handleDeleteCA} />
<div className="border-t" />
<CASection caType="host" ca={hostCA} onCreateClick={handleOpenCreate} onEdit={handleEditCA} onRotate={handleRotateCA} onDelete={handleDeleteCA} />
</div>
)}
{/* ── Edit CA Dialog ── */}
<Dialog open={isEditDialogOpen} onOpenChange={(open) => { setIsEditDialogOpen(open); if (!open) setEditError(null); }}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Edit CA Configuration</DialogTitle>
<DialogDescription>
Update certificate validity settings for <strong>{editingCA?.name}</strong>
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
{editError && (
<div className="p-3 rounded-lg bg-destructive/10 text-destructive text-sm flex items-start gap-2">
<AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
{editError}
</div>
)}
<div className="space-y-2">
<Label htmlFor="default-validity">Default Certificate Validity (hours)</Label>
<Input
id="default-validity"
type="number"
min="1"
value={editFormData.default_cert_validity_hours}
onChange={(e) => setEditFormData({ ...editFormData, default_cert_validity_hours: parseInt(e.target.value) || 1 })}
disabled={isEditSaving}
/>
<p className="text-xs text-muted-foreground">Default validity period when issuing new certificates</p>
</div>
<div className="space-y-2">
<Label htmlFor="max-validity">Maximum Certificate Validity (hours)</Label>
<Input
id="max-validity"
type="number"
min="1"
value={editFormData.max_cert_validity_hours}
onChange={(e) => setEditFormData({ ...editFormData, max_cert_validity_hours: parseInt(e.target.value) || 1 })}
disabled={isEditSaving}
/>
<p className="text-xs text-muted-foreground">Maximum allowed validity period for any certificate from this CA</p>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsEditDialogOpen(false)} disabled={isEditSaving}>Cancel</Button>
<Button onClick={handleSaveCA} disabled={isEditSaving}>
{isEditSaving && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
Save Changes
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* ── Create CA Dialog ── */}
<Dialog open={isCreateOpen} onOpenChange={(open) => { setIsCreateOpen(open); if (!open) setCreateError(null); }}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
{createCaType === "user" ? <User className="w-5 h-5" /> : <Server className="w-5 h-5" />}
Generate {createCaType === "user" ? "User" : "Host"} Signing Key
</DialogTitle>
<DialogDescription>
{createCaType === "user"
? "Creates a key pair for signing SSH user certificates. The private key is stored securely and never exposed."
: "Creates a key pair for signing SSH host certificates, allowing clients to verify server identity."}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
{createError && (
<div className="p-3 rounded-lg bg-destructive/10 text-destructive text-sm flex items-start gap-2">
<AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
<span>{createError}</span>
</div>
)}
<div className="space-y-2">
<Label htmlFor="ca-name">Name <span className="text-destructive">*</span></Label>
<Input
id="ca-name"
placeholder={createCaType === "user" ? "User CA" : "Host CA"}
value={createForm.name}
onChange={(e) => setCreateForm({ ...createForm, name: e.target.value })}
disabled={isCreating}
/>
</div>
<div className="space-y-2">
<Label htmlFor="ca-description">Description</Label>
<Input
id="ca-description"
placeholder="Optional description"
value={createForm.description}
onChange={(e) => setCreateForm({ ...createForm, description: e.target.value })}
disabled={isCreating}
/>
</div>
<div className="space-y-2">
<Label htmlFor="ca-key-type">Key Algorithm</Label>
<Select
value={createForm.key_type}
onValueChange={(v) => setCreateForm({ ...createForm, key_type: v as "ed25519" | "rsa" | "ecdsa" })}
disabled={isCreating}
>
<SelectTrigger id="ca-key-type"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="ed25519">Ed25519 (recommended)</SelectItem>
<SelectItem value="ecdsa">ECDSA (P-521)</SelectItem>
<SelectItem value="rsa">RSA-4096</SelectItem>
</SelectContent>
</Select>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-2">
<Label htmlFor="ca-default-validity">Default validity (hours)</Label>
<Input
id="ca-default-validity"
type="number"
min="1"
value={createForm.default_cert_validity_hours}
onChange={(e) => setCreateForm({ ...createForm, default_cert_validity_hours: parseInt(e.target.value) || 1 })}
disabled={isCreating}
/>
</div>
<div className="space-y-2">
<Label htmlFor="ca-max-validity">Max validity (hours)</Label>
<Input
id="ca-max-validity"
type="number"
min="1"
value={createForm.max_cert_validity_hours}
onChange={(e) => setCreateForm({ ...createForm, max_cert_validity_hours: parseInt(e.target.value) || 1 })}
disabled={isCreating}
/>
</div>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsCreateOpen(false)} disabled={isCreating}>Cancel</Button>
<Button onClick={handleCreateCA} disabled={isCreating}>
{isCreating ? (
<><Loader2 className="w-4 h-4 mr-2 animate-spin" />Generating key</>
) : (
<><Shield className="w-4 h-4 mr-2" />Generate Key</>
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* ── Rotate CA Dialog ── */}
<Dialog open={isRotateDialogOpen} onOpenChange={(open) => { setIsRotateDialogOpen(open); if (!open) setRotateError(null); }}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<RefreshCw className="w-5 h-5" />
Rotate CA Key
</DialogTitle>
<DialogDescription>
Generate a new key pair for <strong>{rotatingCA?.name}</strong>.
Previously-issued certificates remain valid until they expire, but all new
certificates will be signed with the new key. You must update
{rotatingCA?.ca_type === "user"
? " TrustedUserCAKeys on your SSH servers"
: " @cert-authority in client known_hosts files"} after rotation.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
{rotateError && (
<div className="p-3 rounded-lg bg-destructive/10 text-destructive text-sm flex items-start gap-2">
<AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
<span>{rotateError}</span>
</div>
)}
{rotatingCA && (
<div className="rounded-lg bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-900 p-3 text-xs text-amber-800 dark:text-amber-300">
<p className="font-semibold mb-1"> Important</p>
<p>
Current fingerprint: <code className="font-mono">{rotatingCA.fingerprint}</code>
</p>
<p className="mt-1">
After rotation, you <strong>must</strong> replace this fingerprint on every server /
client that trusts this CA. Until updated, new certificates won't be accepted.
</p>
</div>
)}
<div className="space-y-2">
<Label htmlFor="rotate-key-type">New Key Algorithm</Label>
<Select
value={rotateKeyType}
onValueChange={(v) => setRotateKeyType(v as "ed25519" | "rsa" | "ecdsa")}
disabled={isRotating}
>
<SelectTrigger id="rotate-key-type"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="ed25519">Ed25519 (recommended)</SelectItem>
<SelectItem value="ecdsa">ECDSA (P-521)</SelectItem>
<SelectItem value="rsa">RSA-4096</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="rotate-reason">Reason (optional)</Label>
<Input
id="rotate-reason"
placeholder="e.g. Suspected key compromise, Scheduled rotation"
value={rotateReason}
onChange={(e) => setRotateReason(e.target.value)}
disabled={isRotating}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsRotateDialogOpen(false)} disabled={isRotating}>
Cancel
</Button>
<Button onClick={handleConfirmRotate} disabled={isRotating} variant="destructive">
{isRotating ? (
<><Loader2 className="w-4 h-4 mr-2 animate-spin" />Rotating</>
) : (
<><RefreshCw className="w-4 h-4 mr-2" />Rotate Key</>
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* ── Delete CA Confirmation ── */}
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Certificate Authority?</AlertDialogTitle>
<AlertDialogDescription>
This will permanently deactivate <strong>{deletingCA?.name}</strong>.
No new certificates can be signed with this CA after deletion.
Existing certificates remain valid until they expire.
{deletingCA?.active_certs ? (
<span className="block mt-2 font-semibold text-amber-600 dark:text-amber-400">
This CA has {deletingCA.active_certs} active certificate{deletingCA.active_certs !== 1 ? "s" : ""}.
</span>
) : null}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleConfirmDelete}
disabled={isDeleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isDeleting && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
Delete CA
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
+19 -22
View File
@@ -1,14 +1,15 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { Shield, Search, Filter, Loader2, User, Clock, AlertTriangle, CheckCircle, Mail, ExternalLink } from "lucide-react"; import { Shield, Search, Loader2, User, Clock, AlertTriangle, CheckCircle, Mail, ExternalLink } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { api, OrgComplianceMember, create403Handler } from "@/lib/api"; import { api, OrgComplianceMember, create403Handler } from "@/lib/api";
import { useQuery } from "@tanstack/react-query"; import { useQuery, useMutation } from "@tanstack/react-query";
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
import { useOrg } from "@/contexts/OrgContext";
const STATUS_CONFIG: Record<string, { label: string; color: string; icon: typeof Clock }> = { const STATUS_CONFIG: Record<string, { label: string; color: string; icon: typeof Clock }> = {
compliant: { compliant: {
@@ -46,24 +47,10 @@ const STATUS_CONFIG: Record<string, { label: string; color: string; icon: typeof
export default function CompliancePage() { export default function CompliancePage() {
const navigate = useNavigate(); const navigate = useNavigate();
const { toast } = useToast(); const { toast } = useToast();
const [currentOrgId, setCurrentOrgId] = useState<string | null>(null); const { selectedOrgId: currentOrgId } = useOrg();
const [searchQuery, setSearchQuery] = useState(""); const [searchQuery, setSearchQuery] = useState("");
const [statusFilter, setStatusFilter] = useState<string>("all"); const [statusFilter, setStatusFilter] = useState<string>("all");
// Fetch organizations to get current org
const { data: orgsData, isLoading: orgsLoading } = useQuery({
queryKey: ['organizations'],
queryFn: () => api.users.organizations({
on403: create403Handler(toast),
}),
});
useEffect(() => {
if (orgsData?.organizations && orgsData.organizations.length > 0) {
setCurrentOrgId(orgsData.organizations[0].id);
}
}, [orgsData]);
// Fetch compliance data // Fetch compliance data
const { data: complianceData, isLoading: complianceLoading } = useQuery({ const { data: complianceData, isLoading: complianceLoading } = useQuery({
queryKey: ['org-compliance', currentOrgId], queryKey: ['org-compliance', currentOrgId],
@@ -73,6 +60,18 @@ export default function CompliancePage() {
enabled: !!currentOrgId, enabled: !!currentOrgId,
}); });
// Send MFA reminder mutation
const { mutate: sendReminder, variables: reminderVars, isPending: isSendingReminder } = useMutation({
mutationFn: ({ userId }: { userId: string }) =>
api.organizations.sendMfaReminder(currentOrgId!, userId),
onSuccess: () => {
toast({ title: "Reminder sent", description: "MFA reminder email sent successfully." });
},
onError: () => {
toast({ title: "Failed to send", description: "Could not send the reminder. Please try again.", variant: "destructive" });
},
});
// Filter members based on search and status // Filter members based on search and status
const filteredMembers = complianceData?.members?.filter((member) => { const filteredMembers = complianceData?.members?.filter((member) => {
const matchesSearch = const matchesSearch =
@@ -93,7 +92,7 @@ export default function CompliancePage() {
suspended: complianceData?.members?.filter(m => m.status === 'suspended').length || 0, suspended: complianceData?.members?.filter(m => m.status === 'suspended').length || 0,
}; };
if (orgsLoading || complianceLoading) { if (complianceLoading) {
return ( return (
<div className="page-container"> <div className="page-container">
<div className="flex items-center justify-center py-12"> <div className="flex items-center justify-center py-12">
@@ -256,10 +255,8 @@ export default function CompliancePage() {
size="icon" size="icon"
className="h-8 w-8" className="h-8 w-8"
title="Send Reminder" title="Send Reminder"
onClick={() => { disabled={isSendingReminder && reminderVars?.userId === member.user_id}
// TODO: Implement send reminder onClick={() => sendReminder({ userId: member.user_id })}
console.log('Send reminder to', member.user_id);
}}
> >
<Mail className="w-4 h-4" /> <Mail className="w-4 h-4" />
</Button> </Button>
+862
View File
@@ -0,0 +1,862 @@
import { useState, useEffect, useCallback } from "react";
import { Search, Plus, MoreHorizontal, Users, Loader2, Trash2, Edit2, X, ChevronDown, ChevronUp, ShieldCheck, UserPlus, UserMinus, Link as LinkIcon } from "lucide-react";
import { useParams } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { api, Department, Principal, DeptCertPolicy, STANDARD_SSH_EXTENSIONS, DepartmentMember, OrganizationMember } from "@/lib/api";
import { useCurrentOrganizationId } from "@/hooks/useCurrentOrganization";
import { useToast } from "@/hooks/use-toast";
// ---------------------------------------------------------------------------
// Department Certificate Policy Panel
// ---------------------------------------------------------------------------
function DepartmentCertPolicyPanel({ orgId, deptId }: { orgId: string; deptId: string }) {
const { toast } = useToast();
const [policy, setPolicy] = useState<DeptCertPolicy | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [isSaving, setIsSaving] = useState(false);
// Local editable form state
const [allowUserExpiry, setAllowUserExpiry] = useState(false);
const [defaultExpiry, setDefaultExpiry] = useState(1);
const [maxExpiry, setMaxExpiry] = useState(24);
const [allowedExtensions, setAllowedExtensions] = useState<string[]>([...STANDARD_SSH_EXTENSIONS]);
const [customExtensions, setCustomExtensions] = useState<string[]>([]);
const [newCustomExt, setNewCustomExt] = useState("");
useEffect(() => {
setIsLoading(true);
api.admin.getDeptCertPolicy(orgId, deptId)
.then((data) => {
const p = data.cert_policy;
setPolicy(p);
setAllowUserExpiry(p.allow_user_expiry);
setDefaultExpiry(p.default_expiry_hours);
setMaxExpiry(p.max_expiry_hours);
setAllowedExtensions(p.allowed_extensions ?? [...STANDARD_SSH_EXTENSIONS]);
setCustomExtensions(p.custom_extensions ?? []);
})
.catch(() => {/* non-fatal — use defaults */})
.finally(() => setIsLoading(false));
}, [orgId, deptId]);
const toggleExtension = (ext: string) => {
setAllowedExtensions((prev) =>
prev.includes(ext) ? prev.filter((e) => e !== ext) : [...prev, ext]
);
};
const addCustomExt = () => {
const trimmed = newCustomExt.trim();
if (!trimmed || customExtensions.includes(trimmed)) return;
setCustomExtensions((prev) => [...prev, trimmed]);
setNewCustomExt("");
};
const removeCustomExt = (ext: string) => {
setCustomExtensions((prev) => prev.filter((e) => e !== ext));
};
const handleSave = async () => {
setIsSaving(true);
try {
// When members can pick: max_expiry is the cap, default_expiry is also set to max
// (the backend uses default when no expiry is provided).
// When members can't pick: default_expiry is the fixed value, max is irrelevant.
const payload = allowUserExpiry
? { allow_user_expiry: true, default_expiry_hours: maxExpiry, max_expiry_hours: maxExpiry }
: { allow_user_expiry: false, default_expiry_hours: defaultExpiry, max_expiry_hours: defaultExpiry };
const data = await api.admin.setDeptCertPolicy(orgId, deptId, {
...payload,
allowed_extensions: allowedExtensions,
custom_extensions: customExtensions,
});
setPolicy(data.cert_policy);
toast({ title: "Policy saved", description: "Certificate policy updated." });
} catch (err) {
toast({ variant: "destructive", title: "Failed to save policy" });
} finally {
setIsSaving(false);
}
};
if (isLoading) {
return (
<div className="mt-3 p-4 border rounded-lg bg-muted/30 flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="w-4 h-4 animate-spin" />Loading policy
</div>
);
}
return (
<div className="mt-3 p-4 border rounded-lg bg-muted/20 space-y-4">
<h4 className="text-sm font-semibold flex items-center gap-2">
<ShieldCheck className="w-4 h-4 text-primary" />
Certificate Policy
</h4>
{/* Allow user to choose expiry */}
<div className="flex items-center justify-between gap-4">
<div>
<p className="text-sm font-medium">Allow members to pick expiry date</p>
<p className="text-xs text-muted-foreground">Admins can always pick.</p>
</div>
<button
type="button"
role="switch"
aria-checked={allowUserExpiry}
onClick={() => setAllowUserExpiry((v) => !v)}
className={`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 ${
allowUserExpiry ? "bg-primary" : "bg-zinc-600"
}`}
>
<span
className={`pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow-lg transition-transform ${
allowUserExpiry ? "translate-x-5" : "translate-x-0"
}`}
/>
</button>
</div>
{/* Expiry hours — conditional on toggle */}
{allowUserExpiry ? (
<div className="space-y-1">
<Label className="text-xs">Max expiry members can request (hours)</Label>
<Input
type="number"
min={1}
value={maxExpiry}
onChange={(e) => setMaxExpiry(Math.max(1, Number(e.target.value)))}
className="h-8 text-sm w-40"
/>
<p className="text-xs text-muted-foreground">Members can choose any duration up to this cap.</p>
</div>
) : (
<div className="space-y-1">
<Label className="text-xs">Default expiry applied to all members (hours)</Label>
<Input
type="number"
min={1}
value={defaultExpiry}
onChange={(e) => setDefaultExpiry(Math.max(1, Number(e.target.value)))}
className="h-8 text-sm w-40"
/>
<p className="text-xs text-muted-foreground">Members receive this expiry automatically no choice shown.</p>
</div>
)}
{/* Standard extensions */}
<div className="space-y-2">
<Label className="text-xs">Standard SSH extensions</Label>
<div className="space-y-1.5">
{STANDARD_SSH_EXTENSIONS.map((ext) => (
<div key={ext} className="flex items-center gap-2">
<input
type="checkbox"
id={`ext-${deptId}-${ext}`}
checked={allowedExtensions.includes(ext)}
onChange={() => toggleExtension(ext)}
className="accent-primary"
/>
<label htmlFor={`ext-${deptId}-${ext}`} className="text-sm font-mono cursor-pointer">{ext}</label>
</div>
))}
</div>
</div>
{/* Custom extensions */}
<div className="space-y-2">
<Label className="text-xs">Custom extensions</Label>
<div className="flex gap-2">
<Input
placeholder="permit-custom-x"
value={newCustomExt}
onChange={(e) => setNewCustomExt(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && addCustomExt()}
className="h-8 text-sm"
/>
<Button size="sm" variant="outline" onClick={addCustomExt} disabled={!newCustomExt.trim()}>
Add
</Button>
</div>
{customExtensions.length > 0 && (
<div className="flex flex-wrap gap-1 mt-1">
{customExtensions.map((ext) => (
<Badge key={ext} variant="secondary" className="text-xs gap-1 pr-1">
<span className="font-mono">{ext}</span>
<button onClick={() => removeCustomExt(ext)} className="ml-0.5 hover:text-destructive">
<X className="w-3 h-3" />
</button>
</Badge>
))}
</div>
)}
</div>
<Button size="sm" onClick={handleSave} disabled={isSaving}>
{isSaving && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
Save policy
</Button>
</div>
);
}
// ---------------------------------------------------------------------------
// Department Members Panel
// ---------------------------------------------------------------------------
function DepartmentMembersPanel({ orgId, deptId }: { orgId: string; deptId: string }) {
const { toast } = useToast();
const [members, setMembers] = useState<DepartmentMember[]>([]);
const [orgMembers, setOrgMembers] = useState<OrganizationMember[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [isAdding, setIsAdding] = useState(false);
const [removingId, setRemovingId] = useState<string | null>(null);
const [selectedUserId, setSelectedUserId] = useState("");
useEffect(() => {
setIsLoading(true);
Promise.all([
api.organizations.getDepartmentMembers(orgId, deptId),
api.organizations.getMembers(orgId),
])
.then(([deptRes, orgRes]) => {
setMembers(deptRes.members || []);
setOrgMembers(orgRes.members || []);
})
.catch(() => toast({ variant: "destructive", title: "Failed to load members" }))
.finally(() => setIsLoading(false));
}, [orgId, deptId, toast]);
const deptUserIds = new Set(members.map((m) => m.user_id));
const available = orgMembers.filter((m) => !deptUserIds.has(m.user_id));
const handleAdd = async () => {
const orgMember = orgMembers.find((m) => m.user_id === selectedUserId);
if (!orgMember?.user?.email) return;
setIsAdding(true);
try {
const res = await api.organizations.addDepartmentMember(orgId, deptId, orgMember.user.email);
setMembers((prev) => [...prev, res.member]);
setSelectedUserId("");
toast({ title: "Member added", description: `${orgMember.user.full_name || orgMember.user.email} added to department.` });
} catch (err) {
toast({ variant: "destructive", title: "Failed to add member" });
} finally {
setIsAdding(false);
}
};
const handleRemove = async (userId: string, displayName: string) => {
setRemovingId(userId);
try {
await api.organizations.removeDepartmentMember(orgId, deptId, userId);
setMembers((prev) => prev.filter((m) => m.user_id !== userId));
toast({ title: "Member removed", description: `${displayName} removed from department.` });
} catch (err) {
toast({ variant: "destructive", title: "Failed to remove member" });
} finally {
setRemovingId(null);
}
};
if (isLoading) {
return (
<div className="mt-3 p-4 border rounded-lg bg-muted/30 flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="w-4 h-4 animate-spin" /> Loading members
</div>
);
}
return (
<div className="mt-3 p-4 border rounded-lg bg-muted/20 space-y-3">
<h4 className="text-sm font-semibold flex items-center gap-2">
<Users className="w-4 h-4 text-primary" />
Department Members
<Badge variant="secondary" className="ml-1">{members.length}</Badge>
</h4>
{/* Existing members */}
{members.length === 0 ? (
<p className="text-xs text-muted-foreground italic">No members yet.</p>
) : (
<ul className="space-y-1.5">
{members.map((m) => {
const name = m.user?.full_name || m.user?.email || m.user_id;
const email = m.user?.email;
const busy = removingId === m.user_id;
return (
<li key={m.user_id} className="flex items-center justify-between gap-2 text-sm">
<div className="min-w-0">
<span className="font-medium truncate">{name}</span>
{email && name !== email && (
<span className="ml-2 text-xs text-muted-foreground">{email}</span>
)}
</div>
<button
onClick={() => handleRemove(m.user_id, name)}
disabled={busy}
className="flex items-center gap-1 text-xs text-destructive hover:underline disabled:opacity-50 flex-shrink-0"
>
{busy ? <Loader2 className="w-3 h-3 animate-spin" /> : <UserMinus className="w-3 h-3" />}
Remove
</button>
</li>
);
})}
</ul>
)}
{/* Add member */}
{available.length > 0 && (
<div className="flex items-center gap-2 pt-1 border-t">
<select
value={selectedUserId}
onChange={(e) => setSelectedUserId(e.target.value)}
className="flex-1 h-8 rounded-md border border-input bg-background px-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
>
<option value="">Select org member to add</option>
{available.map((m) => {
const email = m.user?.email || "";
const name = m.user?.full_name;
const label = name && email
? `${name} (${email})`
: email || m.user_id;
return (
<option key={m.user_id} value={m.user_id}>
{label}
</option>
);
})}
</select>
<Button size="sm" onClick={handleAdd} disabled={!selectedUserId || isAdding}>
{isAdding ? <Loader2 className="w-3 h-3 animate-spin mr-1" /> : <UserPlus className="w-3 h-3 mr-1" />}
Add
</Button>
</div>
)}
{available.length === 0 && members.length > 0 && (
<p className="text-xs text-muted-foreground pt-1 border-t">All org members are already in this department.</p>
)}
</div>
);
}
export default function DepartmentsPage() {
const params = useParams<{ orgId?: string }>();
const { orgId: fallbackOrgId } = useCurrentOrganizationId();
const orgId = params.orgId || fallbackOrgId;
const { toast } = useToast();
const [search, setSearch] = useState("");
const [departments, setDepartments] = useState<Department[]>([]);
const [principals, setPrincipals] = useState<Principal[]>([]);
const [linkedPrincipals, setLinkedPrincipals] = useState<Record<string, Principal[]>>({});
const [unlinkingKey, setUnlinkingKey] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
const [isLinkDialogOpen, setIsLinkDialogOpen] = useState(false);
const [linkingDept, setLinkingDept] = useState<Department | null>(null);
const [selectedPrincipalId, setSelectedPrincipalId] = useState("");
const [isLinking, setIsLinking] = useState(false);
const [editingDept, setEditingDept] = useState<Department | null>(null);
const [formData, setFormData] = useState({ name: "", description: "" });
const [expandedPolicies, setExpandedPolicies] = useState<Set<string>>(new Set());
const [expandedMembers, setExpandedMembers] = useState<Set<string>>(new Set());
const togglePolicyPanel = (deptId: string) => {
setExpandedPolicies((prev) => {
const next = new Set(prev);
next.has(deptId) ? next.delete(deptId) : next.add(deptId);
return next;
});
};
const toggleMembersPanel = (deptId: string) => {
setExpandedMembers((prev) => {
const next = new Set(prev);
next.has(deptId) ? next.delete(deptId) : next.add(deptId);
return next;
});
};
const fetchLinkedPrincipals = useCallback(async (currentOrgId: string, deptList: Department[]) => {
if (!deptList.length) return;
const results = await Promise.allSettled(
deptList.map((dept) =>
api.organizations.getDepartmentPrincipals(currentOrgId, dept.id)
)
);
const map: Record<string, Principal[]> = {};
deptList.forEach((dept, i) => {
const result = results[i];
map[dept.id] = result.status === "fulfilled" ? result.value.principals || [] : [];
});
setLinkedPrincipals(map);
}, []);
const fetchDepartments = useCallback(async (currentOrgId: string) => {
try {
setIsLoading(true);
setError(null);
const [response, principalsRes] = await Promise.all([
api.organizations.getDepartments(currentOrgId),
api.organizations.getPrincipals(currentOrgId),
]);
const deptList = response.departments || [];
setDepartments(deptList);
setPrincipals(principalsRes.principals || []);
await fetchLinkedPrincipals(currentOrgId, deptList);
} catch (err) {
console.error("Failed to fetch departments:", err);
setError("Failed to load departments. Please try again.");
} finally {
setIsLoading(false);
}
}, [fetchLinkedPrincipals]);
useEffect(() => {
setError(null);
setDepartments([]);
setPrincipals([]);
setLinkedPrincipals({});
if (!orgId) {
setIsLoading(false);
return;
}
fetchDepartments(orgId);
}, [orgId, fetchDepartments]);
const handleUnlink = async (deptId: string, principalId: string) => {
if (!orgId) return;
const key = `${deptId}:${principalId}`;
setUnlinkingKey(key);
try {
await api.organizations.unlinkPrincipalFromDepartment(orgId, principalId, deptId);
setLinkedPrincipals((prev) => ({
...prev,
[deptId]: (prev[deptId] || []).filter((p) => p.id !== principalId),
}));
toast({ title: "Unlinked", description: "Principal removed from department." });
} catch (err) {
console.error("Failed to unlink:", err);
toast({ title: "Error", description: "Failed to unlink principal.", variant: "destructive" });
} finally {
setUnlinkingKey(null);
}
};
const handleLinkPrincipal = async () => {
if (!orgId || !linkingDept || !selectedPrincipalId) return;
setIsLinking(true);
try {
await api.organizations.linkPrincipalToDepartment(orgId, selectedPrincipalId, linkingDept.id);
toast({ title: "Principal linked", description: "Principal linked to department." });
setLinkingDept(null);
setSelectedPrincipalId("");
setIsLinkDialogOpen(false);
await fetchDepartments(orgId);
} catch {
toast({ variant: "destructive", title: "Failed to link principal to department" });
} finally {
setIsLinking(false);
}
};
const openLinkDialog = (dept: Department) => {
setLinkingDept(dept);
setSelectedPrincipalId("");
setIsLinkDialogOpen(true);
};
const handleCreateDepartment = async () => {
if (!orgId || !formData.name.trim()) return;
try {
await api.organizations.createDepartment(
orgId,
formData.name,
formData.description || undefined
);
setFormData({ name: "", description: "" });
setIsCreateDialogOpen(false);
await fetchDepartments(orgId);
} catch (err) {
console.error("Failed to create department:");
setError("Failed to create department.");
}
};
const handleUpdateDepartment = async () => {
if (!orgId || !editingDept || !formData.name.trim()) return;
try {
await api.organizations.updateDepartment(orgId, editingDept.id, {
name: formData.name,
description: formData.description || undefined,
});
setFormData({ name: "", description: "" });
setEditingDept(null);
setIsEditDialogOpen(false);
await fetchDepartments(orgId);
} catch (err) {
console.error("Failed to update department:");
setError("Failed to update department.");
}
};
const handleDeleteDepartment = async (deptId: string) => {
if (!orgId || !confirm("Are you sure you want to delete this department?")) return;
try {
await api.organizations.deleteDepartment(orgId, deptId);
await fetchDepartments(orgId);
} catch (err) {
console.error("Failed to delete department:");
setError("Failed to delete department.");
}
};
const openEditDialog = (dept: Department) => {
setEditingDept(dept);
setFormData({ name: dept.name, description: dept.description || "" });
setIsEditDialogOpen(true);
};
const filteredDepartments = departments.filter((dept) => {
const searchLower = search.toLowerCase();
return (
dept.name.toLowerCase().includes(searchLower) ||
(dept.description?.toLowerCase().includes(searchLower) ?? false)
);
});
// Principals not yet linked to the dept being linked
const availablePrincipalsToLink = linkingDept
? principals.filter((p) => !(linkedPrincipals[linkingDept.id] || []).some((lp) => lp.id === p.id))
: principals;
return (
<div className="page-container">
<div className="page-header flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<h1 className="page-title">Departments</h1>
<p className="page-description">
Manage departments and organize team members
</p>
</div>
<Button onClick={() => { setFormData({ name: "", description: "" }); setIsCreateDialogOpen(true); }}>
<Plus className="w-4 h-4 mr-2" />
Create Department
</Button>
</div>
<div className="mb-4">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
placeholder="Search departments..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10 max-w-sm"
/>
</div>
</div>
<Card>
<CardContent className="p-0">
{isLoading ? (
<div className="flex items-center justify-center p-8">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
<span className="ml-2 text-muted-foreground">Loading departments...</span>
</div>
) : error ? (
<div className="p-8 text-center text-destructive">
{error}
</div>
) : filteredDepartments.length === 0 ? (
<div className="p-8 text-center text-muted-foreground">
No departments found
</div>
) : (
<div className="divide-y">
{filteredDepartments.map((dept) => {
const principals = linkedPrincipals[dept.id] || [];
return (
<div key={dept.id} className="p-4 flex items-start gap-4">
<div className="w-10 h-10 rounded-lg bg-accent/10 text-accent flex items-center justify-center flex-shrink-0">
<Users className="w-4 h-4" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<p className="font-medium text-foreground">
{dept.name}
</p>
</div>
{dept.description && (
<p className="mt-1 text-sm text-muted-foreground">
{dept.description}
</p>
)}
{/* Linked principals */}
<div className="mt-2 flex flex-wrap gap-1">
{principals.length === 0 ? (
<span className="text-xs text-muted-foreground italic">
Not linked to any principal
</span>
) : (
principals.map((principal) => {
const key = `${dept.id}:${principal.id}`;
const busy = unlinkingKey === key;
return (
<span
key={principal.id}
className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-700 dark:bg-purple-900 dark:text-purple-300"
>
{principal.name}
<button
onClick={() => handleUnlink(dept.id, principal.id)}
disabled={busy}
className="ml-0.5 rounded-full hover:bg-purple-200 dark:hover:bg-purple-800 disabled:opacity-50 p-0.5"
aria-label={`Unlink ${principal.name}`}
>
{busy ? (
<Loader2 className="w-3 h-3 animate-spin" />
) : (
<X className="w-3 h-3" />
)}
</button>
</span>
);
})
)}
</div>
<div className="mt-2 text-xs text-muted-foreground">
Created {new Date(dept.created_at).toLocaleDateString()}
</div>
{/* Members toggle */}
<button
className="mt-3 flex items-center gap-1 text-xs text-primary hover:underline"
onClick={() => toggleMembersPanel(dept.id)}
>
<Users className="w-3 h-3" />
Members
{expandedMembers.has(dept.id) ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
</button>
{/* Members panel */}
{orgId && expandedMembers.has(dept.id) && (
<DepartmentMembersPanel orgId={orgId} deptId={dept.id} />
)}
{/* Certificate policy toggle */}
<button
className="mt-3 flex items-center gap-1 text-xs text-primary hover:underline"
onClick={() => orgId && togglePolicyPanel(dept.id)}
>
<ShieldCheck className="w-3 h-3" />
Certificate Policy
{expandedPolicies.has(dept.id) ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
</button>
{/* Certificate policy panel */}
{orgId && expandedPolicies.has(dept.id) && (
<DepartmentCertPolicyPanel orgId={orgId} deptId={dept.id} />
)}
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon">
<MoreHorizontal className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => openEditDialog(dept)}>
<Edit2 className="w-4 h-4 mr-2" />
Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={() => openLinkDialog(dept)}>
<LinkIcon className="w-4 h-4 mr-2" />
Link Principal
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="text-destructive"
onClick={() => handleDeleteDepartment(dept.id)}
>
<Trash2 className="w-4 h-4 mr-2" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
);
})}
</div>
)}
</CardContent>
</Card>
{/* Create Department Dialog */}
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Create Department</DialogTitle>
<DialogDescription>
Create a new department to organize team members
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="dept-name">Department Name</Label>
<Input
id="dept-name"
placeholder="e.g., Engineering"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
/>
</div>
<div>
<Label htmlFor="dept-desc">Description</Label>
<Textarea
id="dept-desc"
placeholder="Optional description..."
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
rows={3}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsCreateDialogOpen(false)}>
Cancel
</Button>
<Button onClick={handleCreateDepartment}>
Create Department
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Edit Department Dialog */}
<Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Edit Department</DialogTitle>
<DialogDescription>
Update department information
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="edit-dept-name">Department Name</Label>
<Input
id="edit-dept-name"
placeholder="e.g., Engineering"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
/>
</div>
<div>
<Label htmlFor="edit-dept-desc">Description</Label>
<Textarea
id="edit-dept-desc"
placeholder="Optional description..."
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
rows={3}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsEditDialogOpen(false)}>
Cancel
</Button>
<Button onClick={handleUpdateDepartment}>
Save Changes
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Link Principal to Department Dialog */}
<Dialog
open={isLinkDialogOpen}
onOpenChange={(open) => {
if (!open) { setLinkingDept(null); setSelectedPrincipalId(""); }
setIsLinkDialogOpen(open);
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>Link Principal to Department</DialogTitle>
<DialogDescription>
Link a principal to <strong>{linkingDept?.name}</strong>. All department members will gain access to the principal.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="principal-select">Principal</Label>
{availablePrincipalsToLink.length === 0 ? (
<p className="mt-2 text-sm text-muted-foreground">
{principals.length === 0
? "No principals exist yet. Create one on the Principals page."
: "All principals are already linked to this department."}
</p>
) : (
<Select value={selectedPrincipalId} onValueChange={setSelectedPrincipalId}>
<SelectTrigger id="principal-select" className="mt-1">
<SelectValue placeholder="Choose a principal…" />
</SelectTrigger>
<SelectContent>
{availablePrincipalsToLink.map((p) => (
<SelectItem key={p.id} value={p.id}>{p.name}</SelectItem>
))}
</SelectContent>
</Select>
)}
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsLinkDialogOpen(false)}>Cancel</Button>
<Button
onClick={handleLinkPrincipal}
disabled={!selectedPrincipalId || isLinking || availablePrincipalsToLink.length === 0}
>
{isLinking && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
Link
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
File diff suppressed because it is too large Load Diff
+158
View File
@@ -0,0 +1,158 @@
import { useEffect, useState } from "react";
import { Layers, GitBranch, Building2, Loader2, Link } from "lucide-react";
import { api, MyOrgMembership } from "@/lib/api";
import { Skeleton } from "@/components/ui/skeleton";
import { Badge } from "@/components/ui/badge";
function MembershipsSkeleton() {
return (
<div className="space-y-6">
{[1, 2].map((i) => (
<div key={i} className="rounded-xl border border-border bg-card p-5 space-y-4">
<Skeleton className="h-5 w-48" />
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Skeleton className="h-24 w-full rounded-lg" />
<Skeleton className="h-24 w-full rounded-lg" />
</div>
</div>
))}
</div>
);
}
export default function MyMembershipsPage() {
const [orgs, setOrgs] = useState<MyOrgMembership[]>([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
api.users.getMyMemberships()
.then((res) => setOrgs(res.orgs ?? []))
.catch(console.error)
.finally(() => setIsLoading(false));
}, []);
const totalDepts = orgs.reduce((s, o) => s + o.departments.length, 0);
const totalPrincipals = orgs.reduce((s, o) => s + o.principals.length, 0);
return (
<div className="page-container">
<div className="page-header">
<h1 className="page-title">My Memberships</h1>
<p className="page-description">
Departments and principals you belong to across your organizations
</p>
</div>
{isLoading ? (
<MembershipsSkeleton />
) : orgs.length === 0 ? (
<div className="flex flex-col items-center justify-center py-20 text-center text-muted-foreground">
<Building2 className="w-10 h-10 mb-3 opacity-30" />
<p className="text-sm">You're not a member of any organizations yet.</p>
</div>
) : (
<div className="space-y-6">
{/* Summary chips */}
<div className="flex flex-wrap gap-3">
<div className="inline-flex items-center gap-2 rounded-full border border-border bg-card px-4 py-1.5 text-sm">
<Layers className="w-3.5 h-3.5 text-primary" />
<span className="font-medium">{totalDepts}</span>
<span className="text-muted-foreground">department{totalDepts !== 1 ? "s" : ""}</span>
</div>
<div className="inline-flex items-center gap-2 rounded-full border border-border bg-card px-4 py-1.5 text-sm">
<GitBranch className="w-3.5 h-3.5 text-primary" />
<span className="font-medium">{totalPrincipals}</span>
<span className="text-muted-foreground">principal{totalPrincipals !== 1 ? "s" : ""}</span>
</div>
</div>
{orgs.map((org) => (
<div
key={org.org_id}
className="rounded-xl border border-border bg-card overflow-hidden"
>
{/* Org header */}
<div className="flex items-center gap-3 px-5 py-4 border-b border-border bg-muted/30">
<div className="w-7 h-7 rounded bg-primary/10 flex items-center justify-center shrink-0">
<Building2 className="w-3.5 h-3.5 text-primary" />
</div>
<span className="font-semibold text-foreground text-sm">{org.org_name}</span>
<Badge variant="outline" className="capitalize text-xs ml-auto">
{org.role.toLowerCase()}
</Badge>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 divide-y md:divide-y-0 md:divide-x divide-border">
{/* Departments */}
<div className="p-5 space-y-3">
<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
<Layers className="w-3.5 h-3.5" />
Departments
</div>
{org.departments.length === 0 ? (
<p className="text-xs text-muted-foreground py-2">
Not assigned to any departments.
</p>
) : (
<ul className="space-y-2">
{org.departments.map((dept) => (
<li
key={dept.id}
className="flex items-start gap-2.5 rounded-lg border border-border bg-background px-3 py-2.5"
>
<Layers className="w-3.5 h-3.5 mt-0.5 text-primary shrink-0" />
<div className="min-w-0">
<p className="text-sm font-medium text-foreground truncate">{dept.name}</p>
{dept.description && (
<p className="text-xs text-muted-foreground mt-0.5 line-clamp-1">{dept.description}</p>
)}
</div>
</li>
))}
</ul>
)}
</div>
{/* Principals */}
<div className="p-5 space-y-3">
<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
<GitBranch className="w-3.5 h-3.5" />
Principals
</div>
{org.principals.length === 0 ? (
<p className="text-xs text-muted-foreground py-2">
No principals assigned.
</p>
) : (
<ul className="space-y-2">
{org.principals.map((p) => (
<li
key={p.id}
className="flex items-start gap-2.5 rounded-lg border border-border bg-background px-3 py-2.5"
>
<GitBranch className="w-3.5 h-3.5 mt-0.5 text-primary shrink-0" />
<div className="min-w-0 flex-1">
<p className="text-sm font-medium text-foreground truncate">{p.name}</p>
{p.description && (
<p className="text-xs text-muted-foreground mt-0.5 line-clamp-1">{p.description}</p>
)}
</div>
{p.via_department && (
<span className="shrink-0 inline-flex items-center gap-1 text-[10px] text-muted-foreground border border-border rounded px-1.5 py-0.5">
<Link className="w-2.5 h-2.5" />
via dept
</span>
)}
</li>
))}
</ul>
)}
</div>
</div>
</div>
))}
</div>
)}
</div>
);
}
+161 -98
View File
@@ -1,7 +1,7 @@
import { useState } from "react"; import { useState, useEffect, useRef } from "react";
import { Plus, Key, ExternalLink, MoreHorizontal, Copy, RefreshCw, Trash2 } from "lucide-react"; import { Plus, Key, MoreHorizontal, Copy, Trash2, Loader2, AlertCircle, CheckCircle } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { import {
DropdownMenu, DropdownMenu,
@@ -21,39 +21,71 @@ import {
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
import { api, OIDCClient, OIDCClientWithSecret } from "@/lib/api";
const clients = [ import { useToast } from "@/hooks/use-toast";
{ import { useOrg } from "@/contexts/OrgContext";
id: "1",
name: "GitLab",
clientId: "gitlab_prod_xxxxxxxxxxxxx",
redirectUris: ["https://gitlab.example.com/callback"],
scopes: ["openid", "profile", "email"],
createdAt: "2024-01-10",
lastUsed: "2 hours ago",
},
{
id: "2",
name: "Grafana",
clientId: "grafana_prod_xxxxxxxxxxxxx",
redirectUris: ["https://grafana.example.com/login/generic_oauth"],
scopes: ["openid", "profile"],
createdAt: "2024-01-08",
lastUsed: "5 minutes ago",
},
{
id: "3",
name: "OAuth2 Proxy",
clientId: "oauth2proxy_xxxxxxxxxxxxx",
redirectUris: ["https://auth.example.com/oauth2/callback"],
scopes: ["openid", "profile", "email", "groups"],
createdAt: "2024-01-05",
lastUsed: "1 day ago",
},
];
export default function OIDCClientsPage() { export default function OIDCClientsPage() {
const { toast } = useToast();
const { selectedOrgId: orgId } = useOrg();
const [clients, setClients] = useState<OIDCClient[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isCreateOpen, setIsCreateOpen] = useState(false); const [isCreateOpen, setIsCreateOpen] = useState(false);
const [isCreating, setIsCreating] = useState(false);
const [newSecret, setNewSecret] = useState<{ clientId: string; secret: string } | null>(null);
const nameRef = useRef<HTMLInputElement>(null);
const urisRef = useRef<HTMLTextAreaElement>(null);
const loadData = (id: string) => {
api.organizations.getClients(id)
.then((data) => setClients(data.clients))
.catch(() => toast({ title: "Error", description: "Failed to load OIDC clients.", variant: "destructive" }))
.finally(() => setIsLoading(false));
};
useEffect(() => {
if (!orgId) { setIsLoading(false); return; }
setIsLoading(true);
loadData(orgId);
}, [orgId]);
const handleCreate = async () => {
if (!orgId || !nameRef.current || !urisRef.current) return;
const name = nameRef.current.value.trim();
const uris = urisRef.current.value.trim().split(/[\n,]+/).map((u) => u.trim()).filter(Boolean);
if (!name || !uris.length) return;
setIsCreating(true);
try {
const result = await api.organizations.createClient(orgId, name, uris);
const created = result.client as OIDCClientWithSecret;
setClients((prev) => [...prev, created]);
setNewSecret({ clientId: created.client_id, secret: created.client_secret });
setIsCreateOpen(false);
} catch {
toast({ title: "Error", description: "Failed to create client.", variant: "destructive" });
} finally {
setIsCreating(false);
}
};
const handleDelete = async (clientId: string) => {
if (!orgId) return;
try {
await api.organizations.deleteClient(orgId, clientId);
setClients((prev) => prev.filter((c) => c.id !== clientId));
toast({ title: "Client deleted", description: "OIDC client deactivated successfully." });
} catch {
toast({ title: "Error", description: "Failed to delete client.", variant: "destructive" });
}
};
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text).then(() =>
toast({ title: "Copied", description: "Copied to clipboard." })
);
};
return ( return (
<div className="page-container"> <div className="page-container">
@@ -81,7 +113,7 @@ export default function OIDCClientsPage() {
<div className="space-y-4 py-4"> <div className="space-y-4 py-4">
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="clientName">Client name</Label> <Label htmlFor="clientName">Client name</Label>
<Input id="clientName" placeholder="My Application" /> <Input id="clientName" placeholder="My Application" ref={nameRef} />
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="redirectUris">Redirect URIs</Label> <Label htmlFor="redirectUris">Redirect URIs</Label>
@@ -89,17 +121,18 @@ export default function OIDCClientsPage() {
id="redirectUris" id="redirectUris"
placeholder="https://myapp.example.com/callback" placeholder="https://myapp.example.com/callback"
className="min-h-[80px]" className="min-h-[80px]"
ref={urisRef}
/> />
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
One URI per line. These are the allowed callback URLs. One URI per line. These are the allowed callback URLs.
</p> </p>
</div> </div>
<div className="flex justify-end gap-2"> <div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setIsCreateOpen(false)}> <Button variant="outline" onClick={() => setIsCreateOpen(false)} disabled={isCreating}>
Cancel Cancel
</Button> </Button>
<Button onClick={() => setIsCreateOpen(false)}> <Button onClick={handleCreate} disabled={isCreating}>
Create client {isCreating ? <><Loader2 className="w-4 h-4 mr-2 animate-spin" />Creating...</> : "Create client"}
</Button> </Button>
</div> </div>
</div> </div>
@@ -107,71 +140,101 @@ export default function OIDCClientsPage() {
</Dialog> </Dialog>
</div> </div>
<div className="space-y-4"> {/* Show new client secret once */}
{clients.map((client) => ( {newSecret && (
<Card key={client.id}> <Card className="mb-4 border-success/50 bg-success/5">
<CardContent className="p-5"> <CardContent className="p-4 flex items-start gap-3">
<div className="flex items-start justify-between"> <CheckCircle className="w-5 h-5 text-success mt-0.5 flex-shrink-0" />
<div className="flex items-start gap-4"> <div className="flex-1 min-w-0">
<div className="w-12 h-12 rounded-lg bg-primary/10 flex items-center justify-center"> <p className="font-medium text-foreground">Client created save your secret now</p>
<Key className="w-6 h-6 text-primary" /> <p className="text-sm text-muted-foreground mb-2">This secret will not be shown again.</p>
<div className="flex items-center gap-2">
<code className="text-xs bg-muted px-2 py-1 rounded font-mono break-all">{newSecret.secret}</code>
<Button variant="ghost" size="icon" className="w-6 h-6 flex-shrink-0" onClick={() => copyToClipboard(newSecret.secret)}>
<Copy className="w-3 h-3" />
</Button>
</div>
</div>
<Button variant="ghost" size="icon" className="w-6 h-6" onClick={() => setNewSecret(null)}>×</Button>
</CardContent>
</Card>
)}
{isLoading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
) : clients.length === 0 ? (
<Card>
<CardContent className="text-center py-12">
<AlertCircle className="w-10 h-10 mx-auto mb-3 text-muted-foreground/50" />
<p className="text-muted-foreground">No OIDC clients configured yet.</p>
<Button className="mt-4" onClick={() => setIsCreateOpen(true)}>
<Plus className="w-4 h-4 mr-2" />
Add your first client
</Button>
</CardContent>
</Card>
) : (
<div className="space-y-4">
{clients.map((client) => (
<Card key={client.id}>
<CardContent className="p-5">
<div className="flex items-start justify-between">
<div className="flex items-start gap-4">
<div className="w-12 h-12 rounded-lg bg-primary/10 flex items-center justify-center">
<Key className="w-6 h-6 text-primary" />
</div>
<div>
<h3 className="font-semibold text-foreground">{client.name}</h3>
<div className="flex items-center gap-2 mt-1">
<code className="text-xs bg-muted px-2 py-1 rounded font-mono">
{client.client_id}
</code>
<Button variant="ghost" size="icon" className="w-6 h-6" onClick={() => copyToClipboard(client.client_id)}>
<Copy className="w-3 h-3" />
</Button>
</div>
<div className="flex flex-wrap gap-1 mt-3">
{(client.scopes ?? []).map((scope) => (
<Badge key={scope} variant="secondary" className="text-xs">
{scope}
</Badge>
))}
</div>
</div>
</div> </div>
<div> <DropdownMenu>
<h3 className="font-semibold text-foreground">{client.name}</h3> <DropdownMenuTrigger asChild>
<div className="flex items-center gap-2 mt-1"> <Button variant="ghost" size="icon">
<code className="text-xs bg-muted px-2 py-1 rounded font-mono"> <MoreHorizontal className="w-4 h-4" />
{client.clientId}
</code>
<Button variant="ghost" size="icon" className="w-6 h-6">
<Copy className="w-3 h-3" />
</Button> </Button>
</div> </DropdownMenuTrigger>
<div className="flex flex-wrap gap-1 mt-3"> <DropdownMenuContent align="end">
{client.scopes.map((scope) => ( <DropdownMenuSeparator />
<Badge key={scope} variant="secondary" className="text-xs"> <DropdownMenuItem
{scope} className="text-destructive"
</Badge> onClick={() => handleDelete(client.id)}
))} >
</div> <Trash2 className="w-4 h-4 mr-2" />
Delete client
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<div className="mt-4 pt-4 border-t flex items-center justify-between text-sm text-muted-foreground">
<span>
Created {new Date(client.created_at).toLocaleDateString()}
</span>
<div className="flex items-center gap-1">
{(client.redirect_uris ?? []).length} redirect URI{(client.redirect_uris ?? []).length !== 1 ? "s" : ""}
</div> </div>
</div> </div>
<DropdownMenu> </CardContent>
<DropdownMenuTrigger asChild> </Card>
<Button variant="ghost" size="icon"> ))}
<MoreHorizontal className="w-4 h-4" /> </div>
</Button> )}
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem>
<ExternalLink className="w-4 h-4 mr-2" />
View details
</DropdownMenuItem>
<DropdownMenuItem>
<RefreshCw className="w-4 h-4 mr-2" />
Rotate secret
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem className="text-destructive">
<Trash2 className="w-4 h-4 mr-2" />
Delete client
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<div className="mt-4 pt-4 border-t flex items-center justify-between text-sm text-muted-foreground">
<div className="flex items-center gap-4">
<span>Created {client.createdAt}</span>
<span></span>
<span>Last used {client.lastUsed}</span>
</div>
<div className="flex items-center gap-1">
{client.redirectUris.length} redirect URI{client.redirectUris.length > 1 ? "s" : ""}
</div>
</div>
</CardContent>
</Card>
))}
</div>
</div> </div>
); );
} }
+130 -103
View File
@@ -1,90 +1,77 @@
import { useState } from "react"; import { useState, useEffect, useCallback } from "react";
import { Search, Filter, Download, User, Settings, Key, UserPlus, AlertTriangle } from "lucide-react"; import { Search, Filter, Download, User, Settings, Key, UserPlus, AlertTriangle, Loader2 } from "lucide-react";
import { useParams } from "react-router-dom";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card"; import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { api, AuditLogEntry } from "@/lib/api";
import { useCurrentOrganizationId } from "@/hooks/useCurrentOrganization";
const auditEvents = [ const getEventIcon = (action: string) => {
{ if (action.includes("member") || action.includes("MEMBER")) {
id: "1", return <UserPlus className="w-4 h-4" />;
type: "member_invited",
actor: "John Doe",
target: "alice@example.com",
timestamp: "2024-01-15T10:30:00Z",
details: "Invited as member",
},
{
id: "2",
type: "policy_changed",
actor: "John Doe",
target: "Password Policy",
timestamp: "2024-01-15T09:00:00Z",
details: "Minimum length changed from 8 to 12",
},
{
id: "3",
type: "member_disabled",
actor: "Jane Smith",
target: "bob@example.com",
timestamp: "2024-01-14T15:45:00Z",
details: "Account disabled",
},
{
id: "4",
type: "client_created",
actor: "John Doe",
target: "GitLab",
timestamp: "2024-01-14T12:00:00Z",
details: "OIDC client created",
},
{
id: "5",
type: "role_changed",
actor: "John Doe",
target: "jane@example.com",
timestamp: "2024-01-13T09:00:00Z",
details: "Role changed from member to admin",
},
];
const getEventIcon = (type: string) => {
switch (type) {
case "member_invited":
case "role_changed":
return <UserPlus className="w-4 h-4" />;
case "policy_changed":
return <Settings className="w-4 h-4" />;
case "member_disabled":
return <AlertTriangle className="w-4 h-4" />;
case "client_created":
return <Key className="w-4 h-4" />;
default:
return <User className="w-4 h-4" />;
} }
if (action.includes("policy") || action.includes("POLICY") || action.includes("mfa")) {
return <Settings className="w-4 h-4" />;
}
if (action.includes("delete") || action.includes("DELETE") || action.includes("disable")) {
return <AlertTriangle className="w-4 h-4" />;
}
if (action.includes("client") || action.includes("oidc") || action.includes("key")) {
return <Key className="w-4 h-4" />;
}
return <User className="w-4 h-4" />;
}; };
const getEventTitle = (type: string) => { const getEventTitle = (action: string) => {
switch (type) { const parts = action.split(".");
case "member_invited": return parts.map(p => p.charAt(0).toUpperCase() + p.slice(1)).join(" ");
return "Member invited"; };
case "policy_changed":
return "Policy changed"; const getActionCategory = (action: string): string => {
case "member_disabled": if (action.includes("member") || action.includes("MEMBER")) return "members";
return "Member disabled"; if (action.includes("policy") || action.includes("POLICY") || action.includes("mfa")) return "policies";
case "client_created": if (action.includes("client") || action.includes("OIDC")) return "clients";
return "OIDC client created"; return "other";
case "role_changed":
return "Role changed";
default:
return "Event";
}
}; };
export default function OrgAuditPage() { export default function OrgAuditPage() {
const params = useParams<{ orgId?: string }>();
const { orgId: fallbackOrgId } = useCurrentOrganizationId();
const orgId = params.orgId || fallbackOrgId;
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [typeFilter, setTypeFilter] = useState("all"); const [typeFilter, setTypeFilter] = useState("all");
const [auditLogs, setAuditLogs] = useState<AuditLogEntry[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchAuditLogs = useCallback(async (currentOrgId: string) => {
try {
setIsLoading(true);
setError(null);
const response = await api.organizations.getAuditLogs(currentOrgId);
setAuditLogs(response.audit_logs || []);
} catch (err) {
console.error("Failed to fetch audit logs:", err);
setError("Failed to load audit logs. Please try again.");
} finally {
setIsLoading(false);
}
}, []);
useEffect(() => {
setError(null);
setAuditLogs([]);
if (!orgId) {
setIsLoading(false);
return;
}
fetchAuditLogs(orgId);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [orgId]);
const formatDate = (dateString: string) => { const formatDate = (dateString: string) => {
const date = new Date(dateString); const date = new Date(dateString);
@@ -96,6 +83,20 @@ export default function OrgAuditPage() {
}).format(date); }).format(date);
}; };
const filteredLogs = auditLogs.filter((log) => {
const matchesSearch =
search === "" ||
log.description?.toLowerCase().includes(search.toLowerCase()) ||
log.action.toLowerCase().includes(search.toLowerCase()) ||
log.user?.email.toLowerCase().includes(search.toLowerCase());
const matchesFilter =
typeFilter === "all" ||
getActionCategory(log.action) === typeFilter;
return matchesSearch && matchesFilter;
});
return ( return (
<div className="page-container"> <div className="page-container">
<div className="page-header flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4"> <div className="page-header flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
@@ -137,39 +138,65 @@ export default function OrgAuditPage() {
<Card> <Card>
<CardContent className="p-0"> <CardContent className="p-0">
<div className="divide-y"> {isLoading ? (
{auditEvents.map((event) => ( <div className="flex items-center justify-center p-8">
<div key={event.id} className="p-4 flex items-start gap-4"> <Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
<div <span className="ml-2 text-muted-foreground">Loading audit logs...</span>
className={`w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0 ${ </div>
event.type === "member_disabled" ) : error ? (
? "bg-destructive/10 text-destructive" <div className="p-8 text-center text-destructive">
: "bg-accent/10 text-accent" {error}
}`} </div>
> ) : filteredLogs.length === 0 ? (
{getEventIcon(event.type)} <div className="p-8 text-center text-muted-foreground">
</div> No audit events found
<div className="flex-1 min-w-0"> </div>
<div className="flex items-center gap-2 flex-wrap"> ) : (
<p className="font-medium text-foreground"> <div className="divide-y">
{getEventTitle(event.type)} {filteredLogs.map((log) => (
</p> <div key={log.id} className="p-4 flex items-start gap-4">
<Badge variant="secondary" className="text-xs"> <div
{event.target} className={`w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0 ${
</Badge> !log.success
? "bg-destructive/10 text-destructive"
: "bg-accent/10 text-accent"
}`}
>
{getEventIcon(log.action)}
</div> </div>
<div className="mt-1 text-sm text-muted-foreground"> <div className="flex-1 min-w-0">
<span>by {event.actor}</span> <div className="flex items-center gap-2 flex-wrap">
<span className="mx-2"></span> <p className="font-medium text-foreground">
<span>{event.details}</span> {getEventTitle(log.action)}
</p>
{log.resource_type && (
<Badge variant="secondary" className="text-xs">
{log.resource_type}
</Badge>
)}
{!log.success && (
<Badge variant="destructive" className="text-xs">
Failed
</Badge>
)}
</div>
<div className="mt-1 text-sm text-muted-foreground">
<span>by {log.user?.full_name || log.user?.email || "System"}</span>
{log.description && (
<>
<span className="mx-2"></span>
<span>{log.description}</span>
</>
)}
</div>
</div> </div>
<p className="text-sm text-muted-foreground whitespace-nowrap">
{formatDate(log.created_at)}
</p>
</div> </div>
<p className="text-sm text-muted-foreground whitespace-nowrap"> ))}
{formatDate(event.timestamp)} </div>
</p> )}
</div>
))}
</div>
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
+190 -40
View File
@@ -1,19 +1,81 @@
import { Building2, Users, Shield, Key, ArrowRight, TrendingUp } from "lucide-react"; import { useEffect, useState } from "react";
import { Link } from "react-router-dom"; import { Building2, Users, Shield, Key, ArrowRight, TrendingUp, Loader2, Trash2, AlertTriangle, ArrowLeftRight } from "lucide-react";
import { Link, useNavigate } from "react-router-dom";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { api, OIDCClient, ApiError } from "@/lib/api";
import { useOrg } from "@/contexts/OrgContext";import { useOrganizations } from "@/hooks/useOrganizations";
import { toast } from "@/hooks/use-toast";
export default function OrgOverviewPage() { export default function OrgOverviewPage() {
// Mock organization data const navigate = useNavigate();
const org = { const { selectedOrg, selectOrg } = useOrg();
name: "Acme Corp", const { refetch: refetchOrgs } = useOrganizations();
createdAt: "January 2024", const [memberCount, setMemberCount] = useState<number>(0);
stats: { const [clientCount, setClientCount] = useState<number>(0);
totalMembers: 24, const [isLoading, setIsLoading] = useState(true);
activeToday: 18,
pendingInvites: 3, // Delete org dialog state
oidcClients: 5, const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
}, const [isDeleting, setIsDeleting] = useState(false);
const isOwner = selectedOrg?.role === "owner";
useEffect(() => {
if (!selectedOrg) return;
setIsLoading(true);
Promise.allSettled([
api.organizations.getMembers(selectedOrg.id),
api.organizations.getClients(selectedOrg.id),
]).then(([membersResp, clientsResp]) => {
if (membersResp.status === "fulfilled") setMemberCount(membersResp.value.count);
if (clientsResp.status === "fulfilled") setClientCount((clientsResp.value as { clients: OIDCClient[]; count: number }).count);
}).catch(console.error)
.finally(() => setIsLoading(false));
}, [selectedOrg?.id]);
const handleDeleteOrg = async () => {
if (!selectedOrg) return;
setIsDeleting(true);
try {
await api.organizations.deleteOrganization(selectedOrg.id);
toast({ title: "Organization deleted", description: `"${selectedOrg.name}" has been deleted.` });
setDeleteDialogOpen(false);
// Refresh org list; context will auto-select next available org
const result = await refetchOrgs();
const remaining = result.data ?? [];
if (remaining.length > 0) {
selectOrg(remaining[0]);
navigate("/org");
} else {
navigate("/org-setup");
}
} catch (err) {
if (err instanceof ApiError && err.type === "ORG_HAS_MEMBERS") {
toast({
title: "Cannot delete organization",
description: "This organization still has other members. Transfer ownership or remove all members first.",
variant: "destructive",
});
} else {
toast({
title: "Deletion failed",
description: err instanceof ApiError ? err.message : "An unexpected error occurred.",
variant: "destructive",
});
}
setDeleteDialogOpen(false);
} finally {
setIsDeleting(false);
}
}; };
const quickLinks = [ const quickLinks = [
@@ -37,6 +99,19 @@ export default function OrgOverviewPage() {
}, },
]; ];
if (isLoading && !selectedOrg) {
return (
<div className="page-container flex items-center justify-center py-12">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
);
}
const org = selectedOrg;
const createdAt = org?.created_at
? new Date(org.created_at).toLocaleDateString("en-US", { month: "long", year: "numeric" })
: "";
return ( return (
<div className="page-container"> <div className="page-container">
<div className="page-header"> <div className="page-header">
@@ -45,42 +120,20 @@ export default function OrgOverviewPage() {
<Building2 className="w-7 h-7 text-primary" /> <Building2 className="w-7 h-7 text-primary" />
</div> </div>
<div> <div>
<h1 className="page-title">{org.name}</h1> <h1 className="page-title">{org?.name ?? "Organization"}</h1>
<p className="page-description">Created {org.createdAt}</p> {createdAt && <p className="page-description">Created {createdAt}</p>}
</div> </div>
</div> </div>
</div> </div>
{/* Stats */} {/* Stats */}
<div className="grid gap-4 grid-cols-2 lg:grid-cols-4 mb-8"> <div className="grid gap-4 grid-cols-2 lg:grid-cols-3 mb-8">
<Card> <Card>
<CardContent className="p-4"> <CardContent className="p-4">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<p className="text-sm text-muted-foreground">Total Members</p> <p className="text-sm text-muted-foreground">Total Members</p>
<p className="text-2xl font-semibold">{org.stats.totalMembers}</p> <p className="text-2xl font-semibold">{memberCount}</p>
</div>
<Users className="w-8 h-8 text-muted-foreground/30" />
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-muted-foreground">Active Today</p>
<p className="text-2xl font-semibold">{org.stats.activeToday}</p>
</div>
<TrendingUp className="w-8 h-8 text-muted-foreground/30" />
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-muted-foreground">Pending Invites</p>
<p className="text-2xl font-semibold">{org.stats.pendingInvites}</p>
</div> </div>
<Users className="w-8 h-8 text-muted-foreground/30" /> <Users className="w-8 h-8 text-muted-foreground/30" />
</div> </div>
@@ -91,17 +144,28 @@ export default function OrgOverviewPage() {
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<p className="text-sm text-muted-foreground">OIDC Clients</p> <p className="text-sm text-muted-foreground">OIDC Clients</p>
<p className="text-2xl font-semibold">{org.stats.oidcClients}</p> <p className="text-2xl font-semibold">{clientCount}</p>
</div> </div>
<Key className="w-8 h-8 text-muted-foreground/30" /> <Key className="w-8 h-8 text-muted-foreground/30" />
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-muted-foreground">Org ID</p>
<p className="text-xs font-mono text-muted-foreground mt-1 truncate max-w-[140px]">{org?.id ?? "—"}</p>
</div>
<TrendingUp className="w-8 h-8 text-muted-foreground/30" />
</div>
</CardContent>
</Card>
</div> </div>
{/* Quick Links */} {/* Quick Links */}
<h2 className="text-lg font-semibold mb-4">Quick Actions</h2> <h2 className="text-lg font-semibold mb-4">Quick Actions</h2>
<div className="grid gap-4 md:grid-cols-3"> <div className="grid gap-4 md:grid-cols-3 mb-8">
{quickLinks.map((link) => ( {quickLinks.map((link) => (
<Link key={link.href} to={link.href}> <Link key={link.href} to={link.href}>
<Card className="h-full hover:border-accent/50 transition-colors cursor-pointer group"> <Card className="h-full hover:border-accent/50 transition-colors cursor-pointer group">
@@ -119,6 +183,92 @@ export default function OrgOverviewPage() {
</Link> </Link>
))} ))}
</div> </div>
{/* Danger Zone — owners only */}
{isOwner && (
<Card className="border-destructive/40">
<CardHeader>
<CardTitle className="text-base text-destructive flex items-center gap-2">
<AlertTriangle className="w-4 h-4" />
Danger Zone
</CardTitle>
<CardDescription>
Irreversible actions for this organization. Proceed with caution.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{/* Transfer ownership hint */}
<div className="flex items-center justify-between rounded-lg border border-border p-4">
<div>
<p className="text-sm font-medium">Transfer Ownership</p>
<p className="text-xs text-muted-foreground mt-0.5">
Pass ownership to another member before deleting the organization.
</p>
</div>
<Button
variant="outline"
size="sm"
onClick={() => navigate("/org/members")}
>
<ArrowLeftRight className="w-4 h-4 mr-2" />
Go to Members
</Button>
</div>
{/* Delete organization */}
<div className="flex items-center justify-between rounded-lg border border-destructive/30 bg-destructive/5 p-4">
<div>
<p className="text-sm font-medium text-destructive">Delete Organization</p>
<p className="text-xs text-muted-foreground mt-0.5">
Permanently deletes this organization.{" "}
{memberCount > 1
? `You must remove all ${memberCount - 1} other member${memberCount > 2 ? "s" : ""} first.`
: "This action cannot be undone."}
</p>
</div>
<Button
variant="destructive"
size="sm"
onClick={() => setDeleteDialogOpen(true)}
disabled={memberCount > 1}
>
<Trash2 className="w-4 h-4 mr-2" />
Delete
</Button>
</div>
</CardContent>
</Card>
)}
{/* Delete confirmation dialog */}
<Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle className="flex items-center gap-2 text-destructive">
<Trash2 className="w-5 h-5" />
Delete "{org?.name}"?
</DialogTitle>
<DialogDescription>
This will permanently delete the organization and all associated
data. This action <strong>cannot be undone</strong>.
</DialogDescription>
</DialogHeader>
<div className="rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">
<AlertTriangle className="w-4 h-4 inline mr-2" />
You are about to delete <strong>{org?.name}</strong>. All settings,
policies, OIDC clients, and CA configurations will be lost.
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setDeleteDialogOpen(false)} disabled={isDeleting}>
Cancel
</Button>
<Button variant="destructive" onClick={handleDeleteOrg} disabled={isDeleting}>
{isDeleting && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
Yes, delete organization
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div> </div>
); );
} }
+3 -16
View File
@@ -12,6 +12,7 @@ import { Button } from "@/components/ui/button";
import { api, OrgPolicyResponse, UpdateOrgPolicyDto, create403Handler } from "@/lib/api"; import { api, OrgPolicyResponse, UpdateOrgPolicyDto, create403Handler } from "@/lib/api";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
import { useOrg } from "@/contexts/OrgContext";
const MFA_MODE_LABELS: Record<string, { label: string; description: string }> = { const MFA_MODE_LABELS: Record<string, { label: string; description: string }> = {
disabled: { disabled: {
@@ -40,7 +41,7 @@ export default function PoliciesPage() {
const navigate = useNavigate(); const navigate = useNavigate();
const { toast } = useToast(); const { toast } = useToast();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const [currentOrgId, setCurrentOrgId] = useState<string | null>(null); const { selectedOrgId: currentOrgId } = useOrg();
// Local form state for unsaved changes // Local form state for unsaved changes
const [formData, setFormData] = useState({ const [formData, setFormData] = useState({
@@ -50,20 +51,6 @@ export default function PoliciesPage() {
}); });
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false); const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
// Fetch organizations to get current org
const { data: orgsData, isLoading: orgsLoading } = useQuery({
queryKey: ['organizations'],
queryFn: () => api.users.organizations({
on403: create403Handler(toast),
}),
});
useEffect(() => {
if (orgsData?.organizations && orgsData.organizations.length > 0) {
setCurrentOrgId(orgsData.organizations[0].id);
}
}, [orgsData]);
// Fetch org policy // Fetch org policy
const { data: policy, isLoading: policyLoading } = useQuery({ const { data: policy, isLoading: policyLoading } = useQuery({
queryKey: ['org-policy', currentOrgId], queryKey: ['org-policy', currentOrgId],
@@ -184,7 +171,7 @@ export default function PoliciesPage() {
} }
}; };
if (orgsLoading || policyLoading) { if (policyLoading) {
return ( return (
<div className="page-container"> <div className="page-container">
<div className="flex items-center justify-center py-12"> <div className="flex items-center justify-center py-12">
+426
View File
@@ -0,0 +1,426 @@
import { useState, useEffect, useCallback } from "react";
import { Search, Plus, MoreHorizontal, Users, Loader2, Trash2, Edit2, Link as LinkIcon, X } from "lucide-react";
import { useParams } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { api, Principal, Department } from "@/lib/api";
import { useCurrentOrganizationId } from "@/hooks/useCurrentOrganization";
import { useToast } from "@/hooks/use-toast";
export default function PrincipalsPage() {
const params = useParams<{ orgId?: string }>();
const { orgId: fallbackOrgId } = useCurrentOrganizationId();
const orgId = params.orgId || fallbackOrgId;
const { toast } = useToast();
const [search, setSearch] = useState("");
const [principals, setPrincipals] = useState<Principal[]>([]);
const [departments, setDepartments] = useState<Department[]>([]);
const [linkedDepts, setLinkedDepts] = useState<Record<string, Department[]>>({});
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
const [isLinkDialogOpen, setIsLinkDialogOpen] = useState(false);
const [editingPrincipal, setEditingPrincipal] = useState<Principal | null>(null);
const [selectedPrincipalForLink, setSelectedPrincipalForLink] = useState<Principal | null>(null);
const [selectedDepartmentId, setSelectedDepartmentId] = useState("");
const [isLinking, setIsLinking] = useState(false);
const [unlinkingKey, setUnlinkingKey] = useState<string | null>(null);
const [formData, setFormData] = useState({ name: "", description: "" });
const fetchLinkedDepts = useCallback(async (currentOrgId: string, principalList: Principal[]) => {
const entries = await Promise.all(
principalList.map(async (p) => {
try {
const res = await api.organizations.getPrincipalDepartments(currentOrgId, p.id);
return [p.id, res.departments] as [string, Department[]];
} catch {
return [p.id, []] as [string, Department[]];
}
})
);
setLinkedDepts(Object.fromEntries(entries));
}, []);
const fetchData = useCallback(async (currentOrgId: string) => {
try {
setIsLoading(true);
setError(null);
const [principalsRes, deptRes] = await Promise.all([
api.organizations.getPrincipals(currentOrgId),
api.organizations.getDepartments(currentOrgId),
]);
const pList = principalsRes.principals || [];
setPrincipals(pList);
setDepartments(deptRes.departments || []);
await fetchLinkedDepts(currentOrgId, pList);
} catch (err) {
console.error("Failed to fetch data:", err);
setError("Failed to load data. Please try again.");
} finally {
setIsLoading(false);
}
}, [fetchLinkedDepts]);
useEffect(() => {
setError(null);
setPrincipals([]);
setDepartments([]);
setLinkedDepts({});
if (!orgId) { setIsLoading(false); return; }
fetchData(orgId);
}, [orgId, fetchData]);
const handleCreatePrincipal = async () => {
if (!orgId || !formData.name.trim()) return;
try {
await api.organizations.createPrincipal(orgId, formData.name, formData.description || undefined);
setFormData({ name: "", description: "" });
setIsCreateDialogOpen(false);
await fetchData(orgId);
} catch {
toast({ variant: "destructive", title: "Failed to create principal" });
}
};
const handleUpdatePrincipal = async () => {
if (!orgId || !editingPrincipal || !formData.name.trim()) return;
try {
await api.organizations.updatePrincipal(orgId, editingPrincipal.id, {
name: formData.name,
description: formData.description || undefined,
});
setFormData({ name: "", description: "" });
setEditingPrincipal(null);
setIsEditDialogOpen(false);
await fetchData(orgId);
} catch {
toast({ variant: "destructive", title: "Failed to update principal" });
}
};
const handleDeletePrincipal = async (principalId: string) => {
if (!orgId || !confirm("Are you sure you want to delete this principal?")) return;
try {
await api.organizations.deletePrincipal(orgId, principalId);
await fetchData(orgId);
} catch {
toast({ variant: "destructive", title: "Failed to delete principal" });
}
};
const handleLinkPrincipal = async () => {
if (!orgId || !selectedPrincipalForLink || !selectedDepartmentId) return;
setIsLinking(true);
try {
await api.organizations.linkPrincipalToDepartment(orgId, selectedPrincipalForLink.id, selectedDepartmentId);
toast({ title: "Principal linked to department" });
setSelectedPrincipalForLink(null);
setSelectedDepartmentId("");
setIsLinkDialogOpen(false);
await fetchData(orgId);
} catch {
toast({ variant: "destructive", title: "Failed to link principal to department" });
} finally {
setIsLinking(false);
}
};
const handleUnlink = async (principalId: string, deptId: string) => {
if (!orgId) return;
const key = `${principalId}:${deptId}`;
setUnlinkingKey(key);
try {
await api.organizations.unlinkPrincipalFromDepartment(orgId, principalId, deptId);
toast({ title: "Unlinked from department" });
setLinkedDepts((prev) => ({
...prev,
[principalId]: (prev[principalId] || []).filter((d) => d.id !== deptId),
}));
} catch {
toast({ variant: "destructive", title: "Failed to unlink" });
} finally {
setUnlinkingKey(null);
}
};
const openEditDialog = (principal: Principal) => {
setEditingPrincipal(principal);
setFormData({ name: principal.name, description: principal.description || "" });
setIsEditDialogOpen(true);
};
const openLinkDialog = (principal: Principal) => {
setSelectedPrincipalForLink(principal);
setSelectedDepartmentId("");
setIsLinkDialogOpen(true);
};
const filteredPrincipals = principals.filter((p) => {
const s = search.toLowerCase();
return p.name.toLowerCase().includes(s) || (p.description?.toLowerCase().includes(s) ?? false);
});
// Only show departments not already linked
const availableToLink = selectedPrincipalForLink
? departments.filter((d) => !(linkedDepts[selectedPrincipalForLink.id] || []).some((ld) => ld.id === d.id))
: departments;
return (
<div className="page-container">
<div className="page-header flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<h1 className="page-title">Principals</h1>
<p className="page-description">Manage principals and link them to departments</p>
</div>
<Button onClick={() => { setFormData({ name: "", description: "" }); setIsCreateDialogOpen(true); }}>
<Plus className="w-4 h-4 mr-2" />
Create Principal
</Button>
</div>
<div className="mb-4">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
placeholder="Search principals..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10 max-w-sm"
/>
</div>
</div>
{error && <div className="mb-4 p-3 rounded-md bg-destructive/10 text-destructive text-sm">{error}</div>}
<Card>
<CardContent className="p-0">
{isLoading ? (
<div className="flex items-center justify-center p-8">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
<span className="ml-2 text-muted-foreground">Loading principals...</span>
</div>
) : filteredPrincipals.length === 0 ? (
<div className="p-8 text-center text-muted-foreground">No principals found</div>
) : (
<div className="divide-y">
{filteredPrincipals.map((principal) => {
const linked = linkedDepts[principal.id] || [];
return (
<div key={principal.id} className="p-4 flex items-start gap-4">
<div className="w-10 h-10 rounded-lg bg-purple-100 dark:bg-purple-900 text-purple-600 dark:text-purple-300 flex items-center justify-center flex-shrink-0 mt-0.5">
<Users className="w-4 h-4" />
</div>
<div className="flex-1 min-w-0">
<p className="font-medium text-foreground">{principal.name}</p>
{principal.description && (
<p className="mt-0.5 text-sm text-muted-foreground">{principal.description}</p>
)}
{/* Linked department tags */}
<div className="mt-2 flex flex-wrap gap-1.5">
{linked.length === 0 ? (
<span className="text-xs text-muted-foreground italic">Not linked to any department</span>
) : linked.map((dept) => {
const key = `${principal.id}:${dept.id}`;
const busy = unlinkingKey === key;
return (
<span
key={dept.id}
className="inline-flex items-center gap-1 text-xs bg-blue-50 dark:bg-blue-950/40 text-blue-700 dark:text-blue-300 border border-blue-200 dark:border-blue-800 rounded-full pl-2.5 pr-1 py-0.5"
>
{dept.name}
<button
onClick={() => handleUnlink(principal.id, dept.id)}
disabled={busy}
className="rounded-full p-0.5 hover:bg-blue-200 dark:hover:bg-blue-800 disabled:opacity-50 transition-colors"
title="Unlink from department"
>
{busy ? <Loader2 className="w-3 h-3 animate-spin" /> : <X className="w-3 h-3" />}
</button>
</span>
);
})}
</div>
<div className="mt-2 text-xs text-muted-foreground">
Created {new Date(principal.created_at).toLocaleDateString()}
</div>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon">
<MoreHorizontal className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => openEditDialog(principal)}>
<Edit2 className="w-4 h-4 mr-2" />
Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={() => openLinkDialog(principal)}>
<LinkIcon className="w-4 h-4 mr-2" />
Link to Department
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="text-destructive"
onClick={() => handleDeletePrincipal(principal.id)}
>
<Trash2 className="w-4 h-4 mr-2" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
);
})}
</div>
)}
</CardContent>
</Card>
{/* Create Principal Dialog */}
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Create Principal</DialogTitle>
<DialogDescription>Create a new principal to manage access and permissions</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="principal-name">Principal Name</Label>
<Input
id="principal-name"
placeholder="e.g., eng-prod"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
/>
</div>
<div>
<Label htmlFor="principal-desc">Description</Label>
<Textarea
id="principal-desc"
placeholder="Optional description..."
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
rows={3}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsCreateDialogOpen(false)}>Cancel</Button>
<Button onClick={handleCreatePrincipal} disabled={!formData.name.trim()}>Create Principal</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Edit Principal Dialog */}
<Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Edit Principal</DialogTitle>
<DialogDescription>Update principal information</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="edit-principal-name">Principal Name</Label>
<Input
id="edit-principal-name"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
/>
</div>
<div>
<Label htmlFor="edit-principal-desc">Description</Label>
<Textarea
id="edit-principal-desc"
placeholder="Optional description..."
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
rows={3}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsEditDialogOpen(false)}>Cancel</Button>
<Button onClick={handleUpdatePrincipal} disabled={!formData.name.trim()}>Save Changes</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Link to Department Dialog */}
<Dialog
open={isLinkDialogOpen}
onOpenChange={(open) => {
if (!open) { setSelectedPrincipalForLink(null); setSelectedDepartmentId(""); }
setIsLinkDialogOpen(open);
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>Link to Department</DialogTitle>
<DialogDescription>
Link <strong>{selectedPrincipalForLink?.name}</strong> to a department
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="dept-select">Department</Label>
{availableToLink.length === 0 ? (
<p className="mt-2 text-sm text-muted-foreground">Already linked to all available departments.</p>
) : (
<Select value={selectedDepartmentId} onValueChange={setSelectedDepartmentId}>
<SelectTrigger id="dept-select" className="mt-1">
<SelectValue placeholder="Choose a department..." />
</SelectTrigger>
<SelectContent>
{availableToLink.map((dept) => (
<SelectItem key={dept.id} value={dept.id}>{dept.name}</SelectItem>
))}
</SelectContent>
</Select>
)}
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsLinkDialogOpen(false)}>Cancel</Button>
<Button onClick={handleLinkPrincipal} disabled={!selectedDepartmentId || isLinking || availableToLink.length === 0}>
{isLinking && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
Link
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
+142 -140
View File
@@ -1,104 +1,60 @@
import { useState } from "react"; import { useState, useEffect } from "react";
import { LogIn, LogOut, Key, Fingerprint, Smartphone, AlertTriangle, CheckCircle, MapPin } from "lucide-react"; import { LogIn, LogOut, Key, Fingerprint, Smartphone, AlertTriangle, Loader2, RefreshCw, Users } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { api, AuditLogEntry } from "@/lib/api";
import { useAuth } from "@/contexts/AuthContext";
const activityEvents = [ // Map audit log action strings to display info
{ const getEventDisplay = (action: string) => {
id: "1", const a = action.toLowerCase();
type: "login_success", if (a.includes("login") && a.includes("fail")) {
method: "password", return { icon: <AlertTriangle className="w-4 h-4" />, title: "Failed login attempt", failed: true };
timestamp: "2024-01-15T10:30:00Z",
location: "San Francisco, CA",
device: "Chrome on macOS",
ip: "192.168.1.1",
},
{
id: "2",
type: "login_success",
method: "passkey",
timestamp: "2024-01-14T15:45:00Z",
location: "San Francisco, CA",
device: "Safari on iOS",
ip: "192.168.1.2",
},
{
id: "3",
type: "login_failed",
method: "password",
timestamp: "2024-01-14T12:00:00Z",
location: "Unknown",
device: "Firefox on Windows",
ip: "10.0.0.5",
},
{
id: "4",
type: "mfa_enabled",
method: "totp",
timestamp: "2024-01-13T09:00:00Z",
location: "San Francisco, CA",
device: "Chrome on macOS",
ip: "192.168.1.1",
},
{
id: "5",
type: "passkey_added",
method: "passkey",
timestamp: "2024-01-12T14:30:00Z",
location: "San Francisco, CA",
device: "Safari on macOS",
ip: "192.168.1.1",
},
];
const getEventIcon = (type: string, method: string) => {
switch (type) {
case "login_success":
return method === "passkey" ? (
<Fingerprint className="w-4 h-4" />
) : (
<LogIn className="w-4 h-4" />
);
case "login_failed":
return <AlertTriangle className="w-4 h-4" />;
case "mfa_enabled":
return <Smartphone className="w-4 h-4" />;
case "passkey_added":
return <Fingerprint className="w-4 h-4" />;
case "logout":
return <LogOut className="w-4 h-4" />;
default:
return <Key className="w-4 h-4" />;
} }
}; if (a.includes("login") || a.includes("authenticate")) {
return { icon: <LogIn className="w-4 h-4" />, title: "Signed in", failed: false };
const getEventTitle = (type: string, method: string) => {
switch (type) {
case "login_success":
return `Signed in with ${method}`;
case "login_failed":
return "Failed login attempt";
case "mfa_enabled":
return "Two-factor authentication enabled";
case "passkey_added":
return "Passkey added";
case "logout":
return "Signed out";
default:
return "Security event";
} }
}; if (a.includes("logout") || a.includes("sign_out")) {
return { icon: <LogOut className="w-4 h-4" />, title: "Signed out", failed: false };
const getEventStatus = (type: string) => {
if (type === "login_failed") {
return { variant: "destructive" as const, label: "Failed" };
} }
return { variant: "default" as const, label: "Success" }; if (a.includes("passkey") || a.includes("webauthn")) {
return { icon: <Fingerprint className="w-4 h-4" />, title: "Passkey event", failed: false };
}
if (a.includes("mfa") || a.includes("totp") || a.includes("2fa")) {
return { icon: <Smartphone className="w-4 h-4" />, title: "MFA event", failed: false };
}
if (a.includes("ssh")) {
return { icon: <Key className="w-4 h-4" />, title: "SSH key event", failed: false };
}
return { icon: <Key className="w-4 h-4" />, title: action.replace(/_/g, " "), failed: !action.includes("success") && a.includes("fail") };
}; };
export default function ActivityPage() { export default function ActivityPage() {
const { isOrgAdmin } = useAuth();
const [filter, setFilter] = useState("all"); const [filter, setFilter] = useState("all");
const [view, setView] = useState<"mine" | "org">("mine");
const [events, setEvents] = useState<AuditLogEntry[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState("");
const loadEvents = () => {
setIsLoading(true);
setError("");
const req =
view === "org" && isOrgAdmin
? api.admin.getAuditLogs({ per_page: "100" }).then((d) => d.audit_logs ?? [])
: api.users.auditLogs({ per_page: "50" }).then((d) => d.audit_logs ?? []);
req
.then((logs) => setEvents(logs))
.catch(() => setError("Failed to load activity. Please try again."))
.finally(() => setIsLoading(false));
};
useEffect(() => { loadEvents(); }, [view]); // eslint-disable-line react-hooks/exhaustive-deps
const formatDate = (dateString: string) => { const formatDate = (dateString: string) => {
const date = new Date(dateString); const date = new Date(dateString);
@@ -110,71 +66,117 @@ export default function ActivityPage() {
}).format(date); }).format(date);
}; };
const filteredEvents = events.filter((e) => {
if (filter === "all") return true;
const a = e.action.toLowerCase();
if (filter === "logins")
return a.includes("session_create") || a.includes("session_revoke") || a.includes("external_auth") || a.includes("login") || a.includes("logout");
if (filter === "security")
return a.includes("mfa") || a.includes("passkey") || a.includes("ssh") || a.includes("totp") || a.includes("password") || a.includes("webauthn");
return true;
});
return ( return (
<div className="page-container"> <div className="page-container">
<div className="page-header flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4"> <div className="page-header flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div> <div>
<h1 className="page-title">Activity</h1> <h1 className="page-title">Activity</h1>
<p className="page-description"> <p className="page-description">
Your recent account activity and security events {view === "org" ? "Organization-wide audit log" : "Your recent account activity and security events"}
</p> </p>
</div> </div>
<Select value={filter} onValueChange={setFilter}> <div className="flex items-center gap-2 flex-wrap">
<SelectTrigger className="w-[180px]"> {isOrgAdmin && (
<SelectValue placeholder="Filter events" /> <Tabs value={view} onValueChange={(v) => setView(v as "mine" | "org")}>
</SelectTrigger> <TabsList>
<SelectContent> <TabsTrigger value="mine">My Activity</TabsTrigger>
<SelectItem value="all">All events</SelectItem> <TabsTrigger value="org">
<SelectItem value="logins">Logins only</SelectItem> <Users className="w-3.5 h-3.5 mr-1" />
<SelectItem value="security">Security changes</SelectItem> Org Logs
</SelectContent> </TabsTrigger>
</Select> </TabsList>
</Tabs>
)}
<Select value={filter} onValueChange={setFilter}>
<SelectTrigger className="w-[160px]">
<SelectValue placeholder="Filter events" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All events</SelectItem>
<SelectItem value="logins">Logins only</SelectItem>
<SelectItem value="security">Security changes</SelectItem>
</SelectContent>
</Select>
<Button variant="outline" size="icon" onClick={loadEvents} disabled={isLoading}>
<RefreshCw className={`w-4 h-4 ${isLoading ? "animate-spin" : ""}`} />
</Button>
</div>
</div> </div>
<Card> <Card>
<CardContent className="p-0"> <CardContent className="p-0">
<div className="divide-y"> {isLoading ? (
{activityEvents.map((event) => { <div className="flex items-center justify-center py-12">
const status = getEventStatus(event.type); <Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
return ( </div>
<div key={event.id} className="p-4 flex items-start gap-4"> ) : error ? (
<div <div className="text-center py-8 text-muted-foreground">
className={`w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0 ${ <AlertTriangle className="w-8 h-8 mx-auto mb-2 text-destructive" />
event.type === "login_failed" <p>{error}</p>
? "bg-destructive/10 text-destructive" </div>
: "bg-accent/10 text-accent" ) : filteredEvents.length === 0 ? (
}`} <div className="text-center py-8 text-muted-foreground">
> <p>No activity events found.</p>
{getEventIcon(event.type, event.method)} </div>
</div> ) : (
<div className="flex-1 min-w-0"> <div className="divide-y">
<div className="flex items-center gap-2 flex-wrap"> {filteredEvents.map((event) => {
<p className="font-medium text-foreground"> const display = getEventDisplay(event.action);
{getEventTitle(event.type, event.method)} return (
</p> <div key={event.id} className="p-4 flex items-start gap-4">
{event.type === "login_failed" && ( <div
<Badge variant="destructive" className="text-xs"> className={`w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0 ${
Failed display.failed || !event.success
</Badge> ? "bg-destructive/10 text-destructive"
)} : "bg-accent/10 text-accent"
}`}
>
{display.icon}
</div> </div>
<div className="mt-1 text-sm text-muted-foreground space-y-0.5"> <div className="flex-1 min-w-0">
<p>{event.device}</p> <div className="flex items-center gap-2 flex-wrap">
<div className="flex items-center gap-2"> <p className="font-medium text-foreground capitalize">
<MapPin className="w-3 h-3" /> {display.title}
<span>{event.location}</span> </p>
<span className="text-muted-foreground/50"></span> {(!event.success || display.failed) && (
<span className="font-mono text-xs">{event.ip}</span> <Badge variant="destructive" className="text-xs">
Failed
</Badge>
)}
</div>
<div className="mt-1 text-sm text-muted-foreground space-y-0.5">
{view === "org" && event.user_id && (
<p className="font-medium text-xs text-foreground/70">User: {event.user_id}</p>
)}
{event.description && <p>{event.description}</p>}
<div className="flex items-center gap-2 flex-wrap">
{event.ip_address && (
<span className="font-mono text-xs">{event.ip_address}</span>
)}
{event.user_agent && (
<span className="truncate max-w-[200px]">{event.user_agent}</span>
)}
</div>
</div> </div>
</div> </div>
<p className="text-sm text-muted-foreground whitespace-nowrap">
{formatDate(event.created_at)}
</p>
</div> </div>
<p className="text-sm text-muted-foreground whitespace-nowrap"> );
{formatDate(event.timestamp)} })}
</p> </div>
</div> )}
);
})}
</div>
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
+156 -81
View File
@@ -1,5 +1,5 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { Mail, Building2, Upload, CheckCircle, AlertCircle, Loader2 } from "lucide-react"; import { Mail, Upload, CheckCircle, AlertCircle, Loader2, Bell, AlertTriangle, Trash2, Building2 } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
@@ -7,10 +7,18 @@ import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from "@/components/ui/skeleton";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { useAuth } from "@/contexts/AuthContext"; import { useAuth } from "@/contexts/AuthContext";
import { api, Organization, ApiError } from "@/lib/api"; import { api, ApiError, PendingInvite } from "@/lib/api";
import { useOrganizations } from "@/hooks/useOrganizations";
import { toast } from "@/hooks/use-toast"; import { toast } from "@/hooks/use-toast";
import { useNavigate } from "react-router-dom";
function ProfileSkeleton() { function ProfileSkeleton() {
return ( return (
@@ -52,38 +60,22 @@ function ProfileSkeleton() {
<Skeleton className="h-12 w-full" /> <Skeleton className="h-12 w-full" />
</CardContent> </CardContent>
</Card> </Card>
{/* Organizations Skeleton */}
<Card>
<CardHeader>
<Skeleton className="h-5 w-28" />
<Skeleton className="h-4 w-48 mt-1" />
</CardHeader>
<CardContent className="space-y-2">
<Skeleton className="h-14 w-full" />
<Skeleton className="h-14 w-full" />
</CardContent>
</Card>
</div> </div>
</div> </div>
); );
} }
export default function ProfilePage() { export default function ProfilePage() {
const { user, isLoading: authLoading, refreshUser } = useAuth(); const { user, isLoading: authLoading, refreshUser, logout } = useAuth();
const navigate = useNavigate();
const [name, setName] = useState(""); const [name, setName] = useState("");
const [isEditing, setIsEditing] = useState(false); const [isEditing, setIsEditing] = useState(false);
const [isSaving, setIsSaving] = useState(false); const [isSaving, setIsSaving] = useState(false);
const [pendingInvites, setPendingInvites] = useState<PendingInvite[]>([]);
// Use React Query hook for organizations with automatic caching and deduplication // Delete account dialog state
const { data: organizations = [], isLoading: orgsLoading, error: orgsError } = useOrganizations(); const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
// Debug logging
console.log('[ProfilePage] organizations data:', organizations);
console.log('[ProfilePage] organizations is array:', Array.isArray(organizations));
// Ensure organizations is always an array (defensive check)
const organizationsArray = Array.isArray(organizations) ? organizations : [];
// Sync local name state with user data // Sync local name state with user data
useEffect(() => { useEffect(() => {
@@ -92,16 +84,13 @@ export default function ProfilePage() {
} }
}, [user?.full_name]); }, [user?.full_name]);
// Handle 403 errors for organizations // Fetch pending invitations for this user
useEffect(() => { useEffect(() => {
if (orgsError instanceof ApiError && orgsError.code === 403) { if (!user) return;
toast({ api.users.getMyInvites()
title: "Access Denied", .then((res) => setPendingInvites(res.invites ?? []))
description: "You don't have permission to view organizations. Please contact your organization administrator.", .catch(() => { /* silently ignore */ });
variant: "destructive", }, [user]);
});
}
}, [orgsError]);
const getInitials = (fullName: string | null) => { const getInitials = (fullName: string | null) => {
if (!fullName) return "?"; if (!fullName) return "?";
@@ -113,6 +102,35 @@ export default function ProfilePage() {
.slice(0, 2); .slice(0, 2);
}; };
const handleDeleteAccount = async () => {
setIsDeleting(true);
try {
await api.users.deleteMe();
toast({ title: "Account deleted", description: "Your account has been deleted." });
setDeleteDialogOpen(false);
await logout();
navigate("/login");
} catch (err) {
if (err instanceof ApiError && err.type === "USER_IS_SOLE_OWNER") {
const orgs: string[] = (err.details?.organizations as string[]) ?? [];
toast({
title: "Cannot delete account",
description: `You are the sole owner of: ${orgs.join(", ")}. Transfer ownership or delete those organizations first.`,
variant: "destructive",
});
} else {
toast({
title: "Deletion failed",
description: err instanceof ApiError ? err.message : "An unexpected error occurred.",
variant: "destructive",
});
}
setDeleteDialogOpen(false);
} finally {
setIsDeleting(false);
}
};
const handleSave = async () => { const handleSave = async () => {
if (!name.trim()) { if (!name.trim()) {
toast({ toast({
@@ -159,11 +177,53 @@ export default function ProfilePage() {
<div className="page-header"> <div className="page-header">
<h1 className="page-title">Profile</h1> <h1 className="page-title">Profile</h1>
<p className="page-description"> <p className="page-description">
Manage your personal information and organization memberships Manage your personal information and account settings
</p> </p>
</div> </div>
<div className="space-y-6"> <div className="space-y-6">
{/* Account Suspended Banner */}
{(user.status === "suspended" || user.status === "compliance_suspended") && (
<div className="flex items-start gap-3 rounded-lg border border-red-300 bg-red-50 px-4 py-4 text-red-800 dark:border-red-700 dark:bg-red-950/60 dark:text-red-300">
<AlertTriangle className="w-5 h-5 mt-0.5 flex-shrink-0" />
<div>
<p className="font-semibold text-sm">Account suspended</p>
<p className="text-sm mt-0.5 opacity-90">
Your account has been suspended. You cannot perform most actions.
Please contact your administrator to resolve this.
</p>
</div>
</div>
)}
{/* Pending Invitations Banner */}
{pendingInvites.length > 0 && (
<div className="rounded-lg border border-primary/40 bg-primary/10 p-4 space-y-3">
<div className="flex items-center gap-2 text-primary font-semibold text-sm">
<Bell className="w-4 h-4" />
You have {pendingInvites.length} pending invitation{pendingInvites.length > 1 ? "s" : ""}
</div>
{pendingInvites.map((invite) => (
<div
key={invite.token}
className="flex items-center justify-between rounded-md border border-border bg-card px-4 py-3"
>
<div>
<p className="text-sm font-medium text-foreground">{invite.organization.name}</p>
<p className="text-xs text-muted-foreground capitalize">
Invited as <span className="font-medium">{invite.role}</span>
</p>
</div>
<a
href={`/invite?token=${invite.token}`}
className="inline-flex items-center gap-1 rounded-md bg-primary px-3 py-1.5 text-xs font-semibold text-primary-foreground hover:bg-primary/90 transition-colors"
>
Accept
</a>
</div>
))}
</div>
)}
{/* Profile Photo & Name */} {/* Profile Photo & Name */}
<Card> <Card>
<CardHeader> <CardHeader>
@@ -248,59 +308,74 @@ export default function ProfilePage() {
</CardContent> </CardContent>
</Card> </Card>
{/* Organizations */} {/* Danger Zone */}
<Card> <Card className="border-destructive/40">
<CardHeader> <CardHeader>
<CardTitle className="text-base">Organizations</CardTitle> <CardTitle className="text-base text-destructive flex items-center gap-2">
<CardDescription>Organizations you're a member of</CardDescription> <AlertTriangle className="w-4 h-4" />
Danger Zone
</CardTitle>
<CardDescription>
Irreversible actions for your account. Proceed with caution.
</CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{orgsLoading ? ( <div className="flex items-center justify-between rounded-lg border border-destructive/30 bg-destructive/5 p-4">
<div className="space-y-2"> <div>
<Skeleton className="h-14 w-full" /> <p className="text-sm font-medium text-destructive">Delete Account</p>
<Skeleton className="h-14 w-full" /> <p className="text-xs text-muted-foreground mt-0.5">
Permanently deletes your profile and all associated data. If you own
any organizations you must transfer ownership or delete them first.
</p>
</div> </div>
) : organizationsArray.length === 0 ? ( <Button
<p className="text-sm text-muted-foreground text-center py-6"> variant="destructive"
You're not a member of any organizations yet. size="sm"
</p> onClick={() => setDeleteDialogOpen(true)}
) : ( >
<div className="space-y-2"> <Trash2 className="w-4 h-4 mr-2" />
{organizationsArray.map((org) => ( Delete account
<div </Button>
key={org.id} </div>
className="flex items-center justify-between p-3 border rounded-lg"
>
<div className="flex items-center gap-3">
{org.logo_url ? (
<Avatar className="w-8 h-8">
<AvatarImage src={org.logo_url} />
<AvatarFallback>
<Building2 className="w-4 h-4 text-primary" />
</AvatarFallback>
</Avatar>
) : (
<div className="w-8 h-8 rounded bg-primary/10 flex items-center justify-center">
<Building2 className="w-4 h-4 text-primary" />
</div>
)}
<span className="text-foreground font-medium">{org.name}</span>
</div>
<div className="flex items-center gap-2">
{(org.role === 'owner' || org.role === 'admin') && (
<Badge variant="default" className="bg-primary text-primary-foreground">
Admin
</Badge>
)}
<Badge variant="secondary" className="capitalize">{org.role}</Badge>
</div>
</div>
))}
</div>
)}
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
{/* Delete account confirmation dialog */}
<Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle className="flex items-center gap-2 text-destructive">
<Trash2 className="w-5 h-5" />
Delete your account?
</DialogTitle>
<DialogDescription>
Your profile, SSH keys, linked accounts, and session data will be
permanently deleted. This action <strong>cannot be undone</strong>.
</DialogDescription>
</DialogHeader>
<div className="rounded-lg border border-amber-300 bg-amber-50 dark:border-amber-700 dark:bg-amber-950/40 p-3 text-sm text-amber-800 dark:text-amber-300 space-y-1">
<p className="flex items-center gap-2 font-medium">
<Building2 className="w-4 h-4" />
Organization ownership check
</p>
<p>
If you are the sole owner of any organization that has other members,
you must <strong>transfer ownership</strong> to another member or delete
those organizations before proceeding.
</p>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setDeleteDialogOpen(false)} disabled={isDeleting}>
Cancel
</Button>
<Button variant="destructive" onClick={handleDeleteAccount} disabled={isDeleting}>
{isDeleting && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
Yes, delete my account
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div> </div>
); );
} }
File diff suppressed because it is too large Load Diff