Add LDAP query builder feature with UI and API endpoints.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 705f2157-ef97-4fbd-89e4-8c7f2ecaea90
This commit is contained in:
alphaeusmote
2025-04-08 20:12:52 +00:00
6 changed files with 1212 additions and 1 deletions
+2
View File
@@ -11,6 +11,7 @@ import ComputersPage from "@/pages/computers-page";
import DomainsPage from "@/pages/domains-page";
import ApiTokensPage from "@/pages/api-tokens-page";
import LdapConnectionsPage from "@/pages/ldap-connections-page";
import LdapQueryBuilderPage from "@/pages/ldap-query-builder-page";
import SettingsPage from "@/pages/settings-page";
import UserManagementPage from "@/pages/user-management-page";
import { ProtectedRoute } from "./lib/protected-route";
@@ -30,6 +31,7 @@ function Router() {
<ProtectedRoute path="/domains" component={DomainsPage} />
<ProtectedRoute path="/api-tokens" component={ApiTokensPage} />
<ProtectedRoute path="/ldap-connections" component={LdapConnectionsPage} />
<ProtectedRoute path="/ldap-query-builder" component={LdapQueryBuilderPage} />
<ProtectedRoute path="/settings" component={SettingsPage} />
<ProtectedRoute path="/user-management" component={UserManagementPage} />
<Route component={NotFound} />
@@ -0,0 +1,464 @@
import React, { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useToast } from "@/hooks/use-toast";
import { LdapConnection } from "@shared/schema";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
CardFooter
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Loader2, Plus, Trash } from "lucide-react";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Tabs,
TabsContent,
TabsList,
TabsTrigger,
} from "@/components/ui/tabs";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
// These types are from the server-side LdapFilterBuilder
export enum LdapOperator {
// Logical operators
AND = "and",
OR = "or",
NOT = "not",
// Comparison operators
EQUALS = "equals",
NOT_EQUALS = "notEquals",
STARTS_WITH = "startsWith",
ENDS_WITH = "endsWith",
CONTAINS = "contains",
GREATER_THAN = "greaterThan",
LESS_THAN = "lessThan",
PRESENT = "present", // attribute exists
APPROX = "approx", // approximately equals
}
export type LdapCondition = {
operator: LdapOperator;
attribute?: string;
value?: string;
conditions?: LdapCondition[];
};
export type LdapQueryBuilderParams = {
targetObject: "users" | "groups" | "computers" | "ous";
filter: LdapCondition;
};
// Used for displaying the operators in the UI
const operatorLabels: Record<LdapOperator, string> = {
[LdapOperator.AND]: "AND (All conditions)",
[LdapOperator.OR]: "OR (Any condition)",
[LdapOperator.NOT]: "NOT",
[LdapOperator.EQUALS]: "Equals",
[LdapOperator.NOT_EQUALS]: "Does not equal",
[LdapOperator.STARTS_WITH]: "Starts with",
[LdapOperator.ENDS_WITH]: "Ends with",
[LdapOperator.CONTAINS]: "Contains",
[LdapOperator.GREATER_THAN]: "Greater than",
[LdapOperator.LESS_THAN]: "Less than",
[LdapOperator.PRESENT]: "Has value (attribute exists)",
[LdapOperator.APPROX]: "Approximately equals",
};
// Group operators by type for the UI
const logicalOperators = [LdapOperator.AND, LdapOperator.OR, LdapOperator.NOT];
const comparisonOperators = [
LdapOperator.EQUALS,
LdapOperator.NOT_EQUALS,
LdapOperator.STARTS_WITH,
LdapOperator.ENDS_WITH,
LdapOperator.CONTAINS,
LdapOperator.GREATER_THAN,
LdapOperator.LESS_THAN,
LdapOperator.PRESENT,
LdapOperator.APPROX,
];
interface LdapQueryBuilderProps {
connections: LdapConnection[];
value: LdapQueryBuilderParams;
onChange: (value: LdapQueryBuilderParams) => void;
onTest?: () => void;
onSave?: () => void;
}
export function LdapQueryBuilder({
connections,
value,
onChange,
onTest,
onSave
}: LdapQueryBuilderProps) {
const { toast } = useToast();
const [selectedConnectionId, setSelectedConnectionId] = useState<number | null>(
connections.length > 0 ? connections[0].id : null
);
// Load available attributes based on connection and object type
const { data: availableAttributes = [], isLoading: isLoadingAttributes } = useQuery<string[]>({
queryKey: ["/api/ldap-queries/attributes", { connectionId: selectedConnectionId, targetObject: value.targetObject }],
enabled: !!selectedConnectionId && !!value.targetObject,
});
// Update the selected connection ID if the connections list changes
useEffect(() => {
if (connections.length > 0 && !selectedConnectionId) {
setSelectedConnectionId(connections[0].id);
}
}, [connections, selectedConnectionId]);
// Handle changes to the query target object type
const handleTargetObjectChange = (targetObject: "users" | "groups" | "computers" | "ous") => {
onChange({
...value,
targetObject,
});
};
// Handle updates to a condition
const handleConditionChange = (
condition: LdapCondition,
path: number[] = []
): LdapCondition => {
if (path.length === 0) {
return condition;
}
const [index, ...restPath] = path;
const updatedConditions = [...(value.filter.conditions || [])];
if (restPath.length === 0) {
updatedConditions[index] = condition;
} else {
updatedConditions[index] = handleConditionChange(
updatedConditions[index],
restPath
);
}
return {
...value.filter,
conditions: updatedConditions,
};
};
// Add a new condition to a logical operator
const handleAddCondition = (path: number[] = []) => {
let currentCondition = value.filter;
let parent = currentCondition;
// Navigate to the target condition
for (const index of path) {
if (!currentCondition.conditions) {
currentCondition.conditions = [];
}
parent = currentCondition;
currentCondition = currentCondition.conditions[index];
}
// Add a new condition
if (!parent.conditions) {
parent.conditions = [];
}
parent.conditions.push({
operator: LdapOperator.EQUALS,
attribute: availableAttributes.length > 0 ? availableAttributes[0] : undefined,
value: "",
});
onChange({ ...value });
};
// Remove a condition
const handleRemoveCondition = (path: number[]) => {
if (path.length === 0) return;
const parentPath = path.slice(0, -1);
const index = path[path.length - 1];
let currentCondition = value.filter;
// Navigate to the parent condition
for (const idx of parentPath) {
if (!currentCondition.conditions) return;
currentCondition = currentCondition.conditions[idx];
}
// Remove the condition
if (currentCondition.conditions) {
currentCondition.conditions = currentCondition.conditions.filter((_, i) => i !== index);
onChange({ ...value });
}
};
// UI component for rendering a single condition
const ConditionItem = ({
condition,
path = []
}: {
condition: LdapCondition;
path: number[];
}) => {
const isLogical = logicalOperators.includes(condition.operator);
return (
<div className="p-4 border rounded-md mb-2">
<div className="flex flex-wrap gap-2 mb-2">
<Select
value={condition.operator}
onValueChange={(newValue) => {
const updatedCondition = { ...condition, operator: newValue as LdapOperator };
// Reset attributes and values when switching between logical and comparison
const wasLogical = logicalOperators.includes(condition.operator);
const isNowLogical = logicalOperators.includes(updatedCondition.operator);
if (wasLogical !== isNowLogical) {
if (isNowLogical) {
delete updatedCondition.attribute;
delete updatedCondition.value;
updatedCondition.conditions = [];
} else {
delete updatedCondition.conditions;
updatedCondition.attribute = availableAttributes.length > 0 ? availableAttributes[0] : undefined;
updatedCondition.value = "";
}
}
const newFilter = handleConditionChange(updatedCondition, path);
onChange({ ...value, filter: newFilter });
}}
>
<SelectTrigger className="w-[200px]">
<SelectValue placeholder="Select operator" />
</SelectTrigger>
<SelectContent>
<SelectItem value="group" disabled className="font-semibold">
Logical Operators
</SelectItem>
{logicalOperators.map((op) => (
<SelectItem key={op} value={op}>
{operatorLabels[op]}
</SelectItem>
))}
<SelectItem value="divider" disabled className="font-semibold">
Comparison Operators
</SelectItem>
{comparisonOperators.map((op) => (
<SelectItem key={op} value={op}>
{operatorLabels[op]}
</SelectItem>
))}
</SelectContent>
</Select>
{!isLogical && (
<>
<Select
value={condition.attribute}
onValueChange={(newValue) => {
const updatedCondition = { ...condition, attribute: newValue };
const newFilter = handleConditionChange(updatedCondition, path);
onChange({ ...value, filter: newFilter });
}}
>
<SelectTrigger className="w-[200px]">
<SelectValue placeholder="Select attribute" />
</SelectTrigger>
<SelectContent>
{isLoadingAttributes ? (
<div className="flex items-center justify-center p-2">
<Loader2 className="h-4 w-4 animate-spin mr-2" />
Loading attributes...
</div>
) : availableAttributes.length === 0 ? (
<SelectItem value="empty" disabled>
No attributes available
</SelectItem>
) : (
availableAttributes.map((attr) => (
<SelectItem key={attr} value={attr}>
{attr}
</SelectItem>
))
)}
</SelectContent>
</Select>
{condition.operator !== LdapOperator.PRESENT && (
<Input
value={condition.value || ""}
placeholder="Value"
className="flex-1"
onChange={(e) => {
const updatedCondition = { ...condition, value: e.target.value };
const newFilter = handleConditionChange(updatedCondition, path);
onChange({ ...value, filter: newFilter });
}}
/>
)}
</>
)}
{path.length > 0 && (
<Button
variant="ghost"
size="icon"
onClick={() => handleRemoveCondition(path)}
>
<Trash className="h-4 w-4 text-destructive" />
</Button>
)}
</div>
{isLogical && (
<div className="pl-4 border-l-2 border-dashed border-muted-foreground/30">
{condition.conditions?.map((childCondition, index) => (
<ConditionItem
key={index}
condition={childCondition}
path={[...path, index]}
/>
))}
<Button
variant="outline"
size="sm"
onClick={() => handleAddCondition(path)}
className="mt-2"
>
<Plus className="h-4 w-4 mr-2" />
Add Condition
</Button>
</div>
)}
</div>
);
};
return (
<Card className="w-full">
<CardHeader>
<CardTitle>LDAP Query Builder</CardTitle>
<CardDescription>
Build LDAP queries with a visual interface
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<Label htmlFor="connection">LDAP Connection</Label>
<Select
value={selectedConnectionId?.toString() || ""}
onValueChange={(value) => setSelectedConnectionId(parseInt(value))}
disabled={connections.length === 0}
>
<SelectTrigger id="connection">
<SelectValue placeholder="Select LDAP connection" />
</SelectTrigger>
<SelectContent>
{connections.length === 0 ? (
<SelectItem value="empty" disabled>
No connections available
</SelectItem>
) : (
connections.map((connection) => (
<SelectItem key={connection.id} value={connection.id.toString()}>
{connection.name}
</SelectItem>
))
)}
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="targetObject">Target Object Type</Label>
<Select
value={value.targetObject}
onValueChange={(value) =>
handleTargetObjectChange(value as "users" | "groups" | "computers" | "ous")}
>
<SelectTrigger id="targetObject">
<SelectValue placeholder="Select object type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="users">Users</SelectItem>
<SelectItem value="groups">Groups</SelectItem>
<SelectItem value="computers">Computers</SelectItem>
<SelectItem value="ous">Organizational Units</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div>
<Label className="mb-2 block">Build Filter</Label>
<Tabs defaultValue="builder" className="w-full">
<TabsList className="mb-2">
<TabsTrigger value="builder">Visual Builder</TabsTrigger>
<TabsTrigger value="preview">LDAP Filter Preview</TabsTrigger>
</TabsList>
<TabsContent value="builder" className="p-0">
<ConditionItem condition={value.filter} path={[]} />
</TabsContent>
<TabsContent value="preview" className="p-0">
<div className="p-4 bg-muted rounded-md font-mono text-sm overflow-auto">
<pre>
{JSON.stringify(value.filter, null, 2)}
</pre>
</div>
</TabsContent>
</Tabs>
</div>
{availableAttributes.length > 0 && (
<div>
<Label className="mb-2 block">Available Attributes</Label>
<div className="flex flex-wrap gap-2 max-h-[150px] overflow-y-auto p-2 border rounded-md">
{availableAttributes.map((attr) => (
<Badge key={attr} variant="outline" className="cursor-pointer">
{attr}
</Badge>
))}
</div>
</div>
)}
</div>
</CardContent>
<CardFooter className="flex justify-end gap-2">
{onTest && (
<Button
variant="outline"
onClick={onTest}
>
Test Query
</Button>
)}
{onSave && (
<Button
onClick={onSave}
>
Save Query
</Button>
)}
</CardFooter>
</Card>
);
}
+1
View File
@@ -67,6 +67,7 @@ const menuSections: MenuSection[] = [
items: [
{ title: "API Tokens", path: "/api-tokens", icon: <Key className="h-4 w-4" /> },
{ title: "LDAP Connections", path: "/ldap-connections", icon: <Server className="h-4 w-4" /> },
{ title: "LDAP Query Builder", path: "/ldap-query-builder", icon: <FolderClosed className="h-4 w-4" /> },
{ title: "Settings", path: "/settings", icon: <Settings className="h-4 w-4" /> },
{ title: "User Management", path: "/user-management", icon: <ShieldAlert className="h-4 w-4" /> },
],
@@ -0,0 +1,535 @@
import { useState } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { useToast } from "@/hooks/use-toast";
import { DashboardLayout } from "@/layouts/dashboard-layout";
import { LdapConnection, LdapQuery } from "@shared/schema";
import { LdapQueryBuilder, LdapQueryBuilderParams, LdapOperator } from "@/components/ldap/ldap-query-builder";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { DataTable } from "@/components/ui/data-table";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger
} from "@/components/ui/dropdown-menu";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle
} from "@/components/ui/card";
import {
Tabs,
TabsContent,
TabsList,
TabsTrigger,
} from "@/components/ui/tabs";
import { Loader2, MoreHorizontal, Plus, Code, Save, Play, FileClock } from "lucide-react";
import { format } from "date-fns";
export default function LdapQueryBuilderPage() {
const { toast } = useToast();
const [showCreateDialog, setShowCreateDialog] = useState(false);
const [showTestDialog, setShowTestDialog] = useState(false);
const [testResults, setTestResults] = useState<any[] | null>(null);
const [queryName, setQueryName] = useState("");
const [queryDescription, setQueryDescription] = useState("");
const [activeQuery, setActiveQuery] = useState<LdapQuery | null>(null);
const [queryBuilderParams, setQueryBuilderParams] = useState<LdapQueryBuilderParams>({
targetObject: "users",
filter: {
operator: LdapOperator.AND,
conditions: []
}
});
// Fetch all saved queries
const { data: savedQueries = [], isLoading: isLoadingQueries } = useQuery<LdapQuery[]>({
queryKey: ["/api/ldap-queries"],
});
// Fetch LDAP connections for the query builder
const { data: connections = [], isLoading: isLoadingConnections } = useQuery<LdapConnection[]>({
queryKey: ["/api/ldap-connections"],
});
// Mutation for creating a new query
const createQueryMutation = useMutation({
mutationFn: async (data: {
name: string;
description: string;
targetObject: string;
filter: any;
}) => {
const response = await apiRequest("POST", "/api/ldap-queries", data);
return await response.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/ldap-queries"] });
setShowCreateDialog(false);
setQueryName("");
setQueryDescription("");
toast({
title: "Query saved",
description: "The LDAP query has been saved successfully.",
});
},
onError: (error) => {
toast({
title: "Error saving query",
description: error.message,
variant: "destructive",
});
}
});
// Mutation for testing a query
const testQueryMutation = useMutation({
mutationFn: async (data: {
connectionId: number;
targetObject: string;
filter: any;
limit?: number;
}) => {
const response = await apiRequest("POST", "/api/ldap-queries/test", data);
return await response.json();
},
onSuccess: (data) => {
setTestResults(data.results);
setShowTestDialog(true);
toast({
title: "Query executed",
description: `Query returned ${data.count} results.`,
});
},
onError: (error) => {
toast({
title: "Error testing query",
description: error.message,
variant: "destructive",
});
}
});
// Mutation for updating an existing query
const updateQueryMutation = useMutation({
mutationFn: async (data: {
id: number;
name: string;
description: string;
targetObject: string;
filter: any;
}) => {
const response = await apiRequest("PUT", `/api/ldap-queries/${data.id}`, data);
return await response.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/ldap-queries"] });
setActiveQuery(null);
toast({
title: "Query updated",
description: "The LDAP query has been updated successfully.",
});
},
onError: (error) => {
toast({
title: "Error updating query",
description: error.message,
variant: "destructive",
});
}
});
// Function to handle query deletion
const deleteQuery = async (id: number) => {
try {
await apiRequest("DELETE", `/api/ldap-queries/${id}`);
queryClient.invalidateQueries({ queryKey: ["/api/ldap-queries"] });
toast({
title: "Query deleted",
description: "The LDAP query has been deleted successfully.",
});
} catch (error: any) {
toast({
title: "Error deleting query",
description: error.message,
variant: "destructive",
});
}
};
// Function to load a query for editing
const loadQuery = (query: LdapQuery) => {
setActiveQuery(query);
setQueryBuilderParams({
targetObject: query.targetObject as "users" | "groups" | "computers" | "ous",
filter: query.filter
});
setQueryName(query.name);
setQueryDescription(query.description || "");
};
// Function to handle saving a query
const handleSaveQuery = () => {
if (activeQuery) {
updateQueryMutation.mutate({
id: activeQuery.id,
name: queryName,
description: queryDescription,
targetObject: queryBuilderParams.targetObject,
filter: queryBuilderParams.filter
});
} else {
setShowCreateDialog(true);
}
};
// Function to handle testing a query
const handleTestQuery = () => {
if (connections.length === 0) {
toast({
title: "No connections available",
description: "Please add an LDAP connection first.",
variant: "destructive",
});
return;
}
testQueryMutation.mutate({
connectionId: connections[0].id,
targetObject: queryBuilderParams.targetObject,
filter: queryBuilderParams.filter,
limit: 100
});
};
// Generate columns for the saved queries table
const queriesColumns = [
{
header: "Name",
accessorKey: "name",
},
{
header: "Description",
accessorKey: "description",
},
{
header: "Target",
accessorKey: "targetObject",
cell: (row: LdapQuery) => {
const targets: Record<string, string> = {
users: "Users",
groups: "Groups",
computers: "Computers",
ous: "Organizational Units",
};
return targets[row.targetObject] || row.targetObject;
},
},
{
header: "Last Updated",
accessorKey: "updatedAt",
cell: (row: LdapQuery) =>
row.updatedAt ? format(new Date(row.updatedAt), "MMM dd, yyyy HH:mm") : "",
},
{
header: "",
accessorKey: "id",
cell: (row: LdapQuery) => (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon">
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => loadQuery(row)}>
<Code className="h-4 w-4 mr-2" />
Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={() => {
testQueryMutation.mutate({
connectionId: connections.length > 0 ? connections[0].id : 0,
targetObject: row.targetObject,
filter: row.filter,
limit: 100
});
}}>
<Play className="h-4 w-4 mr-2" />
Test
</DropdownMenuItem>
<DropdownMenuItem onClick={() => deleteQuery(row.id)}>
<FileClock className="h-4 w-4 mr-2" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
),
},
];
// Generate columns for the test results table dynamically based on the returned attributes
const getTestResultsColumns = () => {
if (!testResults || testResults.length === 0) return [];
const firstResult = testResults[0];
return Object.keys(firstResult).map(key => ({
header: key,
accessorKey: key,
cell: (row: any) => {
const value = row[key];
if (value === null || value === undefined) return "-";
if (typeof value === "boolean") return value ? "Yes" : "No";
if (Array.isArray(value)) return value.join(", ");
return String(value);
}
}));
};
return (
<DashboardLayout
title="LDAP Query Builder"
description="Build and save LDAP queries for your directory"
>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
{/* Left panel - Saved Queries */}
<div className="md:col-span-1">
<Card className="h-full">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<div>
<CardTitle>Saved Queries</CardTitle>
<CardDescription>
Reuse and manage your saved LDAP queries
</CardDescription>
</div>
<Button
size="sm"
onClick={() => {
setActiveQuery(null);
setQueryBuilderParams({
targetObject: "users",
filter: {
operator: LdapOperator.AND,
conditions: []
}
});
setQueryName("");
setQueryDescription("");
}}
>
<Plus className="h-4 w-4 mr-2" />
New
</Button>
</CardHeader>
<CardContent>
<div className="h-[calc(100vh-300px)] overflow-auto">
<DataTable
data={savedQueries}
columns={queriesColumns}
isLoading={isLoadingQueries}
searchable
/>
</div>
</CardContent>
</Card>
</div>
{/* Right panel - Query Builder */}
<div className="md:col-span-2">
<Card className="h-full">
<CardHeader className="pb-2">
<div className="flex flex-col sm:flex-row justify-between sm:items-center gap-2">
<div>
<CardTitle>
{activeQuery ? "Edit Query" : "New Query"}
</CardTitle>
<CardDescription>
{activeQuery ? `Editing: ${activeQuery.name}` : "Create a new LDAP query"}
</CardDescription>
</div>
<div className="flex gap-2">
<Button
variant="outline"
onClick={handleTestQuery}
disabled={isLoadingConnections || connections.length === 0}
>
{testQueryMutation.isPending ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Play className="h-4 w-4 mr-2" />
)}
Test Query
</Button>
<Button
onClick={handleSaveQuery}
disabled={createQueryMutation.isPending || updateQueryMutation.isPending}
>
{(createQueryMutation.isPending || updateQueryMutation.isPending) ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Save className="h-4 w-4 mr-2" />
)}
Save
</Button>
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-4">
{activeQuery ? (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<Label htmlFor="queryName">Query Name</Label>
<Input
id="queryName"
value={queryName}
onChange={(e) => setQueryName(e.target.value)}
placeholder="My Query"
/>
</div>
<div>
<Label htmlFor="queryDescription">Description</Label>
<Input
id="queryDescription"
value={queryDescription}
onChange={(e) => setQueryDescription(e.target.value)}
placeholder="What does this query do?"
/>
</div>
</div>
) : null}
<div className="pt-2">
<LdapQueryBuilder
connections={connections}
value={queryBuilderParams}
onChange={setQueryBuilderParams}
onTest={handleTestQuery}
onSave={handleSaveQuery}
/>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
{/* Create Query Dialog */}
<Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle>Save Query</DialogTitle>
<DialogDescription>
Give your query a name and description for future reference.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="name">Query Name</Label>
<Input
id="name"
value={queryName}
onChange={(e) => setQueryName(e.target.value)}
placeholder="Enter a name for your query"
/>
</div>
<div className="space-y-2">
<Label htmlFor="description">Description (Optional)</Label>
<Textarea
id="description"
value={queryDescription}
onChange={(e) => setQueryDescription(e.target.value)}
placeholder="What does this query do?"
rows={3}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setShowCreateDialog(false)}>
Cancel
</Button>
<Button
onClick={() => {
if (!queryName) {
toast({
title: "Name required",
description: "Please enter a name for your query.",
variant: "destructive",
});
return;
}
createQueryMutation.mutate({
name: queryName,
description: queryDescription,
targetObject: queryBuilderParams.targetObject,
filter: queryBuilderParams.filter
});
}}
disabled={createQueryMutation.isPending}
>
{createQueryMutation.isPending ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : null}
Save Query
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Test Results Dialog */}
<Dialog open={showTestDialog} onOpenChange={setShowTestDialog}>
<DialogContent className="max-w-5xl max-h-[80vh] overflow-hidden flex flex-col">
<DialogHeader>
<DialogTitle>Query Results</DialogTitle>
<DialogDescription>
Displaying {testResults?.length || 0} results from the LDAP query.
</DialogDescription>
</DialogHeader>
<div className="flex-1 overflow-auto py-4">
{testResults && testResults.length > 0 ? (
<DataTable
data={testResults}
columns={getTestResultsColumns()}
searchable
/>
) : (
<div className="text-center py-8 text-muted-foreground">
{testQueryMutation.isPending ? (
<div className="flex flex-col items-center">
<Loader2 className="h-8 w-8 animate-spin mb-2" />
Executing query...
</div>
) : (
"No results found"
)}
</div>
)}
</div>
<DialogFooter>
<Button onClick={() => setShowTestDialog(false)}>
Close
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</DashboardLayout>
);
}
+82 -1
View File
@@ -6,7 +6,7 @@ import {
buildLdapFilter,
LdapQueryBuilder
} from "./ldap-filter-builder";
import { connectToLdap, searchLdap } from "./ldap";
import { connectToLdap, searchLdap, getLdapAvailableAttributes } from "./ldap";
import { IStorage } from "./storage";
import { InsertLdapQuery, LdapQuery, InsertLdapQueryVersion } from "@shared/schema";
@@ -506,6 +506,87 @@ export function registerLdapQueryBuilderRoutes(router: Router, storage: IStorage
* 404:
* description: Connection not found
*/
/**
* @swagger
* /ldap-queries/attributes:
* get:
* summary: Get available LDAP attributes
* description: Retrieve a list of available attributes for the specified object type from an LDAP connection
* tags: [LDAP Query Builder]
* security:
* - bearerAuth: []
* parameters:
* - in: query
* name: connectionId
* required: true
* schema:
* type: integer
* description: LDAP Connection ID
* - in: query
* name: targetObject
* required: true
* schema:
* type: string
* enum: [users, groups, computers, ous]
* description: The type of object to get attributes for
* responses:
* 200:
* description: A list of available attributes
* content:
* application/json:
* schema:
* type: array
* items:
* type: string
* 400:
* description: Invalid request parameters
* 404:
* description: Connection not found
*/
router.get("/ldap-queries/attributes", hasPermission("read:ldap_objects"), async (req, res) => {
try {
const connectionId = parseInt(req.query.connectionId as string);
const targetObject = req.query.targetObject as "users" | "groups" | "computers" | "ous";
if (isNaN(connectionId)) {
return res.status(400).json({ error: "Invalid connection ID" });
}
if (!targetObject || !["users", "groups", "computers", "ous"].includes(targetObject)) {
return res.status(400).json({ error: "Invalid target object type" });
}
// Get the connection
const connection = await storage.getLdapConnection(connectionId);
if (!connection) {
return res.status(404).json({ error: "LDAP connection not found" });
}
// Connect to LDAP
try {
const client = await connectToLdap(connection);
// Get available attributes
const attributes = await getLdapAvailableAttributes(client, targetObject);
// Close the connection
client.destroy();
// Return the attributes
res.json(attributes);
} catch (error) {
console.error("Error connecting to LDAP:", error);
return res.status(500).json({
error: "Failed to connect to LDAP server",
details: error instanceof Error ? error.message : String(error)
});
}
} catch (error) {
console.error("Error getting LDAP attributes:", error);
res.status(500).json({ error: "Failed to retrieve LDAP attributes" });
}
});
router.post("/ldap-queries/test", hasPermission("read:ldap_objects"), async (req, res) => {
try {
const { connectionId, targetObject, filter, limit = 100, properties = [] } = req.body;
+128
View File
@@ -128,4 +128,132 @@ export async function getLdapDomainInfo(client: ldapjs.Client): Promise<Record<s
debug("Failed to get LDAP domain info:", error);
throw new Error(`Failed to get LDAP domain info: ${errorMessage}`);
}
}
/**
* Get available attributes for a specific object type from LDAP schema
* This function retrieves attributes that are commonly used for the specified object type
*/
export async function getLdapAvailableAttributes(
client: ldapjs.Client,
targetObject: "users" | "groups" | "computers" | "ous"
): Promise<string[]> {
debug(`Getting available attributes for ${targetObject}`);
// Define common attributes for each object type
const commonAttributes = [
"cn", "name", "displayName", "description", "objectClass", "objectCategory",
"distinguishedName", "whenCreated", "whenChanged", "objectGUID", "objectSid"
];
// Object type specific attributes
const specificAttributes: Record<string, string[]> = {
users: [
"sAMAccountName", "userPrincipalName", "givenName", "sn", "mail",
"telephoneNumber", "mobile", "title", "department", "company",
"manager", "employeeID", "employeeNumber", "memberOf", "userAccountControl",
"pwdLastSet", "lastLogon", "lastLogonTimestamp", "accountExpires", "badPwdCount",
"logonCount", "homeDirectory", "homeDrive", "scriptPath", "profilePath",
"lockoutTime", "country", "st", "l", "streetAddress", "postalCode", "otherTelephone"
],
groups: [
"sAMAccountName", "groupType", "member", "memberOf", "managedBy", "msDS-PrincipalName",
"mail", "info", "groupCategory", "adminCount", "proxyAddresses"
],
computers: [
"sAMAccountName", "operatingSystem", "operatingSystemVersion", "operatingSystemServicePack",
"dNSHostName", "servicePrincipalName", "lastLogonTimestamp", "pwdLastSet",
"userAccountControl", "managedBy", "location", "serialNumber", "msDS-SupportedEncryptionTypes",
"networkAddress", "primaryGroupID"
],
ous: [
"ou", "name", "description", "distinguishedName", "managedBy", "gPLink", "gPOptions",
"msDS-Approx-Immed-Subordinates", "streetAddress", "l", "st", "postalCode", "c"
]
};
try {
// Try to dynamically retrieve schema info for more attributes
// This gets attributes from the schema for the specific object class
let dynamicAttributes: string[] = [];
let objectClass: string;
switch (targetObject) {
case "users":
objectClass = "user";
break;
case "groups":
objectClass = "group";
break;
case "computers":
objectClass = "computer";
break;
case "ous":
objectClass = "organizationalUnit";
break;
}
try {
// Attempt to query the schema - we need to try different base DNs since the schema location varies
let schemaResults: Record<string, any>[] = [];
// Try common locations for the schema (most AD servers will use one of these)
const schemaLocations = [
"CN=Schema,CN=Configuration,DC=domain,DC=com", // Generic example
"CN=Schema,CN=Configuration,DC=ad,DC=example,DC=com",
"CN=Schema,CN=Configuration,DC=example,DC=com",
"CN=Schema,CN=Configuration",
"CN=Schema",
];
let schemaFound = false;
for (const schemaLocation of schemaLocations) {
try {
schemaResults = await searchLdap(client, {
base: schemaLocation,
filter: `(&(objectClass=attributeSchema)(|(attributeSyntax=2.5.5.8)(attributeSyntax=2.5.5.9)(attributeSyntax=2.5.5.12)))`,
scope: "sub",
attributes: ["lDAPDisplayName", "attributeSyntax", "isSingleValued"],
limit: 500
});
if (schemaResults.length > 0) {
schemaFound = true;
debug(`Found schema at ${schemaLocation} with ${schemaResults.length} attributes`);
break;
}
} catch (locationError) {
debug(`Schema not found at ${schemaLocation}: ${locationError instanceof Error ? locationError.message : String(locationError)}`);
// Continue trying other locations
}
}
if (!schemaFound) {
debug("Could not find schema in any of the standard locations");
}
dynamicAttributes = schemaResults.map(attr => attr.lDAPDisplayName);
debug(`Retrieved ${dynamicAttributes.length} attributes from schema`);
} catch (schemaError) {
debug("Failed to retrieve attributes from schema, using predefined list:", schemaError);
// Continue with the predefined attributes
}
// Combine common and specific attributes, then add dynamic attributes
let allAttributes = [...commonAttributes, ...specificAttributes[targetObject]];
// Add any dynamic attributes that aren't already in our list
dynamicAttributes.forEach(attr => {
if (!allAttributes.includes(attr)) {
allAttributes.push(attr);
}
});
// Sort alphabetically
return allAttributes.sort();
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : String(error);
debug("Failed to get LDAP available attributes:", error);
// Return a default set of attributes instead of throwing
return [...commonAttributes, ...specificAttributes[targetObject]].sort();
}
}