Restored to 'd77ce2adbe81c897769f79623edb2fdd7c5cdbc7'

Replit-Restored-To: d77ce2adbe
This commit is contained in:
alphaeusmote
2025-04-08 21:19:22 +00:00
parent 077269a3df
commit afca6f811d
18 changed files with 357 additions and 3584 deletions
-2
View File
@@ -11,7 +11,6 @@ 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";
@@ -31,7 +30,6 @@ 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} />
@@ -1,682 +0,0 @@
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, Info } 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";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
// Import shared types from our shared lib
import { LdapOperator, LdapCondition, LdapAttribute } from "@/lib/ldap-types";
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 EnhancedLdapQueryBuilder({
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<LdapAttribute[]>({
queryKey: ["/api/ldap-queries/attributes", { connectionId: selectedConnectionId, targetObject: value.targetObject }],
enabled: !!selectedConnectionId && !!value.targetObject,
});
// Group attributes by their type for better organization
const groupedAttributes = React.useMemo(() => {
const grouped = {
string: availableAttributes.filter(attr => !attr.type || attr.type === "string"),
number: availableAttributes.filter(attr => attr.type === "number"),
datetime: availableAttributes.filter(attr => attr.type === "datetime"),
boolean: availableAttributes.filter(attr => attr.type === "boolean"),
};
return grouped;
}, [availableAttributes]);
// 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].name : 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 });
}
};
// Get recommended operators based on attribute type
const getRecommendedOperators = (attributeName: string | undefined): LdapOperator[] => {
if (!attributeName) return comparisonOperators;
const attribute = availableAttributes.find(attr => attr.name === attributeName);
if (!attribute) return comparisonOperators;
// Return appropriate operators based on type
switch(attribute.type) {
case "number":
return [
LdapOperator.EQUALS,
LdapOperator.NOT_EQUALS,
LdapOperator.GREATER_THAN,
LdapOperator.LESS_THAN,
LdapOperator.PRESENT
];
case "datetime":
return [
LdapOperator.EQUALS,
LdapOperator.NOT_EQUALS,
LdapOperator.GREATER_THAN,
LdapOperator.LESS_THAN,
LdapOperator.PRESENT
];
case "boolean":
return [
LdapOperator.EQUALS,
LdapOperator.NOT_EQUALS,
LdapOperator.PRESENT
];
default: // string
return [
LdapOperator.EQUALS,
LdapOperator.NOT_EQUALS,
LdapOperator.STARTS_WITH,
LdapOperator.ENDS_WITH,
LdapOperator.CONTAINS,
LdapOperator.PRESENT,
LdapOperator.APPROX
];
}
};
// UI component for rendering a single condition
const ConditionItem = ({
condition,
path = []
}: {
condition: LdapCondition;
path: number[];
}) => {
const isLogical = logicalOperators.includes(condition.operator);
const selectedAttribute = availableAttributes.find(attr => attr.name === condition.attribute);
const recommendedOperators = !isLogical ? getRecommendedOperators(condition.attribute) : [];
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].name : 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>
))}
{!isLogical && condition.attribute && (
<SelectItem value="divider" disabled className="font-semibold">
Recommended Operators
</SelectItem>
)}
{!isLogical && condition.attribute && recommendedOperators.map((op) => (
<SelectItem key={op} value={op} className="text-primary">
{operatorLabels[op]}
</SelectItem>
))}
<SelectItem value="divider2" disabled className="font-semibold">
All 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-[250px]">
<SelectValue placeholder="Select attribute" />
</SelectTrigger>
<SelectContent className="max-h-[400px]">
{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>
) : (
<>
{/* String attributes */}
{groupedAttributes.string.length > 0 && (
<>
<SelectItem value="string_group" disabled className="font-semibold">
Text Attributes
</SelectItem>
{groupedAttributes.string.map((attr) => (
<SelectItem key={attr.name} value={attr.name}>
<div className="flex items-center justify-between w-full">
<span>{attr.name}</span>
<div className="flex items-center">
{attr.isMultiValued && (
<Badge variant="outline" className="text-xs ml-2">
Multi
</Badge>
)}
{attr.description && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Info className="h-3 w-3 ml-2 text-muted-foreground" />
</TooltipTrigger>
<TooltipContent side="right">
<p className="max-w-[300px]">{attr.description}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</div>
</div>
</SelectItem>
))}
</>
)}
{/* Number attributes */}
{groupedAttributes.number.length > 0 && (
<>
<SelectItem value="number_group" disabled className="font-semibold">
Number Attributes
</SelectItem>
{groupedAttributes.number.map((attr) => (
<SelectItem key={attr.name} value={attr.name}>
<div className="flex items-center justify-between w-full">
<span>{attr.name}</span>
<div className="flex items-center">
{attr.isMultiValued && (
<Badge variant="outline" className="text-xs ml-2">
Multi
</Badge>
)}
{attr.description && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Info className="h-3 w-3 ml-2 text-muted-foreground" />
</TooltipTrigger>
<TooltipContent side="right">
<p className="max-w-[300px]">{attr.description}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</div>
</div>
</SelectItem>
))}
</>
)}
{/* DateTime attributes */}
{groupedAttributes.datetime.length > 0 && (
<>
<SelectItem value="date_group" disabled className="font-semibold">
Date/Time Attributes
</SelectItem>
{groupedAttributes.datetime.map((attr) => (
<SelectItem key={attr.name} value={attr.name}>
<div className="flex items-center justify-between w-full">
<span>{attr.name}</span>
<div className="flex items-center">
{attr.isMultiValued && (
<Badge variant="outline" className="text-xs ml-2">
Multi
</Badge>
)}
{attr.description && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Info className="h-3 w-3 ml-2 text-muted-foreground" />
</TooltipTrigger>
<TooltipContent side="right">
<p className="max-w-[300px]">{attr.description}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</div>
</div>
</SelectItem>
))}
</>
)}
{/* Boolean attributes */}
{groupedAttributes.boolean.length > 0 && (
<>
<SelectItem value="boolean_group" disabled className="font-semibold">
Boolean Attributes
</SelectItem>
{groupedAttributes.boolean.map((attr) => (
<SelectItem key={attr.name} value={attr.name}>
<div className="flex items-center justify-between w-full">
<span>{attr.name}</span>
<div className="flex items-center">
{attr.isMultiValued && (
<Badge variant="outline" className="text-xs ml-2">
Multi
</Badge>
)}
{attr.description && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Info className="h-3 w-3 ml-2 text-muted-foreground" />
</TooltipTrigger>
<TooltipContent side="right">
<p className="max-w-[300px]">{attr.description}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</div>
</div>
</SelectItem>
))}
</>
)}
</>
)}
</SelectContent>
</Select>
{condition.operator !== LdapOperator.PRESENT && (
<Input
value={condition.value || ""}
placeholder={selectedAttribute?.type === "datetime" ? "YYYY-MM-DD" : "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) => (
<TooltipProvider key={attr.name}>
<Tooltip>
<TooltipTrigger asChild>
<Badge
variant="outline"
className={`cursor-pointer ${
attr.type === 'number'
? 'bg-blue-50 dark:bg-blue-950'
: attr.type === 'datetime'
? 'bg-amber-50 dark:bg-amber-950'
: attr.type === 'boolean'
? 'bg-green-50 dark:bg-green-950'
: ''
}`}
>
{attr.name}
{attr.isMultiValued && <span className="ml-1 opacity-70">*</span>}
</Badge>
</TooltipTrigger>
<TooltipContent>
<div>
<p className="font-bold">{attr.name}</p>
{attr.description && <p>{attr.description}</p>}
<p className="text-xs mt-1">Type: {attr.type || 'string'}</p>
{attr.isMultiValued && (
<p className="text-xs">Multi-valued attribute</p>
)}
</div>
</TooltipContent>
</Tooltip>
</TooltipProvider>
))}
</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,441 +0,0 @@
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";
// Import shared types from our shared lib
import { LdapOperator, LdapCondition, LdapAttribute } from "@/lib/ldap-types";
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<LdapAttribute[]>({
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].name : 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].name : 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.name} value={attr.name}>
{attr.name} {attr.description ? `(${attr.description})` : ''}
</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.name} variant="outline" className="cursor-pointer">
{attr.name} {attr.type ? `(${attr.type})` : ''}
</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,7 +67,6 @@ 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" /> },
],
-36
View File
@@ -1,36 +0,0 @@
// LDAP query types
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
}
// Type definition for an LDAP condition
export interface LdapCondition {
operator: LdapOperator;
attribute?: string; // Not required for logical operators (AND, OR, NOT)
value?: string; // Not required for some operators (PRESENT, logical operators)
conditions?: LdapCondition[]; // For nested conditions with logical operators
}
// Type definition for an LDAP attribute
export interface LdapAttribute {
name: string;
type: string;
description?: string;
syntax?: string;
isMultiValued?: boolean;
isMandatory?: boolean;
}
+6 -17
View File
@@ -100,29 +100,18 @@ export default function AuthPage() {
},
});
// Register mutation - using our simplified endpoint
// Register mutation
const registerMutation = useMutation({
mutationFn: async (credentials: any) => {
try {
const res = await apiRequest("POST", "/api/simple-register", credentials);
if (!res.ok) {
const errorData = await res.json();
throw new Error(errorData.message || "Registration failed");
}
return await res.json();
} catch (error) {
console.error("Registration error:", error);
throw error instanceof Error ? error : new Error("Unknown registration error");
}
const res = await apiRequest("POST", "/api/register", credentials);
return await res.json();
},
onSuccess: (response) => {
onSuccess: (user) => {
toast({
title: "Registration successful",
description: response.message || `Welcome, ${response.username}!`,
description: `Welcome, ${user.username}!`,
});
// Switch to login tab automatically
const loginTab = document.querySelector('[data-state="inactive"][data-value="login"]') as HTMLElement;
if (loginTab) loginTab.click();
navigate('/');
},
onError: (error: Error) => {
toast({
@@ -1,537 +0,0 @@
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 { LdapQueryBuilderParams } from "@/components/ldap/ldap-query-builder";
import { EnhancedLdapQueryBuilder } from "@/components/ldap/enhanced-ldap-query-builder";
import { LdapCondition, LdapOperator } from "@/lib/ldap-types";
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.filterJson as LdapCondition
});
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" as keyof LdapQuery,
},
{
header: "Description",
accessorKey: "description" as keyof LdapQuery,
},
{
header: "Target",
accessorKey: "targetObject" as keyof LdapQuery,
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" as keyof LdapQuery,
cell: (row: LdapQuery) =>
row.updatedAt ? format(new Date(row.updatedAt), "MMM dd, yyyy HH:mm") : "",
},
{
header: "",
accessorKey: "id" as keyof LdapQuery,
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.filterJson as LdapCondition,
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 as keyof typeof firstResult,
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">
<EnhancedLdapQueryBuilder
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>
);
}