Feat: RBAC, Keys Extension, Invites
feat: org members page — invite users, cancel invites, change roles feat: show pending invitations banner on profile page feat: invite accept flow for existing users (no password needed) feat: departments page updates feat: SSH keys page — dept cert policy UI (expiry + extensions) feat: wire up auth pages to real API (register, verify, reset, OIDC) feat: CLI auth bridge — login page handles CLI token flow feat: admin users — suspend/unsuspend, role badges, role filter feat: add admin OAuth providers management page feat: activity page — org-wide audit log view for admins feat: add my memberships page chore: add isOrgAdmin/isOrgMember to AuthContext, restrict sidebar chore: update app routing and shared layout
This commit is contained in:
+42
-14
@@ -38,8 +38,10 @@ 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 AdminUsersPage from "@/pages/admin/AdminUsersPage";
|
||||
import OAuthProvidersPage from "@/pages/admin/OAuthProvidersPage";
|
||||
|
||||
import NotFound from "@/pages/NotFound";
|
||||
import ApiDevTools from "@/components/dev/ApiDevTools";
|
||||
@@ -78,8 +80,30 @@ 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, isLoading } = useAuth();
|
||||
// Allow authenticated users through to /login when it's a CLI auth request —
|
||||
// LoginPage will immediately forward the existing token to the CLI callback.
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const isCli = params.has('cli_token') || params.has('cli_redirect');
|
||||
if (isLoading) return null; // wait for auth state to resolve
|
||||
if (isAuthenticated) return <Navigate to="/profile" replace />;
|
||||
if (isAuthenticated && !isCli) return <Navigate to="/profile" 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}</>;
|
||||
}
|
||||
|
||||
@@ -113,20 +137,24 @@ function AppRoutes() {
|
||||
<Route path="/activity" element={<ActivityPage />} />
|
||||
<Route path="/ssh-keys" element={<SSHKeysPage />} />
|
||||
|
||||
{/* Organization routes */}
|
||||
<Route path="/org" element={<OrgOverviewPage />} />
|
||||
<Route path="/org/members" element={<MembersPage />} />
|
||||
<Route path="/org/departments" element={<DepartmentsPage />} />
|
||||
<Route path="/org/principals" element={<PrincipalsPage />} />
|
||||
<Route path="/org/policies" element={<PoliciesPage />} />
|
||||
<Route path="/org/policies/compliance" element={<CompliancePage />} />
|
||||
<Route path="/org/audit" element={<OrgAuditPage />} />
|
||||
<Route path="/org/clients" element={<OIDCClientsPage />} />
|
||||
<Route path="/org/cas" element={<CAsPage />} />
|
||||
{/* Organization routes — org members: overview + own memberships only */}
|
||||
<Route path="/org" element={<RequireOrgMember><OrgOverviewPage /></RequireOrgMember>} />
|
||||
<Route path="/org/my-memberships" element={<RequireOrgMember><MyMembershipsPage /></RequireOrgMember>} />
|
||||
|
||||
{/* Admin routes */}
|
||||
<Route path="/admin/audit" element={<SystemAuditPage />} />
|
||||
<Route path="/admin/users" element={<AdminUsersPage />} />
|
||||
{/* Organization management routes — org admins/owners only */}
|
||||
<Route path="/org/members" element={<RequireAdmin><MembersPage /></RequireAdmin>} />
|
||||
<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={<RequireAdmin><AdminUsersPage /></RequireAdmin>} />
|
||||
<Route path="/admin/oauth" element={<RequireAdmin><OAuthProvidersPage /></RequireAdmin>} />
|
||||
</Route>
|
||||
|
||||
{/* Catch-all */}
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
Users,
|
||||
Settings,
|
||||
FileText,
|
||||
Key,
|
||||
Layers,
|
||||
GitBranch,
|
||||
ScrollText,
|
||||
@@ -17,6 +16,7 @@ import {
|
||||
} from "lucide-react";
|
||||
import { GatehouseLogo } from "@/components/branding/GatehouseLogo";
|
||||
import { NavLink } from "@/components/NavLink";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
@@ -40,19 +40,25 @@ const userNavItems = [
|
||||
{ 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: "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: "Audit Log", url: "/org/audit", icon: FileText },
|
||||
];
|
||||
|
||||
const adminNavItems = [
|
||||
{ title: "OIDC Clients", url: "/org/clients", icon: Key },
|
||||
{ title: "Users", url: "/admin/users", icon: Users },
|
||||
{ title: "Certificate Auth.", url: "/org/cas", icon: ShieldCheck },
|
||||
// { title: "Users", url: "/admin/users", icon: Users },
|
||||
{ title: "Org Audit Log", url: "/org/audit", icon: FileText },
|
||||
{ title: "System Logs", url: "/admin/audit", icon: ScrollText },
|
||||
];
|
||||
|
||||
@@ -60,10 +66,11 @@ export function AppSidebar() {
|
||||
const { state } = useSidebar();
|
||||
const collapsed = state === "collapsed";
|
||||
const location = useLocation();
|
||||
const { isOrgAdmin, isOrgMember } = useAuth();
|
||||
|
||||
const isActive = (path: string) => location.pathname === path;
|
||||
const isOrgActive = orgNavItems.some((item) => isActive(item.url)) || adminNavItems.some((item) => isActive(item.url));
|
||||
const isUserActive = userNavItems.some((item) => isActive(item.url));
|
||||
const isOrgActive = orgAdminNavItems.some((item) => isActive(item.url)) || adminNavItems.some((item) => isActive(item.url));
|
||||
void isOrgActive; // used for future active state tracking
|
||||
|
||||
return (
|
||||
<Sidebar
|
||||
@@ -88,9 +95,11 @@ export function AppSidebar() {
|
||||
<SidebarContent className="py-4">
|
||||
{/* User Section */}
|
||||
<SidebarGroup>
|
||||
{!collapsed && (
|
||||
<SidebarGroupLabel className="px-4 text-xs font-medium text-sidebar-muted uppercase tracking-wider">
|
||||
{!collapsed && "Account"}
|
||||
Account
|
||||
</SidebarGroupLabel>
|
||||
)}
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
{userNavItems.map((item) => (
|
||||
@@ -100,8 +109,11 @@ export function AppSidebar() {
|
||||
to={item.url}
|
||||
end
|
||||
className={cn(
|
||||
"flex items-center gap-3 px-4 py-2.5 text-sm text-sidebar-foreground rounded-lg mx-2 transition-colors",
|
||||
"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
|
||||
"flex items-center text-sm text-sidebar-foreground rounded-lg transition-colors",
|
||||
"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"
|
||||
>
|
||||
@@ -115,22 +127,28 @@ export function AppSidebar() {
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
|
||||
{/* Organization Section */}
|
||||
{/* Organization Section — content differs by role */}
|
||||
{isOrgMember && (
|
||||
<SidebarGroup className="mt-4">
|
||||
{!collapsed && (
|
||||
<SidebarGroupLabel className="px-4 text-xs font-medium text-sidebar-muted uppercase tracking-wider">
|
||||
{!collapsed && "Organization"}
|
||||
Organization
|
||||
</SidebarGroupLabel>
|
||||
)}
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
{orgNavItems.map((item) => (
|
||||
{(isOrgAdmin ? orgAdminNavItems : orgMemberNavItems).map((item) => (
|
||||
<SidebarMenuItem key={item.title}>
|
||||
<SidebarMenuButton asChild>
|
||||
<NavLink
|
||||
to={item.url}
|
||||
end
|
||||
className={cn(
|
||||
"flex items-center gap-3 px-4 py-2.5 text-sm text-sidebar-foreground rounded-lg mx-2 transition-colors",
|
||||
"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
|
||||
"flex items-center text-sm text-sidebar-foreground rounded-lg transition-colors",
|
||||
"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"
|
||||
>
|
||||
@@ -143,12 +161,16 @@ export function AppSidebar() {
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
)}
|
||||
|
||||
{/* Admin Section */}
|
||||
{/* Admin Section — only visible to org admins/owners */}
|
||||
{isOrgAdmin && (
|
||||
<SidebarGroup className="mt-4">
|
||||
{!collapsed && (
|
||||
<SidebarGroupLabel className="px-4 text-xs font-medium text-sidebar-muted uppercase tracking-wider">
|
||||
{!collapsed && "Admin"}
|
||||
Admin
|
||||
</SidebarGroupLabel>
|
||||
)}
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
{adminNavItems.map((item) => (
|
||||
@@ -158,8 +180,11 @@ export function AppSidebar() {
|
||||
to={item.url}
|
||||
end
|
||||
className={cn(
|
||||
"flex items-center gap-3 px-4 py-2.5 text-sm text-sidebar-foreground rounded-lg mx-2 transition-colors",
|
||||
"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
|
||||
"flex items-center text-sm text-sidebar-foreground rounded-lg transition-colors",
|
||||
"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"
|
||||
>
|
||||
@@ -172,6 +197,7 @@ export function AppSidebar() {
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
)}
|
||||
</SidebarContent>
|
||||
|
||||
<SidebarFooter className="p-4 border-t border-sidebar-border">
|
||||
|
||||
@@ -12,10 +12,12 @@ interface AuthContextType {
|
||||
user: User | null;
|
||||
isLoading: boolean;
|
||||
isAuthenticated: boolean;
|
||||
isOrgAdmin: boolean;
|
||||
isOrgMember: boolean;
|
||||
mfaCompliance: MfaComplianceSummary | null;
|
||||
requiresMfaEnrollment: boolean;
|
||||
login: (email: string, password: string, rememberMe?: boolean) => Promise<LoginResult>;
|
||||
verifyTotp: (code: string, isBackupCode?: boolean) => Promise<void>;
|
||||
login: (email: string, password: string, rememberMe?: boolean, skipNavigate?: boolean) => Promise<LoginResult>;
|
||||
verifyTotp: (code: string, isBackupCode?: boolean, skipNavigate?: boolean) => Promise<void>;
|
||||
verifyWebAuthn: () => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
refreshUser: () => Promise<void>;
|
||||
@@ -40,66 +42,61 @@ function persistMfaCompliance(compliance: MfaComplianceSummary | null): void {
|
||||
function loadMfaCompliance(): MfaComplianceSummary | null {
|
||||
try {
|
||||
const stored = localStorage.getItem(MFA_COMPLIANCE_KEY);
|
||||
if (!stored) {
|
||||
console.log('[AuthContext] loadMfaCompliance: no stored data');
|
||||
return null;
|
||||
}
|
||||
if (!stored) return null;
|
||||
|
||||
const parsed = JSON.parse(stored);
|
||||
console.log('[AuthContext] loadMfaCompliance: raw parsed:', parsed);
|
||||
|
||||
// Handle both direct format and legacy double-nested format
|
||||
// Legacy format: { mfa_compliance: { ... } }
|
||||
// Current format: { ... }
|
||||
let compliance: Record<string, unknown>;
|
||||
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>;
|
||||
} else {
|
||||
compliance = parsed;
|
||||
}
|
||||
|
||||
// Validate that the stored data has the required fields
|
||||
if (!compliance || typeof compliance !== 'object') {
|
||||
console.log('[AuthContext] loadMfaCompliance: invalid compliance object');
|
||||
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');
|
||||
}
|
||||
if (!compliance || typeof compliance !== 'object') return null;
|
||||
if (!Array.isArray(compliance.orgs)) return null;
|
||||
|
||||
// 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
|
||||
const hasEffectiveMode = compliance.orgs.some((org: Record<string, unknown>) =>
|
||||
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;
|
||||
} catch (error) {
|
||||
console.log('[AuthContext] loadMfaCompliance: error loading:', error);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
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 [requiresMfaEnrollment, setRequiresMfaEnrollment] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
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 () => {
|
||||
try {
|
||||
const compliance = await api.policies.getMyCompliance();
|
||||
@@ -148,7 +145,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const response = await api.users.me();
|
||||
setUser(response.user);
|
||||
|
||||
// Also fetch compliance status
|
||||
// Also fetch compliance status and org role
|
||||
try {
|
||||
const compliance = await api.policies.getMyCompliance();
|
||||
setMfaCompliance(compliance);
|
||||
@@ -159,8 +156,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
setMfaCompliance(null);
|
||||
persistMfaCompliance(null);
|
||||
}
|
||||
// Check org admin status
|
||||
await checkOrgAdmin();
|
||||
} catch {
|
||||
setUser(null);
|
||||
setIsOrgAdmin(false);
|
||||
setIsOrgMember(false);
|
||||
setMfaCompliance(null);
|
||||
persistMfaCompliance(null);
|
||||
setRequiresMfaEnrollment(false);
|
||||
@@ -172,32 +173,21 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
checkAuth();
|
||||
}, []);
|
||||
|
||||
const login = useCallback(async (email: string, password: string, rememberMe = false): Promise<LoginResult> => {
|
||||
console.log('[AuthContext] login() called');
|
||||
const login = useCallback(async (email: string, password: string, rememberMe = false, skipNavigate = false): Promise<LoginResult> => {
|
||||
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 (response.requires_webauthn) {
|
||||
console.log('[AuthContext] WebAuthn required, returning early');
|
||||
return { requiresTotp: false, requiresWebAuthn: true };
|
||||
}
|
||||
|
||||
// If TOTP is required, don't set user yet - wait for TOTP verification
|
||||
if (response.requires_totp) {
|
||||
console.log('[AuthContext] TOTP required, returning early');
|
||||
return { requiresTotp: true, requiresWebAuthn: false };
|
||||
}
|
||||
|
||||
// If MFA enrollment is required (past deadline), set compliance state
|
||||
if (response.requires_mfa_enrollment) {
|
||||
console.log('[AuthContext] MFA enrollment required, setting compliance state');
|
||||
if (response.token) {
|
||||
tokenManager.setToken(response.token, response.expires_at ?? null);
|
||||
}
|
||||
@@ -212,47 +202,38 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
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) {
|
||||
console.log('[AuthContext] Storing token in localStorage');
|
||||
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) {
|
||||
console.log('[AuthContext] Setting user state and navigating to /profile');
|
||||
setUser(response.user);
|
||||
if (response.mfa_compliance) {
|
||||
setMfaCompliance(response.mfa_compliance);
|
||||
persistMfaCompliance(response.mfa_compliance);
|
||||
}
|
||||
setRequiresMfaEnrollment(false);
|
||||
await checkOrgAdmin();
|
||||
if (!skipNavigate) {
|
||||
navigate('/profile');
|
||||
}
|
||||
}
|
||||
return { requiresTotp: false, requiresWebAuthn: false };
|
||||
}, [navigate]);
|
||||
}, [navigate, checkOrgAdmin]);
|
||||
|
||||
const verifyWebAuthn = useCallback(async () => {
|
||||
// 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);
|
||||
|
||||
// Store token explicitly before setting user state
|
||||
// This ensures the token is available for any subsequent API calls
|
||||
if (response.token) {
|
||||
tokenManager.setToken(response.token, response.expires_at ?? null);
|
||||
}
|
||||
|
||||
setUser(response.user);
|
||||
|
||||
// Check for MFA compliance in response
|
||||
try {
|
||||
const compliance = await api.policies.getMyCompliance();
|
||||
setMfaCompliance(compliance);
|
||||
@@ -263,14 +244,19 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
persistMfaCompliance(null);
|
||||
}
|
||||
|
||||
await checkOrgAdmin();
|
||||
if (!skipNavigate) {
|
||||
navigate('/profile');
|
||||
}, [navigate]);
|
||||
}
|
||||
}, [navigate, checkOrgAdmin]);
|
||||
|
||||
const logout = useCallback(async () => {
|
||||
try {
|
||||
await api.auth.logout();
|
||||
} finally {
|
||||
setUser(null);
|
||||
setIsOrgAdmin(false);
|
||||
setIsOrgMember(false);
|
||||
setMfaCompliance(null);
|
||||
persistMfaCompliance(null);
|
||||
setRequiresMfaEnrollment(false);
|
||||
@@ -284,6 +270,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
user,
|
||||
isLoading,
|
||||
isAuthenticated: !!user,
|
||||
isOrgAdmin,
|
||||
isOrgMember,
|
||||
mfaCompliance,
|
||||
requiresMfaEnrollment,
|
||||
login,
|
||||
|
||||
+109
-3
@@ -25,6 +25,10 @@ export interface User {
|
||||
last_login_at: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
// Fields present in admin list view
|
||||
org_role?: string;
|
||||
org_id?: string;
|
||||
activated?: boolean;
|
||||
}
|
||||
|
||||
export interface Organization {
|
||||
@@ -471,6 +475,14 @@ export const api = {
|
||||
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: {
|
||||
@@ -495,6 +507,51 @@ export const api = {
|
||||
// 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),
|
||||
|
||||
// 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: {
|
||||
@@ -873,6 +930,16 @@ export const api = {
|
||||
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),
|
||||
@@ -918,14 +985,14 @@ export const api = {
|
||||
invites: {
|
||||
// Get invite details by token (unauthenticated)
|
||||
getInfo: (token: string) =>
|
||||
request<{ email: string; organization: { id: string; name: string }; role: string }>(
|
||||
request<{ email: string; organization: { id: string; name: string }; role: string; user_exists?: boolean }>(
|
||||
`/invites/${token}`,
|
||||
{},
|
||||
false,
|
||||
),
|
||||
|
||||
// Accept invite (unauthenticated)
|
||||
accept: (token: string, full_name: string, password: string) =>
|
||||
// Accept invite (unauthenticated) — password/name only needed for new accounts
|
||||
accept: (token: string, full_name?: string, password?: string) =>
|
||||
request<LoginResponse>(
|
||||
`/invites/${token}/accept`,
|
||||
{
|
||||
@@ -979,6 +1046,10 @@ export const api = {
|
||||
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),
|
||||
@@ -1064,6 +1135,40 @@ export interface Department {
|
||||
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;
|
||||
@@ -1097,6 +1202,7 @@ export interface OrgInvite {
|
||||
email: string;
|
||||
role: string;
|
||||
expires_at: string;
|
||||
invite_link?: string; // only present on create response (dev/when email disabled)
|
||||
}
|
||||
|
||||
export interface OIDCClient {
|
||||
|
||||
@@ -8,6 +8,11 @@ import {
|
||||
Loader2,
|
||||
Plus,
|
||||
ChevronRight,
|
||||
ShieldCheck,
|
||||
Shield,
|
||||
Ban,
|
||||
UserCheck,
|
||||
AlertTriangle,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
@@ -36,16 +41,48 @@ import {
|
||||
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 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[]>([]);
|
||||
@@ -55,6 +92,7 @@ export default function AdminUsersPage() {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [search, setSearch] = useState("");
|
||||
const [debouncedSearch, setDebouncedSearch] = useState("");
|
||||
const [roleFilter, setRoleFilter] = useState("all");
|
||||
|
||||
// Debounce search
|
||||
useEffect(() => {
|
||||
@@ -67,6 +105,9 @@ export default function AdminUsersPage() {
|
||||
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("");
|
||||
@@ -74,6 +115,10 @@ export default function AdminUsersPage() {
|
||||
const [isAddingKey, setIsAddingKey] = useState(false);
|
||||
const [addKeyError, setAddKeyError] = useState<string | null>(null);
|
||||
|
||||
// Suspend / unsuspend
|
||||
const [isSuspending, setIsSuspending] = useState(false);
|
||||
const [showSuspendConfirm, setShowSuspendConfirm] = useState(false);
|
||||
|
||||
// ── Fetch users ─────────────────────────────────────────────────────────────
|
||||
const fetchUsers = useCallback(async (q: string, pg: number) => {
|
||||
setIsLoading(true);
|
||||
@@ -123,6 +168,32 @@ export default function AdminUsersPage() {
|
||||
}
|
||||
};
|
||||
|
||||
// ── 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;
|
||||
@@ -146,6 +217,47 @@ export default function AdminUsersPage() {
|
||||
}
|
||||
};
|
||||
|
||||
// ── 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) {
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
// 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">
|
||||
@@ -156,8 +268,9 @@ export default function AdminUsersPage() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Search bar */}
|
||||
<div className="relative mb-4">
|
||||
{/* 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"
|
||||
@@ -166,6 +279,18 @@ export default function AdminUsersPage() {
|
||||
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>
|
||||
@@ -174,21 +299,21 @@ export default function AdminUsersPage() {
|
||||
Users
|
||||
{!isLoading && <Badge variant="secondary" className="ml-1">{total}</Badge>}
|
||||
</CardTitle>
|
||||
<CardDescription>Click a user to view details and manage their SSH keys</CardDescription>
|
||||
<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>
|
||||
) : users.length === 0 ? (
|
||||
) : 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">
|
||||
{users.map((user) => (
|
||||
{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"
|
||||
@@ -204,7 +329,13 @@ export default function AdminUsersPage() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 flex-shrink-0">
|
||||
{(user as ApiUser & { activated?: boolean }).activated === false && (
|
||||
<RoleBadge role={user.org_role || "member"} />
|
||||
{user.status === "suspended" && (
|
||||
<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>
|
||||
@@ -261,19 +392,98 @@ export default function AdminUsersPage() {
|
||||
{/* 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">
|
||||
{selectedUser.status === "suspended" ? (
|
||||
<><Ban className="w-4 h-4 text-red-500" /><span className="text-red-600 font-medium">Suspended</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 as ApiUser & { activated?: boolean }).activated === false ? (
|
||||
{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>
|
||||
{selectedUser.status === "suspended" ? (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-muted-foreground">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">
|
||||
@@ -371,6 +581,34 @@ export default function AdminUsersPage() {
|
||||
</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>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ 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 } from "@/lib/api";
|
||||
|
||||
export default function ForgotPasswordPage() {
|
||||
const [email, setEmail] = useState("");
|
||||
@@ -15,11 +16,14 @@ export default function ForgotPasswordPage() {
|
||||
e.preventDefault();
|
||||
setIsLoading(true);
|
||||
|
||||
// Mock API call - POST /api/auth/forgot-password
|
||||
setTimeout(() => {
|
||||
try {
|
||||
await api.auth.forgotPassword(email);
|
||||
} catch {
|
||||
// Always show success to avoid leaking account existence
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
setIsSubmitted(true);
|
||||
}, 1000);
|
||||
}
|
||||
};
|
||||
|
||||
// Success state - always show neutral message (don't leak account existence)
|
||||
|
||||
@@ -1,36 +1,106 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { User, Lock, Upload, ArrowRight, Building2 } from "lucide-react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useNavigate, useSearchParams, Link } from "react-router-dom";
|
||||
import { User, Lock, ArrowRight, Building2, Loader2, AlertCircle, CheckCircle } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
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() {
|
||||
const navigate = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
const token = searchParams.get("token") || "";
|
||||
const { login } = useAuth();
|
||||
|
||||
const [name, setName] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
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
|
||||
const inviteData = {
|
||||
email: "invited@example.com",
|
||||
organization: "Acme Corp",
|
||||
};
|
||||
useEffect(() => {
|
||||
if (!token) {
|
||||
setTokenError("No invite token found in the URL.");
|
||||
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) => {
|
||||
e.preventDefault();
|
||||
setSubmitError("");
|
||||
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);
|
||||
setTimeout(() => {
|
||||
setIsLoading(false);
|
||||
try {
|
||||
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");
|
||||
}, 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 (
|
||||
<div className="auth-card">
|
||||
<div className="text-center mb-8">
|
||||
@@ -41,36 +111,27 @@ export default function InviteAcceptPage() {
|
||||
You're invited!
|
||||
</h1>
|
||||
<p className="text-muted-foreground mt-2">
|
||||
<span className="font-medium text-foreground">{inviteData.organization}</span> has
|
||||
invited you to join their organization
|
||||
<span className="font-medium text-foreground">{inviteData?.organization.name}</span> has
|
||||
invited you to join as <span className="font-medium text-foreground capitalize">{inviteData?.role}</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{/* Avatar upload */}
|
||||
<div className="flex flex-col items-center mb-6">
|
||||
<Avatar className="w-20 h-20 mb-3">
|
||||
<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 className="space-y-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={inviteData.email}
|
||||
disabled
|
||||
className="bg-muted"
|
||||
/>
|
||||
<Label>Email</Label>
|
||||
<Input type="email" value={inviteData?.email ?? ""} disabled className="bg-muted" />
|
||||
</div>
|
||||
|
||||
{isExistingUser ? (
|
||||
<div className="rounded-lg bg-accent/10 border border-accent/20 p-4 flex items-start gap-3">
|
||||
<CheckCircle className="w-5 h-5 text-accent flex-shrink-0 mt-0.5" />
|
||||
<div className="text-sm">
|
||||
<p className="font-medium text-foreground">Account found</p>
|
||||
<p className="text-muted-foreground">You already have a Gatehouse account. Click below to join the organization.</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">Full name</Label>
|
||||
<div className="relative">
|
||||
@@ -86,7 +147,6 @@ export default function InviteAcceptPage() {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<div className="relative">
|
||||
@@ -103,7 +163,6 @@ export default function InviteAcceptPage() {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirmPassword">Confirm password</Label>
|
||||
<div className="relative">
|
||||
@@ -119,17 +178,35 @@ export default function InviteAcceptPage() {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{submitError && (
|
||||
<p className="text-sm text-destructive flex items-center gap-2">
|
||||
<AlertCircle className="w-4 h-4 flex-shrink-0" />
|
||||
{submitError}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Button type="submit" className="w-full" disabled={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" />
|
||||
</>
|
||||
)}
|
||||
</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>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -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 { 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 { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
@@ -49,7 +49,7 @@ async function completeOidcFlow(oidcSessionId: string, token: string): Promise<s
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
const { login, verifyTotp, refreshUser } = useAuth();
|
||||
const { login, verifyTotp, refreshUser, user, isLoading: authLoading } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const { toast } = useToast();
|
||||
const [searchParams] = useSearchParams();
|
||||
@@ -69,6 +69,46 @@ export default function LoginPage() {
|
||||
const oidcSessionId = searchParams.get('oidc_session_id');
|
||||
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) => {
|
||||
if (!oidcSessionId) return false;
|
||||
try {
|
||||
@@ -110,8 +150,12 @@ export default function LoginPage() {
|
||||
e.preventDefault();
|
||||
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 {
|
||||
const result = await login(email, password, rememberMe);
|
||||
const result = await login(email, password, rememberMe, needsCustomNav);
|
||||
if (result.requiresWebAuthn) {
|
||||
setStep('webauthn');
|
||||
} else if (result.requiresTotp) {
|
||||
@@ -119,13 +163,17 @@ export default function LoginPage() {
|
||||
setTotpCode("");
|
||||
} else if (result.requiresMfaEnrollment) {
|
||||
// MFA enrollment required - will be handled by ProtectedLayout
|
||||
// Navigation happens in AuthContext
|
||||
// Navigation happens in AuthContext (MFA path always navigates)
|
||||
} else if (oidcSessionId) {
|
||||
// OIDC bridge: send token back to the Gatehouse backend to complete the flow
|
||||
const token = tokenManager.getToken();
|
||||
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) {
|
||||
if (import.meta.env.DEV) {
|
||||
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
|
||||
if (oidcSessionId && response.token) {
|
||||
await finishOidcFlow(response.token);
|
||||
} else if (cliRedirectUrl && response.token) {
|
||||
finishCliFlow(response.token);
|
||||
} else {
|
||||
await refreshUser();
|
||||
navigate('/profile');
|
||||
}
|
||||
} else {
|
||||
// Fallback to regular TOTP verification
|
||||
await verifyTotp(totpCode, useBackupCode);
|
||||
const needsCustomNav = !!(cliRedirectUrl || oidcSessionId);
|
||||
await verifyTotp(totpCode, useBackupCode, needsCustomNav);
|
||||
if (oidcSessionId) {
|
||||
const token = tokenManager.getToken();
|
||||
if (token) await finishOidcFlow(token);
|
||||
} else if (cliRedirectUrl) {
|
||||
const token = tokenManager.getToken();
|
||||
if (token) finishCliFlow(token);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -227,13 +281,17 @@ export default function LoginPage() {
|
||||
setIsLoading(true);
|
||||
|
||||
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
|
||||
if (oidcSessionId) {
|
||||
const token = tokenManager.getToken();
|
||||
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) {
|
||||
if (import.meta.env.DEV) {
|
||||
console.error("[Gatehouse] TOTP verification failed:", error);
|
||||
@@ -292,6 +350,9 @@ export default function LoginPage() {
|
||||
if (oidcSessionId) {
|
||||
const token = tokenManager.getToken();
|
||||
if (token) await finishOidcFlow(token);
|
||||
} else if (cliRedirectUrl) {
|
||||
const token = tokenManager.getToken();
|
||||
if (token) finishCliFlow(token);
|
||||
} else {
|
||||
navigate('/profile');
|
||||
}
|
||||
@@ -364,6 +425,9 @@ export default function LoginPage() {
|
||||
if (oidcSessionId) {
|
||||
const token = tokenManager.getToken();
|
||||
if (token) await finishOidcFlow(token);
|
||||
} else if (cliRedirectUrl) {
|
||||
const token = tokenManager.getToken();
|
||||
if (token) finishCliFlow(token);
|
||||
} else {
|
||||
await refreshUser();
|
||||
navigate('/profile');
|
||||
@@ -444,6 +508,11 @@ export default function LoginPage() {
|
||||
...(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
|
||||
window.location.href = response.authorization_url;
|
||||
|
||||
@@ -860,11 +929,18 @@ export default function LoginPage() {
|
||||
return (
|
||||
<div className="auth-card">
|
||||
<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">
|
||||
{oidcSessionId ? "Sign in to continue" : "Welcome back"}
|
||||
{cliRedirectUrl ? "Authorize CLI access" : oidcSessionId ? "Sign in to continue" : "Welcome back"}
|
||||
</h1>
|
||||
<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"
|
||||
: "Sign in to your account to continue"}
|
||||
</p>
|
||||
|
||||
@@ -97,6 +97,15 @@ export default function OAuthCallbackPage() {
|
||||
tokenManager.setToken(token, expiresAt);
|
||||
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 ──
|
||||
if (oidcSessionId) {
|
||||
try {
|
||||
|
||||
@@ -1,39 +1,122 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { CheckCircle, XCircle, Shield, User, Mail, Building2 } from "lucide-react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useNavigate, useSearchParams } from "react-router-dom";
|
||||
import { CheckCircle, XCircle, Shield, User, Mail, Building2, Loader2, Key } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
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() {
|
||||
const navigate = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
const oidcSessionId = searchParams.get("oidc_session_id");
|
||||
|
||||
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
|
||||
const clientData = {
|
||||
name: "GitLab",
|
||||
logo: null,
|
||||
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" },
|
||||
],
|
||||
};
|
||||
useEffect(() => {
|
||||
if (!oidcSessionId) {
|
||||
setFetchError("No OIDC session provided.");
|
||||
return;
|
||||
}
|
||||
|
||||
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);
|
||||
// Mock consent - will redirect to client callback
|
||||
setTimeout(() => {
|
||||
try {
|
||||
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);
|
||||
// In real implementation: redirect to redirectUri with auth code
|
||||
}, 500);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeny = () => {
|
||||
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 (
|
||||
<div className="auth-card">
|
||||
<div className="text-center mb-6">
|
||||
@@ -41,7 +124,7 @@ export default function OIDCConsentPage() {
|
||||
<Shield className="w-7 h-7 text-primary" />
|
||||
</div>
|
||||
<h1 className="text-xl font-semibold text-foreground tracking-tight">
|
||||
Authorize {clientData.name}
|
||||
Authorize {context.client_name}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground mt-2">
|
||||
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">
|
||||
<p className="text-sm text-foreground font-medium mb-3">
|
||||
{clientData.name} is requesting access to:
|
||||
{context.client_name} is requesting access to:
|
||||
</p>
|
||||
<ul className="space-y-3">
|
||||
{clientData.scopes.map((scope) => (
|
||||
<li key={scope.id} className="flex items-start gap-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">
|
||||
{scope.id === "openid" && <Shield className="w-4 h-4 text-accent" />}
|
||||
{scope.id === "profile" && <User className="w-4 h-4 text-accent" />}
|
||||
{scope.id === "email" && <Mail className="w-4 h-4 text-accent" />}
|
||||
<Icon className="w-4 h-4 text-accent" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-foreground">{scope.name}</p>
|
||||
<p className="text-xs text-muted-foreground">{scope.description}</p>
|
||||
<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>
|
||||
|
||||
{context.redirect_uri && (
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground mb-6">
|
||||
<Building2 className="w-4 h-4" />
|
||||
<span>
|
||||
Redirecting to: <span className="font-mono text-foreground">{clientData.redirectUri}</span>
|
||||
Redirecting to:{" "}
|
||||
<span className="font-mono text-foreground">
|
||||
{new URL(context.redirect_uri).origin}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Separator className="mb-6" />
|
||||
|
||||
@@ -93,8 +187,12 @@ export default function OIDCConsentPage() {
|
||||
className="flex-1"
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<CheckCircle className="w-4 h-4 mr-2" />
|
||||
{isLoading ? "Authorizing..." : "Allow"}
|
||||
)}
|
||||
{isLoading ? "Authorizing…" : "Allow"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,14 +1,26 @@
|
||||
import { AlertTriangle, ArrowLeft, Home } from "lucide-react";
|
||||
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() {
|
||||
// Mock error data - will be parsed from URL params
|
||||
const errorData = {
|
||||
error: "invalid_request",
|
||||
description: "The request was missing a required parameter or was otherwise malformed.",
|
||||
clientName: "Unknown Application",
|
||||
};
|
||||
const [searchParams] = useSearchParams();
|
||||
|
||||
const error = searchParams.get("error") || "server_error";
|
||||
const errorDescription =
|
||||
searchParams.get("error_description") ||
|
||||
ERROR_DESCRIPTIONS[error] ||
|
||||
"An unexpected error occurred during authentication.";
|
||||
const clientName = searchParams.get("client") || "the application";
|
||||
|
||||
return (
|
||||
<div className="auth-card text-center">
|
||||
@@ -20,15 +32,16 @@ export default function OIDCErrorPage() {
|
||||
Authentication Error
|
||||
</h1>
|
||||
<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>
|
||||
|
||||
<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">
|
||||
Error: <code className="text-destructive">{errorData.error}</code>
|
||||
Error: <code className="text-destructive">{error}</code>
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{errorData.description}
|
||||
{decodeURIComponent(errorDescription)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import { useState } from "react";
|
||||
import { Link, useNavigate } from "react-router-dom";
|
||||
import { Link } from "react-router-dom";
|
||||
import { Mail, Lock, User, ArrowRight, ArrowLeft } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { PasswordStrengthMeter, isPasswordValid } from "@/components/auth/PasswordStrengthMeter";
|
||||
import { BannerAlert } from "@/components/auth/BannerAlert";
|
||||
import { api, ApiError } from "@/lib/api";
|
||||
|
||||
type RegistrationState = "form" | "success" | "disabled";
|
||||
|
||||
export default function RegisterPage() {
|
||||
const navigate = useNavigate();
|
||||
const [name, setName] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
@@ -42,22 +42,25 @@ export default function RegisterPage() {
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
// Mock registration - will be replaced with actual API call
|
||||
// POST /api/auth/register
|
||||
setTimeout(() => {
|
||||
setIsLoading(false);
|
||||
|
||||
// Simulate different responses
|
||||
const mockResponse = "success" as RegistrationState | "error";
|
||||
|
||||
if (mockResponse === "disabled") {
|
||||
setState("disabled");
|
||||
} else if (mockResponse === "error") {
|
||||
setError("An error occurred. Please try again.");
|
||||
} else {
|
||||
try {
|
||||
await api.auth.register(email, password, name.trim() || undefined);
|
||||
// Show "check your email" — verification email was sent
|
||||
setState("success");
|
||||
} 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);
|
||||
}
|
||||
}, 1000);
|
||||
};
|
||||
|
||||
// Registration disabled state
|
||||
|
||||
@@ -1,27 +1,43 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { Lock, ArrowRight, CheckCircle } from "lucide-react";
|
||||
import { useNavigate, useSearchParams } from "react-router-dom";
|
||||
import { Lock, ArrowRight, CheckCircle, AlertCircle, Loader2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
export default function ResetPasswordPage() {
|
||||
const navigate = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
const token = searchParams.get("token") || "";
|
||||
|
||||
const [password, setPassword] = useState("");
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isSuccess, setIsSuccess] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
if (password !== confirmPassword) {
|
||||
setError("Passwords do not match.");
|
||||
return;
|
||||
}
|
||||
if (!token) {
|
||||
setError("Invalid reset link. Please request a new one.");
|
||||
return;
|
||||
}
|
||||
setIsLoading(true);
|
||||
setTimeout(() => {
|
||||
setIsLoading(false);
|
||||
try {
|
||||
await api.auth.resetPassword(token, password);
|
||||
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) {
|
||||
@@ -96,7 +112,7 @@ export default function ResetPasswordPage() {
|
||||
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading ? (
|
||||
"Resetting..."
|
||||
<><Loader2 className="w-4 h-4 mr-2 animate-spin" />Resetting...</>
|
||||
) : (
|
||||
<>
|
||||
Reset password
|
||||
@@ -104,6 +120,13 @@ export default function ResetPasswordPage() {
|
||||
</>
|
||||
)}
|
||||
</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>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -5,6 +5,7 @@ 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 } from "@/lib/api";
|
||||
|
||||
type VerificationState = "verifying" | "success" | "error" | "resend";
|
||||
|
||||
@@ -22,21 +23,20 @@ export default function VerifyEmailPage() {
|
||||
if (token && state === "verifying") {
|
||||
verifyToken(token);
|
||||
}
|
||||
}, [token, state]);
|
||||
}, [token]);
|
||||
|
||||
const verifyToken = async (verificationToken: string) => {
|
||||
// Mock verification - POST /api/auth/verify-email?token=...
|
||||
setTimeout(() => {
|
||||
// Simulate different responses
|
||||
const mockSuccess = Math.random() > 0.3; // 70% success rate for demo
|
||||
|
||||
if (mockSuccess) {
|
||||
try {
|
||||
await api.auth.verifyEmail(verificationToken);
|
||||
setState("success");
|
||||
} else {
|
||||
} catch (err) {
|
||||
setState("error");
|
||||
if (err instanceof ApiError) {
|
||||
setErrorMessage(err.message || "This verification link has expired or is invalid.");
|
||||
} else {
|
||||
setErrorMessage("This verification link has expired or is invalid.");
|
||||
}
|
||||
}, 1500);
|
||||
}
|
||||
};
|
||||
|
||||
const handleResendVerification = async (e: React.FormEvent) => {
|
||||
@@ -44,11 +44,14 @@ export default function VerifyEmailPage() {
|
||||
setIsResending(true);
|
||||
setResendSuccess(false);
|
||||
|
||||
// Mock resend - POST /api/auth/request-email-verification
|
||||
setTimeout(() => {
|
||||
try {
|
||||
await api.auth.resendVerification(resendEmail);
|
||||
} catch {
|
||||
// Always show success to avoid leaking account existence
|
||||
} finally {
|
||||
setIsResending(false);
|
||||
setResendSuccess(true);
|
||||
}, 1000);
|
||||
}
|
||||
};
|
||||
|
||||
// Loading / Verifying state
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import { useState, useEffect } from "react";
|
||||
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 { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
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 { useOrganizations } from "@/hooks/useOrganizations";
|
||||
|
||||
const STATUS_CONFIG: Record<string, { label: string; color: string; icon: typeof Clock }> = {
|
||||
compliant: {
|
||||
@@ -51,18 +52,13 @@ export default function CompliancePage() {
|
||||
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),
|
||||
}),
|
||||
});
|
||||
const { data: organizations, isLoading: orgsLoading } = useOrganizations();
|
||||
|
||||
useEffect(() => {
|
||||
if (orgsData?.organizations && orgsData.organizations.length > 0) {
|
||||
setCurrentOrgId(orgsData.organizations[0].id);
|
||||
if (organizations && organizations.length > 0) {
|
||||
setCurrentOrgId(organizations[0].id);
|
||||
}
|
||||
}, [orgsData]);
|
||||
}, [organizations]);
|
||||
|
||||
// Fetch compliance data
|
||||
const { data: complianceData, isLoading: complianceLoading } = useQuery({
|
||||
@@ -73,6 +69,18 @@ export default function CompliancePage() {
|
||||
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
|
||||
const filteredMembers = complianceData?.members?.filter((member) => {
|
||||
const matchesSearch =
|
||||
@@ -256,10 +264,8 @@ export default function CompliancePage() {
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
title="Send Reminder"
|
||||
onClick={() => {
|
||||
// TODO: Implement send reminder
|
||||
console.log('Send reminder to', member.user_id);
|
||||
}}
|
||||
disabled={isSendingReminder && reminderVars?.userId === member.user_id}
|
||||
onClick={() => sendReminder({ userId: member.user_id })}
|
||||
>
|
||||
<Mail className="w-4 h-4" />
|
||||
</Button>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { Search, Plus, MoreHorizontal, Users, Loader2, Trash2, Edit2, X } from "lucide-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";
|
||||
@@ -21,10 +21,348 @@ import {
|
||||
} from "@/components/ui/dialog";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { api, Department, Principal } from "@/lib/api";
|
||||
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) => (
|
||||
<option key={m.user_id} value={m.user_id}>
|
||||
{m.user?.full_name || m.user?.email || m.user_id}
|
||||
</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();
|
||||
@@ -33,14 +371,37 @@ export default function DepartmentsPage() {
|
||||
|
||||
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;
|
||||
@@ -61,9 +422,13 @@ export default function DepartmentsPage() {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
const response = await api.organizations.getDepartments(currentOrgId);
|
||||
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);
|
||||
@@ -76,6 +441,7 @@ export default function DepartmentsPage() {
|
||||
useEffect(() => {
|
||||
setError(null);
|
||||
setDepartments([]);
|
||||
setPrincipals([]);
|
||||
setLinkedPrincipals({});
|
||||
if (!orgId) {
|
||||
setIsLoading(false);
|
||||
@@ -103,6 +469,29 @@ export default function DepartmentsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
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 {
|
||||
@@ -162,6 +551,11 @@ export default function DepartmentsPage() {
|
||||
);
|
||||
});
|
||||
|
||||
// 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">
|
||||
@@ -260,6 +654,36 @@ export default function DepartmentsPage() {
|
||||
<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>
|
||||
@@ -272,6 +696,10 @@ export default function DepartmentsPage() {
|
||||
<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"
|
||||
@@ -371,6 +799,57 @@ export default function DepartmentsPage() {
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
+323
-31
@@ -1,8 +1,9 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Search, Plus, MoreHorizontal, Shield, User, Mail, Clock, Loader2 } from "lucide-react";
|
||||
import { Search, Shield, ShieldCheck, Mail, Loader2, Copy, Check, ExternalLink } from "lucide-react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
@@ -13,9 +14,27 @@ import {
|
||||
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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { api, OrganizationMember } from "@/lib/api";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { api, OrganizationMember, ApiError, OrgInvite } from "@/lib/api";
|
||||
import { useCurrentOrganizationId } from "@/hooks/useCurrentOrganization";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import { MoreHorizontal } from "lucide-react";
|
||||
|
||||
const getInitials = (name: string | null | undefined): string => {
|
||||
if (!name) return "?";
|
||||
@@ -27,16 +46,63 @@ const getInitials = (name: string | null | undefined): string => {
|
||||
.slice(0, 2);
|
||||
};
|
||||
|
||||
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 MembersPage() {
|
||||
const params = useParams<{ orgId?: string }>();
|
||||
const { orgId: fallbackOrgId } = useCurrentOrganizationId();
|
||||
const orgId = params.orgId || fallbackOrgId;
|
||||
const { toast } = useToast();
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const [search, setSearch] = useState("");
|
||||
const [members, setMembers] = useState<OrganizationMember[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Invite dialog
|
||||
const [showInvite, setShowInvite] = useState(false);
|
||||
const [inviteEmail, setInviteEmail] = useState("");
|
||||
const [inviteRole, setInviteRole] = useState("member");
|
||||
const [isInviting, setIsInviting] = useState(false);
|
||||
const [inviteError, setInviteError] = useState<string | null>(null);
|
||||
|
||||
// Invite link dialog (shown when email is not configured)
|
||||
const [inviteLink, setInviteLink] = useState<string | null>(null);
|
||||
const [inviteLinkEmail, setInviteLinkEmail] = useState("");
|
||||
const [linkCopied, setLinkCopied] = useState(false);
|
||||
|
||||
// Change role dialog
|
||||
const [changeRoleMember, setChangeRoleMember] = useState<OrganizationMember | null>(null);
|
||||
const [newRole, setNewRole] = useState("member");
|
||||
const [isChangingRole, setIsChangingRole] = useState(false);
|
||||
|
||||
// Pending invites
|
||||
const [invites, setInvites] = useState<OrgInvite[]>([]);
|
||||
const [isInvitesLoading, setIsInvitesLoading] = useState(false);
|
||||
const [cancellingInviteId, setCancellingInviteId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setError(null);
|
||||
setMembers([]);
|
||||
@@ -59,7 +125,20 @@ export default function MembersPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const fetchInvites = async () => {
|
||||
try {
|
||||
setIsInvitesLoading(true);
|
||||
const res = await api.organizations.getInvites(orgId);
|
||||
setInvites(res.invites || []);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch invites:", err);
|
||||
} finally {
|
||||
setIsInvitesLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchMembers();
|
||||
fetchInvites();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [orgId]);
|
||||
|
||||
@@ -71,20 +150,88 @@ export default function MembersPage() {
|
||||
);
|
||||
});
|
||||
|
||||
const handleInvite = async () => {
|
||||
if (!orgId) return;
|
||||
setInviteError(null);
|
||||
if (!inviteEmail.trim()) {
|
||||
setInviteError("Email is required.");
|
||||
return;
|
||||
}
|
||||
setIsInviting(true);
|
||||
try {
|
||||
const res = await api.organizations.createInvite(orgId, inviteEmail.trim(), inviteRole);
|
||||
const link = res.invite?.invite_link;
|
||||
setShowInvite(false);
|
||||
// Refresh invites list
|
||||
const updated = await api.organizations.getInvites(orgId);
|
||||
setInvites(updated.invites || []);
|
||||
if (link) {
|
||||
// Email delivery not configured — show copyable link as fallback
|
||||
setInviteLink(link);
|
||||
setInviteLinkEmail(inviteEmail.trim());
|
||||
} else {
|
||||
// Email was sent successfully
|
||||
toast({ title: "Invitation sent", description: `Invite email sent to ${inviteEmail.trim()}.` });
|
||||
}
|
||||
setInviteEmail("");
|
||||
setInviteRole("member");
|
||||
} catch (err) {
|
||||
setInviteError(err instanceof ApiError ? err.message : "Failed to send invitation.");
|
||||
} finally {
|
||||
setIsInviting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleChangeRole = async () => {
|
||||
if (!orgId || !changeRoleMember) return;
|
||||
setIsChangingRole(true);
|
||||
try {
|
||||
const updated = await api.organizations.updateMemberRole(orgId, changeRoleMember.user_id, newRole.toUpperCase());
|
||||
setMembers((prev) =>
|
||||
prev.map((m) => (m.id === changeRoleMember.id ? { ...m, role: updated.member.role } : m))
|
||||
);
|
||||
toast({
|
||||
title: "Role updated",
|
||||
description: `${changeRoleMember.user?.full_name || changeRoleMember.user?.email} is now a ${newRole}.`,
|
||||
});
|
||||
setChangeRoleMember(null);
|
||||
} catch (err) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Failed to update role",
|
||||
description: err instanceof ApiError ? err.message : "Something went wrong.",
|
||||
});
|
||||
} finally {
|
||||
setIsChangingRole(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveMember = async (member: OrganizationMember) => {
|
||||
if (!orgId) return;
|
||||
try {
|
||||
await api.organizations.removeMember(orgId, member.user_id);
|
||||
setMembers((prev) => prev.filter((m) => m.id !== member.id));
|
||||
toast({
|
||||
title: "Member removed",
|
||||
description: `${member.user?.full_name || member.user?.email} has been removed.`,
|
||||
});
|
||||
} catch (err) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Failed to remove member",
|
||||
description: err instanceof ApiError ? err.message : "Something went wrong.",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="page-container">
|
||||
<div className="page-header flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||
<div>
|
||||
<div className="page-header">
|
||||
<h1 className="page-title">Members</h1>
|
||||
<p className="page-description">
|
||||
Manage organization members and invitations
|
||||
</p>
|
||||
</div>
|
||||
<Button>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Invite member
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="members" className="w-full">
|
||||
<TabsList className="mb-4">
|
||||
@@ -92,7 +239,7 @@ export default function MembersPage() {
|
||||
Members ({members.length})
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="invites">
|
||||
Pending Invites (0)
|
||||
Invitations {invites.length > 0 && <span className="ml-1.5 inline-flex items-center justify-center w-4 h-4 rounded-full bg-primary text-primary-foreground text-[10px] font-bold">{invites.length}</span>}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
@@ -139,23 +286,14 @@ export default function MembersPage() {
|
||||
<p className="font-medium text-foreground truncate">
|
||||
{member.user?.full_name || member.user?.email}
|
||||
</p>
|
||||
{member.role === "admin" && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
<Shield className="w-3 h-3 mr-1" />
|
||||
Admin
|
||||
</Badge>
|
||||
)}
|
||||
{member.role === "owner" && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
<Shield className="w-3 h-3 mr-1" />
|
||||
Owner
|
||||
</Badge>
|
||||
)}
|
||||
<RoleBadge role={member.role} />
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground truncate">
|
||||
{member.user?.email}
|
||||
</p>
|
||||
</div>
|
||||
{/* Actions — hide for self and for owners (can't modify owner here) */}
|
||||
{member.user?.id !== currentUser?.id && (member.role || "").toLowerCase() !== "owner" && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
@@ -163,20 +301,25 @@ export default function MembersPage() {
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem>
|
||||
<User className="w-4 h-4 mr-2" />
|
||||
View profile
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setChangeRoleMember(member);
|
||||
setNewRole((member.role || "member").toLowerCase());
|
||||
}}
|
||||
>
|
||||
<Shield className="w-4 h-4 mr-2" />
|
||||
Change role
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="text-destructive">
|
||||
<DropdownMenuItem
|
||||
className="text-destructive"
|
||||
onClick={() => handleRemoveMember(member)}
|
||||
>
|
||||
Remove member
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -186,15 +329,164 @@ export default function MembersPage() {
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="invites">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<div className="p-8 text-center text-muted-foreground">
|
||||
No pending invitations
|
||||
<CardContent>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h3 className="text-sm font-semibold">Pending invitations</h3>
|
||||
<span className="text-sm text-muted-foreground">{isInvitesLoading ? 'Loading...' : `${invites.length}`}</span>
|
||||
</div>
|
||||
{isInvitesLoading ? (
|
||||
<div className="p-4 text-center text-muted-foreground">Loading invites...</div>
|
||||
) : invites.length === 0 ? (
|
||||
<div className="p-4 text-center text-muted-foreground">No pending invitations</div>
|
||||
) : (
|
||||
<div className="divide-y">
|
||||
{invites.map((inv) => (
|
||||
<div key={inv.id} className="py-3 flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="font-medium">{inv.email}</div>
|
||||
<div className="text-sm text-muted-foreground">Role: {inv.role} • Expires: {new Date(inv.expires_at).toLocaleString()}</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button size="sm" variant="ghost" onClick={() => { void (async () => {
|
||||
if (!orgId) return;
|
||||
setCancellingInviteId(inv.id);
|
||||
try {
|
||||
await api.organizations.cancelInvite(orgId, inv.id);
|
||||
setInvites((prev) => prev.filter((i) => i.id !== inv.id));
|
||||
toast({ title: 'Invite cancelled' });
|
||||
} catch (err) {
|
||||
toast({ variant: 'destructive', title: 'Failed to cancel invite' });
|
||||
} finally {
|
||||
setCancellingInviteId(null);
|
||||
}
|
||||
})() }}>
|
||||
{cancellingInviteId === inv.id ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Cancel'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-6 space-y-4">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Mail className="w-4 h-4 text-muted-foreground" />
|
||||
<h3 className="text-sm font-semibold">Send an invitation</h3>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Label>Email address</Label>
|
||||
<Input
|
||||
type="email"
|
||||
placeholder="colleague@example.com"
|
||||
value={inviteEmail}
|
||||
onChange={(e) => setInviteEmail(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Role</Label>
|
||||
<Select value={inviteRole} onValueChange={setInviteRole}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="member">Member</SelectItem>
|
||||
<SelectItem value="admin">Admin</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{inviteError && (
|
||||
<p className="text-sm text-destructive">{inviteError}</p>
|
||||
)}
|
||||
<Button onClick={handleInvite} disabled={isInviting || !inviteEmail.trim()} className="w-full">
|
||||
{isInviting && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
<Mail className="w-4 h-4 mr-2" />
|
||||
Send invitation
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
{/* ── Invite link dialog (shown when SMTP not configured) ────────────────── */}
|
||||
<Dialog open={!!inviteLink} onOpenChange={(o) => { if (!o) { setInviteLink(null); setLinkCopied(false); } }}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
Share this invite link
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Email delivery is not configured. Share this link directly with <strong>{inviteLinkEmail}</strong>.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-3 py-2">
|
||||
<div className="flex items-center gap-2 rounded-md border bg-muted px-3 py-2">
|
||||
<span className="flex-1 text-xs text-muted-foreground break-all font-mono">{inviteLink}</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="shrink-0"
|
||||
onClick={() => {
|
||||
if (inviteLink) {
|
||||
navigator.clipboard.writeText(inviteLink);
|
||||
setLinkCopied(true);
|
||||
setTimeout(() => setLinkCopied(false), 2000);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{linkCopied ? <Check className="w-4 h-4 text-green-500" /> : <Copy className="w-4 h-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This link expires in 7 days. The recipient must already have an account or will be prompted to create one.
|
||||
</p>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button onClick={() => { setInviteLink(null); setLinkCopied(false); }}>Done</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* ── Change role dialog ─────────────────────────────────────────────────── */}
|
||||
<Dialog open={!!changeRoleMember} onOpenChange={(o) => { if (!o) setChangeRoleMember(null); }}>
|
||||
<DialogContent className="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Change role</DialogTitle>
|
||||
<DialogDescription>
|
||||
Update the role for {changeRoleMember?.user?.full_name || changeRoleMember?.user?.email}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="py-2">
|
||||
<Label className="mb-2 block">New role</Label>
|
||||
<Select value={newRole} onValueChange={setNewRole} disabled={isChangingRole}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="member">Member</SelectItem>
|
||||
<SelectItem value="admin">Admin</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setChangeRoleMember(null)} disabled={isChangingRole}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleChangeRole} disabled={isChangingRole}>
|
||||
{isChangingRole && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { LogIn, LogOut, Key, Fingerprint, Smartphone, AlertTriangle, Loader2, RefreshCw } from "lucide-react";
|
||||
import { LogIn, LogOut, Key, Fingerprint, Smartphone, AlertTriangle, Loader2, RefreshCw, Users } from "lucide-react";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
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";
|
||||
|
||||
// Map audit log action strings to display info
|
||||
const getEventDisplay = (action: string) => {
|
||||
@@ -31,7 +33,9 @@ const getEventDisplay = (action: string) => {
|
||||
};
|
||||
|
||||
export default function ActivityPage() {
|
||||
const { isOrgAdmin } = useAuth();
|
||||
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("");
|
||||
@@ -39,15 +43,18 @@ export default function ActivityPage() {
|
||||
const loadEvents = () => {
|
||||
setIsLoading(true);
|
||||
setError("");
|
||||
api.users.auditLogs({ per_page: "50" })
|
||||
.then((data) => {
|
||||
setEvents(data.audit_logs ?? []);
|
||||
})
|
||||
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(); }, []);
|
||||
useEffect(() => { loadEvents(); }, [view]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
const date = new Date(dateString);
|
||||
@@ -75,12 +82,23 @@ export default function ActivityPage() {
|
||||
<div>
|
||||
<h1 className="page-title">Activity</h1>
|
||||
<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>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{isOrgAdmin && (
|
||||
<Tabs value={view} onValueChange={(v) => setView(v as "mine" | "org")}>
|
||||
<TabsList>
|
||||
<TabsTrigger value="mine">My Activity</TabsTrigger>
|
||||
<TabsTrigger value="org">
|
||||
<Users className="w-3.5 h-3.5 mr-1" />
|
||||
Org Logs
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
)}
|
||||
<Select value={filter} onValueChange={setFilter}>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectTrigger className="w-[160px]">
|
||||
<SelectValue placeholder="Filter events" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -137,6 +155,9 @@ export default function ActivityPage() {
|
||||
)}
|
||||
</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 && (
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Mail, Building2, Upload, CheckCircle, AlertCircle, Loader2 } from "lucide-react";
|
||||
import { Mail, Upload, CheckCircle, AlertCircle, Loader2, Bell } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
@@ -8,8 +8,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import { api, Organization, ApiError } from "@/lib/api";
|
||||
import { useOrganizations } from "@/hooks/useOrganizations";
|
||||
import { api, ApiError, PendingInvite } from "@/lib/api";
|
||||
import { toast } from "@/hooks/use-toast";
|
||||
|
||||
function ProfileSkeleton() {
|
||||
@@ -52,18 +51,6 @@ function ProfileSkeleton() {
|
||||
<Skeleton className="h-12 w-full" />
|
||||
</CardContent>
|
||||
</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>
|
||||
);
|
||||
@@ -74,16 +61,7 @@ export default function ProfilePage() {
|
||||
const [name, setName] = useState("");
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
|
||||
// Use React Query hook for organizations with automatic caching and deduplication
|
||||
const { data: organizations = [], isLoading: orgsLoading, error: orgsError } = useOrganizations();
|
||||
|
||||
// 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 : [];
|
||||
const [pendingInvites, setPendingInvites] = useState<PendingInvite[]>([]);
|
||||
|
||||
// Sync local name state with user data
|
||||
useEffect(() => {
|
||||
@@ -92,16 +70,13 @@ export default function ProfilePage() {
|
||||
}
|
||||
}, [user?.full_name]);
|
||||
|
||||
// Handle 403 errors for organizations
|
||||
// Fetch pending invitations for this user
|
||||
useEffect(() => {
|
||||
if (orgsError instanceof ApiError && orgsError.code === 403) {
|
||||
toast({
|
||||
title: "Access Denied",
|
||||
description: "You don't have permission to view organizations. Please contact your organization administrator.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}, [orgsError]);
|
||||
if (!user) return;
|
||||
api.users.getMyInvites()
|
||||
.then((res) => setPendingInvites(res.invites ?? []))
|
||||
.catch(() => { /* silently ignore */ });
|
||||
}, [user]);
|
||||
|
||||
const getInitials = (fullName: string | null) => {
|
||||
if (!fullName) return "?";
|
||||
@@ -159,11 +134,39 @@ export default function ProfilePage() {
|
||||
<div className="page-header">
|
||||
<h1 className="page-title">Profile</h1>
|
||||
<p className="page-description">
|
||||
Manage your personal information and organization memberships
|
||||
Manage your personal information and account settings
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* 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 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@@ -247,59 +250,6 @@ export default function ProfilePage() {
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Organizations */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Organizations</CardTitle>
|
||||
<CardDescription>Organizations you're a member of</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{orgsLoading ? (
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-14 w-full" />
|
||||
<Skeleton className="h-14 w-full" />
|
||||
</div>
|
||||
) : organizationsArray.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-6">
|
||||
You're not a member of any organizations yet.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{organizationsArray.map((org) => (
|
||||
<div
|
||||
key={org.id}
|
||||
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>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
Pencil,
|
||||
ShieldOff,
|
||||
Server,
|
||||
Clock,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
@@ -46,7 +47,7 @@ import {
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { api, SSHKey, SSHCertificate, ApiError, PrincipalOption, MyPrincipalsOrg } from "@/lib/api";
|
||||
import { api, SSHKey, SSHCertificate, ApiError, PrincipalOption, MyPrincipalsOrg, DeptCertPolicy } from "@/lib/api";
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
// Helpers
|
||||
@@ -124,6 +125,7 @@ export default function SSHKeysPage() {
|
||||
const [signError, setSignError] = useState<string | null>(null);
|
||||
const [certType, setCertType] = useState<'user' | 'host'>('user');
|
||||
const [expiryHours, setExpiryHours] = useState<string>('');
|
||||
const [deptCertPolicy, setDeptCertPolicy] = useState<DeptCertPolicy | null>(null);
|
||||
|
||||
// Principal selection (populated when sign dialog opens)
|
||||
const [principalOrgs, setPrincipalOrgs] = useState<MyPrincipalsOrg[]>([]);
|
||||
@@ -314,8 +316,14 @@ export default function SSHKeysPage() {
|
||||
setIsAdminMode(false);
|
||||
setCertType('user');
|
||||
setExpiryHours('');
|
||||
setDeptCertPolicy(null);
|
||||
setIsLoadingPrincipals(true);
|
||||
|
||||
// Fetch dept cert policy in parallel
|
||||
api.ssh.getMyDeptCertPolicy().then((data) => {
|
||||
setDeptCertPolicy(data.policy);
|
||||
}).catch(() => {/* non-fatal */});
|
||||
|
||||
try {
|
||||
const data = await api.users.myPrincipals();
|
||||
setPrincipalOrgs(data.orgs);
|
||||
@@ -961,12 +969,40 @@ cat /tmp/challenge.txt.sig | base64 -w0`}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Expiry hours override */}
|
||||
{/* Expiry — controlled by dept cert policy */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="expiry-hours" className="text-sm font-medium">
|
||||
Validity (hours){' '}
|
||||
<span className="text-muted-foreground font-normal">(optional — leave blank to use CA default)</span>
|
||||
<Label htmlFor="expiry-hours" className="text-sm font-medium flex items-center gap-1.5">
|
||||
<Clock className="w-4 h-4" />
|
||||
Validity (hours)
|
||||
</Label>
|
||||
{deptCertPolicy?.allow_user_expiry ? (
|
||||
<div className="space-y-1">
|
||||
<Input
|
||||
id="expiry-hours"
|
||||
type="number"
|
||||
min={1}
|
||||
max={deptCertPolicy.max_expiry_hours}
|
||||
placeholder={`Default: ${deptCertPolicy.default_expiry_hours}h`}
|
||||
value={expiryHours}
|
||||
onChange={(e) => setExpiryHours(e.target.value)}
|
||||
className="w-40"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{isAdminMode
|
||||
? deptCertPolicy.max_expiry_hours < 8760
|
||||
? <>Capped at <strong>{deptCertPolicy.max_expiry_hours}h</strong> by department policy. Leave blank for default ({deptCertPolicy.default_expiry_hours}h).</>
|
||||
: <>Leave blank to use default ({deptCertPolicy.default_expiry_hours}h).</>
|
||||
: <>Max allowed: <strong>{deptCertPolicy.max_expiry_hours}h</strong>. Leave blank for default ({deptCertPolicy.default_expiry_hours}h).</>
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
) : deptCertPolicy ? (
|
||||
<div className="flex items-center gap-2 px-3 py-2 rounded-md bg-muted text-sm text-muted-foreground">
|
||||
<Clock className="w-4 h-4 flex-shrink-0" />
|
||||
<span>Expiry set by policy: <strong>{deptCertPolicy.default_expiry_hours} hours</strong></span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
<Input
|
||||
id="expiry-hours"
|
||||
type="number"
|
||||
@@ -976,7 +1012,22 @@ cat /tmp/challenge.txt.sig | base64 -w0`}
|
||||
onChange={(e) => setExpiryHours(e.target.value)}
|
||||
className="w-36"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">Leave blank to use CA default.</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Extensions granted (informational) */}
|
||||
{deptCertPolicy && deptCertPolicy.all_extensions?.length > 0 && (
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-sm font-medium">Extensions granted</Label>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{deptCertPolicy.all_extensions?.map((ext) => (
|
||||
<Badge key={ext} variant="secondary" className="text-xs font-mono">{ext}</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3 py-2">
|
||||
|
||||
Reference in New Issue
Block a user