Add dynamic group management functionality

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 705f2157-ef97-4fbd-89e4-8c7f2ecaea90
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/7ed01c5f-a82d-405a-b728-b2e3d127c60c/b79bd19f-1b58-4c34-bd88-7fdc94d48f8a.jpg
This commit is contained in:
alphaeusmote
2025-04-10 03:33:30 +00:00
parent 628e9b6ac1
commit 9346c46054
5 changed files with 1458 additions and 0 deletions
+2
View File
@@ -21,6 +21,7 @@ import SettingsPage from "@/pages/settings-page";
import UserManagementPage from "@/pages/user-management-page";
import AuditLogsPage from "@/pages/audit-logs-page";
import SitesPage from "@/pages/sites-page";
import DynamicGroupsPage from "@/pages/dynamic-groups-page";
export default function App() {
return (
@@ -45,6 +46,7 @@ export default function App() {
<ProtectedRoute path="/settings" component={SettingsPage} />
<ProtectedRoute path="/user-management" component={UserManagementPage} />
<ProtectedRoute path="/sites" component={SitesPage} />
<ProtectedRoute path="/dynamic-groups" component={DynamicGroupsPage} />
<ProtectedRoute path="/reporting/dashboards" component={CustomDashboardsPage} />
<Route>
<NotFound />
@@ -0,0 +1,591 @@
import React, { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useQuery } from "@tanstack/react-query";
import { Loader2, Plus, Trash, ArrowRightLeft, MoveVertical, Group, Layers } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import {
DndContext,
DragOverlay,
closestCenter,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
DragStartEvent,
DragEndEvent,
} from "@dnd-kit/core";
import {
SortableContext,
sortableKeyboardCoordinates,
verticalListSortingStrategy,
useSortable,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
interface Condition {
id: number;
type: "condition" | "group";
parentId: number | null;
operator: string;
attribute?: string;
value?: string;
position: number;
children?: Condition[];
}
interface Connection {
id: number;
name: string;
server: string;
}
interface LdapAttribute {
id: number;
name: string;
displayName: string | null;
description: string | null;
type: string | null;
multiValued: boolean;
objectClass: string;
}
interface ConditionBuilderProps {
conditions: Condition[];
onChange: (conditions: Condition[]) => void;
connections: Connection[];
}
const conditionOperators = [
{ value: "equals", label: "Equals" },
{ value: "contains", label: "Contains" },
{ value: "startsWith", label: "Starts With" },
{ value: "endsWith", label: "Ends With" },
{ value: "present", label: "Is Present" },
{ value: "notPresent", label: "Is Not Present" },
{ value: "greaterThan", label: "Greater Than" },
{ value: "lessThan", label: "Less Than" },
];
const groupOperators = [
{ value: "and", label: "AND" },
{ value: "or", label: "OR" },
{ value: "not", label: "NOT" },
];
export default function ConditionBuilder({ conditions, onChange, connections }: ConditionBuilderProps) {
const [selectedConnectionId, setSelectedConnectionId] = useState<number | null>(null);
const [activeId, setActiveId] = useState<number | null>(null);
const [nextId, setNextId] = useState<number>(1);
// Ensure we have unique IDs for new conditions
useEffect(() => {
if (conditions.length > 0) {
const maxId = Math.max(...conditions.map(c => c.id)) + 1;
setNextId(maxId);
}
}, [conditions]);
// Fetch LDAP attributes for the selected connection
const { data: attributes, isLoading: isLoadingAttributes } = useQuery({
queryKey: ["/api/ldap-attributes", selectedConnectionId],
enabled: !!selectedConnectionId,
retry: false,
});
// DnD setup
const sensors = useSensors(
useSensor(PointerSensor),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
})
);
const handleDragStart = (event: DragStartEvent) => {
setActiveId(event.active.id as number);
};
const handleDragEnd = (event: DragEndEvent) => {
setActiveId(null);
const { active, over } = event;
if (over && active.id !== over.id) {
// Handle reordering logic here
const updatedConditions = [...conditions];
// Implement sorting logic
onChange(updatedConditions);
}
};
// Add a new condition to the root level
const addCondition = () => {
const newCondition: Condition = {
id: nextId,
type: "condition",
parentId: null,
operator: "equals",
attribute: "",
value: "",
position: conditions.length,
};
onChange([...conditions, newCondition]);
setNextId(nextId + 1);
};
// Add a new condition group to the root level
const addGroup = () => {
const newGroup: Condition = {
id: nextId,
type: "group",
parentId: null,
operator: "and",
position: conditions.length,
children: [],
};
onChange([...conditions, newGroup]);
setNextId(nextId + 1);
};
// Update a condition
const updateCondition = (id: number, updates: Partial<Condition>) => {
const updatedConditions = conditions.map(condition => {
if (condition.id === id) {
return { ...condition, ...updates };
}
return condition;
});
onChange(updatedConditions);
};
// Delete a condition
const deleteCondition = (id: number) => {
const filteredConditions = conditions.filter(condition => condition.id !== id);
onChange(filteredConditions);
};
// Add a nested condition inside a group
const addNestedCondition = (parentId: number) => {
const updatedConditions = [...conditions];
const parentIndex = updatedConditions.findIndex(c => c.id === parentId);
if (parentIndex !== -1 && updatedConditions[parentIndex].type === "group") {
const parent = updatedConditions[parentIndex];
const children = parent.children || [];
const newCondition: Condition = {
id: nextId,
type: "condition",
parentId: parentId,
operator: "equals",
attribute: "",
value: "",
position: children.length,
};
updatedConditions[parentIndex] = {
...parent,
children: [...children, newCondition],
};
onChange(updatedConditions);
setNextId(nextId + 1);
}
};
return (
<div className="space-y-4">
<div className="flex items-center space-x-4 mb-6">
<Label htmlFor="connection-select" className="min-w-36">Select LDAP Connection:</Label>
<Select
value={selectedConnectionId?.toString() || ""}
onValueChange={(value) => setSelectedConnectionId(parseInt(value, 10))}
>
<SelectTrigger id="connection-select" className="w-[260px]">
<SelectValue placeholder="Select a connection" />
</SelectTrigger>
<SelectContent>
{connections.map((connection) => (
<SelectItem key={connection.id} value={connection.id.toString()}>
{connection.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex items-center space-x-2 mb-4">
<Button onClick={addCondition} variant="outline" size="sm">
<Plus className="mr-1 h-4 w-4" />
Add Condition
</Button>
<Button onClick={addGroup} variant="outline" size="sm">
<Layers className="mr-1 h-4 w-4" />
Add Group
</Button>
</div>
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
>
<SortableContext
items={conditions.map(c => c.id)}
strategy={verticalListSortingStrategy}
>
<div className="space-y-3">
{conditions.length === 0 ? (
<div className="border border-dashed rounded-lg p-6 text-center">
<p className="text-muted-foreground">No conditions defined. Add a condition or group to get started.</p>
</div>
) : (
conditions.map(condition => (
<ConditionItem
key={condition.id}
condition={condition}
attributes={attributes || []}
isLoadingAttributes={isLoadingAttributes}
onUpdate={(updates) => updateCondition(condition.id, updates)}
onDelete={() => deleteCondition(condition.id)}
onAddNested={
condition.type === "group"
? () => addNestedCondition(condition.id)
: undefined
}
selectedConnectionId={selectedConnectionId}
/>
))
)}
</div>
</SortableContext>
<DragOverlay>
{activeId ? (
<div className="bg-background border rounded-lg p-4 shadow-lg">
Dragging Item {activeId}
</div>
) : null}
</DragOverlay>
</DndContext>
</div>
);
}
interface ConditionItemProps {
condition: Condition;
attributes: LdapAttribute[];
isLoadingAttributes: boolean;
onUpdate: (updates: Partial<Condition>) => void;
onDelete: () => void;
onAddNested?: () => void;
selectedConnectionId: number | null;
}
function ConditionItem({
condition,
attributes,
isLoadingAttributes,
onUpdate,
onDelete,
onAddNested,
selectedConnectionId
}: ConditionItemProps) {
const {
attributes: sortableAttributes,
listeners,
setNodeRef,
transform,
transition,
} = useSortable({ id: condition.id });
const style = {
transform: CSS.Transform.toString(transform),
transition,
};
if (condition.type === "group") {
return (
<div ref={setNodeRef} style={style} className="relative">
<Card className="border-primary/20">
<CardContent className="p-4">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center space-x-2">
<Badge variant="outline" className="cursor-move" {...sortableAttributes} {...listeners}>
<MoveVertical className="h-3 w-3 mr-1" />
Drag
</Badge>
<Label>Group Operator:</Label>
<Select
value={condition.operator}
onValueChange={(value) => onUpdate({ operator: value })}
>
<SelectTrigger className="w-[140px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
{groupOperators.map((op) => (
<SelectItem key={op.value} value={op.value}>
{op.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex items-center space-x-2">
<Button variant="ghost" size="icon" onClick={onAddNested}>
<Plus className="h-4 w-4" />
</Button>
<Button variant="ghost" size="icon" onClick={onDelete}>
<Trash className="h-4 w-4 text-destructive" />
</Button>
</div>
</div>
<div className="pl-6 border-l-2 border-primary/20 mt-4 space-y-3">
{condition.children && condition.children.length > 0 ? (
condition.children.map((child) => (
<NestedConditionItem
key={child.id}
condition={child}
attributes={attributes}
isLoadingAttributes={isLoadingAttributes}
onUpdate={(updates) => {
const updatedChildren = condition.children?.map((c) => {
if (c.id === child.id) {
return { ...c, ...updates };
}
return c;
});
onUpdate({ children: updatedChildren });
}}
onDelete={() => {
const updatedChildren = condition.children?.filter((c) => c.id !== child.id);
onUpdate({ children: updatedChildren });
}}
selectedConnectionId={selectedConnectionId}
/>
))
) : (
<div className="text-center py-2 text-sm text-muted-foreground">
<p>No conditions in this group.</p>
<Button
variant="ghost"
size="sm"
className="mt-1"
onClick={onAddNested}
>
<Plus className="h-4 w-4 mr-1" />
Add Condition
</Button>
</div>
)}
</div>
</CardContent>
</Card>
</div>
);
}
return (
<div ref={setNodeRef} style={style}>
<Card>
<CardContent className="p-4">
<div className="flex flex-wrap gap-3 items-center">
<Badge variant="outline" className="cursor-move" {...sortableAttributes} {...listeners}>
<MoveVertical className="h-3 w-3 mr-1" />
Drag
</Badge>
<div className="flex-1 min-w-52">
<Label htmlFor={`attribute-${condition.id}`} className="mb-1 block text-xs">
Attribute
</Label>
{isLoadingAttributes ? (
<div className="flex items-center">
<Loader2 className="h-4 w-4 animate-spin mr-2" />
<span className="text-sm">Loading attributes...</span>
</div>
) : !selectedConnectionId ? (
<Input
id={`attribute-${condition.id}`}
value={condition.attribute || ""}
onChange={(e) => onUpdate({ attribute: e.target.value })}
placeholder="Select a connection first"
className="w-full"
/>
) : (
<Select
value={condition.attribute || ""}
onValueChange={(value) => onUpdate({ attribute: value })}
>
<SelectTrigger id={`attribute-${condition.id}`} className="w-full">
<SelectValue placeholder="Select attribute" />
</SelectTrigger>
<SelectContent>
{attributes.map((attr) => (
<SelectItem key={attr.id} value={attr.name}>
{attr.displayName || attr.name}
</SelectItem>
))}
<SelectItem value="custom">Custom attribute...</SelectItem>
</SelectContent>
</Select>
)}
</div>
<div className="w-36">
<Label htmlFor={`operator-${condition.id}`} className="mb-1 block text-xs">
Operator
</Label>
<Select
value={condition.operator}
onValueChange={(value) => onUpdate({ operator: value })}
>
<SelectTrigger id={`operator-${condition.id}`} className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
{conditionOperators.map((op) => (
<SelectItem key={op.value} value={op.value}>
{op.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex-1 min-w-52">
<Label htmlFor={`value-${condition.id}`} className="mb-1 block text-xs">
Value
</Label>
<Input
id={`value-${condition.id}`}
value={condition.value || ""}
onChange={(e) => onUpdate({ value: e.target.value })}
placeholder="Value"
className="w-full"
disabled={["present", "notPresent"].includes(condition.operator)}
/>
</div>
<Button variant="ghost" size="icon" onClick={onDelete} className="self-end mb-0.5">
<Trash className="h-4 w-4 text-destructive" />
</Button>
</div>
</CardContent>
</Card>
</div>
);
}
interface NestedConditionItemProps {
condition: Condition;
attributes: LdapAttribute[];
isLoadingAttributes: boolean;
onUpdate: (updates: Partial<Condition>) => void;
onDelete: () => void;
selectedConnectionId: number | null;
}
function NestedConditionItem({
condition,
attributes,
isLoadingAttributes,
onUpdate,
onDelete,
selectedConnectionId
}: NestedConditionItemProps) {
return (
<Card className="border-muted">
<CardContent className="p-3">
<div className="flex flex-wrap gap-2 items-center">
<div className="flex-1 min-w-40">
<Label htmlFor={`nested-attribute-${condition.id}`} className="mb-1 block text-xs">
Attribute
</Label>
{isLoadingAttributes ? (
<div className="flex items-center">
<Loader2 className="h-4 w-4 animate-spin mr-2" />
<span className="text-sm">Loading...</span>
</div>
) : !selectedConnectionId ? (
<Input
id={`nested-attribute-${condition.id}`}
value={condition.attribute || ""}
onChange={(e) => onUpdate({ attribute: e.target.value })}
placeholder="Select a connection first"
className="w-full"
/>
) : (
<Select
value={condition.attribute || ""}
onValueChange={(value) => onUpdate({ attribute: value })}
>
<SelectTrigger id={`nested-attribute-${condition.id}`} className="w-full">
<SelectValue placeholder="Select attribute" />
</SelectTrigger>
<SelectContent>
{attributes.map((attr) => (
<SelectItem key={attr.id} value={attr.name}>
{attr.displayName || attr.name}
</SelectItem>
))}
<SelectItem value="custom">Custom attribute...</SelectItem>
</SelectContent>
</Select>
)}
</div>
<div className="w-32">
<Label htmlFor={`nested-operator-${condition.id}`} className="mb-1 block text-xs">
Operator
</Label>
<Select
value={condition.operator}
onValueChange={(value) => onUpdate({ operator: value })}
>
<SelectTrigger id={`nested-operator-${condition.id}`} className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
{conditionOperators.map((op) => (
<SelectItem key={op.value} value={op.value}>
{op.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex-1 min-w-40">
<Label htmlFor={`nested-value-${condition.id}`} className="mb-1 block text-xs">
Value
</Label>
<Input
id={`nested-value-${condition.id}`}
value={condition.value || ""}
onChange={(e) => onUpdate({ value: e.target.value })}
placeholder="Value"
className="w-full"
disabled={["present", "notPresent"].includes(condition.operator)}
/>
</div>
<Button variant="ghost" size="icon" onClick={onDelete} className="self-end mb-0.5">
<Trash className="h-4 w-4 text-destructive" />
</Button>
</div>
</CardContent>
</Card>
);
}
@@ -0,0 +1,397 @@
import React, { useState, useEffect } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Separator } from "@/components/ui/separator";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import { queryClient, apiRequest } from "@/lib/queryClient";
import { Loader2, Plus, Save, Trash, Code, Filter } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Checkbox } from "@/components/ui/checkbox";
import { useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import ConditionBuilder from "./condition-builder";
// Define the schema for rule form
const ruleFormSchema = z.object({
name: z.string().min(1, "Name is required"),
description: z.string().optional(),
targetGroup: z.string().min(1, "Target group is required"),
enabled: z.boolean().default(true),
schedule: z.string().min(1, "Schedule is required"),
variablePattern: z.string().optional(),
connectionIds: z.array(z.number()).min(1, "At least one connection is required"),
});
type RuleFormValues = z.infer<typeof ruleFormSchema>;
interface Condition {
id: number;
type: "condition" | "group";
parentId: number | null;
operator: string;
attribute?: string;
value?: string;
position: number;
children?: Condition[];
}
interface Connection {
id: number;
name: string;
server: string;
}
interface DynamicGroupRule {
id?: number;
name: string;
description: string | null;
targetGroup: string;
enabled: boolean;
schedule: string;
variablePattern: string | null;
connectionIds: number[];
conditions: Condition[];
}
interface RuleEditorProps {
ruleId?: number;
onSuccess?: () => void;
onCancel?: () => void;
}
export default function RuleEditor({ ruleId, onSuccess, onCancel }: RuleEditorProps) {
const { toast } = useToast();
const [conditions, setConditions] = useState<Condition[]>([]);
const [activeTab, setActiveTab] = useState("general");
const isEditMode = !!ruleId;
// Fetch connections for dropdown
const { data: connections, isLoading: isLoadingConnections } = useQuery({
queryKey: ["/api/ldap-connections"],
retry: false,
});
// Fetch rule data if editing
const { data: ruleData, isLoading: isLoadingRule } = useQuery({
queryKey: ["/api/dynamic-group-rules", ruleId],
enabled: !!ruleId,
retry: false,
});
// Form setup
const form = useForm<RuleFormValues>({
resolver: zodResolver(ruleFormSchema),
defaultValues: {
name: "",
description: "",
targetGroup: "",
enabled: true,
schedule: "0 0 * * *", // Daily at midnight
variablePattern: "",
connectionIds: [],
},
});
// Update form when rule data is loaded
useEffect(() => {
if (ruleData) {
form.reset({
name: ruleData.name,
description: ruleData.description || "",
targetGroup: ruleData.targetGroup,
enabled: ruleData.enabled,
schedule: ruleData.schedule,
variablePattern: ruleData.variablePattern || "",
connectionIds: ruleData.connections.map((c: any) => c.id),
});
setConditions(ruleData.conditions || []);
}
}, [ruleData, form]);
// Create/Update rule mutation
const saveMutation = useMutation({
mutationFn: async (data: DynamicGroupRule) => {
const url = isEditMode
? `/api/dynamic-group-rules/${ruleId}`
: `/api/dynamic-group-rules`;
const method = isEditMode ? "PUT" : "POST";
const response = await apiRequest(method, url, data);
return response.json();
},
onSuccess: () => {
toast({
title: "Success",
description: `Rule ${isEditMode ? "updated" : "created"} successfully`,
variant: "default",
});
queryClient.invalidateQueries({ queryKey: ["/api/dynamic-group-rules"] });
if (onSuccess) onSuccess();
},
onError: (error: Error) => {
toast({
title: "Error",
description: `Failed to ${isEditMode ? "update" : "create"} rule: ${error.message}`,
variant: "destructive",
});
},
});
// Handle form submission
const onSubmit = (values: RuleFormValues) => {
const ruleData: DynamicGroupRule = {
...values,
conditions,
};
saveMutation.mutate(ruleData);
};
// Update conditions handler
const handleConditionsUpdate = (updatedConditions: Condition[]) => {
setConditions(updatedConditions);
};
// Loading state
const isLoading = isLoadingConnections || (isEditMode && isLoadingRule);
return (
<div className="space-y-6">
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList className="grid w-full grid-cols-3">
<TabsTrigger value="general">General</TabsTrigger>
<TabsTrigger value="conditions">Conditions</TabsTrigger>
<TabsTrigger value="preview">Preview</TabsTrigger>
</TabsList>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<TabsContent value="general" className="space-y-4 mt-4">
{isLoading ? (
<div className="flex items-center justify-center py-10">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</div>
) : (
<Card>
<CardHeader>
<CardTitle>Rule Configuration</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{/* Basic rule information */}
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Rule Name</FormLabel>
<FormControl>
<Input placeholder="Enter rule name" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>Description</FormLabel>
<FormControl>
<Textarea
placeholder="Optional description of what this rule does"
{...field}
value={field.value || ""}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="targetGroup"
render={({ field }) => (
<FormItem>
<FormLabel>Target Group (DN)</FormLabel>
<FormControl>
<Input
placeholder="Distinguished Name of the target group"
{...field}
/>
</FormControl>
<FormDescription>
Members matching the conditions will be added to this group
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="connectionIds"
render={() => (
<FormItem>
<FormLabel>LDAP Connections</FormLabel>
<div className="space-y-2">
{connections && connections.map((connection: Connection) => (
<div key={connection.id} className="flex items-center space-x-2">
<Controller
control={form.control}
name="connectionIds"
render={({ field }) => (
<Checkbox
id={`connection-${connection.id}`}
checked={field.value?.includes(connection.id)}
onCheckedChange={(checked) => {
if (checked) {
const newValue = [...(field.value || []), connection.id];
field.onChange(newValue);
} else {
const newValue = field.value?.filter((id) => id !== connection.id);
field.onChange(newValue);
}
}}
/>
)}
/>
<Label htmlFor={`connection-${connection.id}`}>
{connection.name} <span className="text-muted-foreground">({connection.server})</span>
</Label>
</div>
))}
</div>
<FormDescription>
Select the LDAP connections this rule should apply to
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Separator />
<FormField
control={form.control}
name="schedule"
render={({ field }) => (
<FormItem>
<FormLabel>Schedule (Cron Format)</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormDescription>
When to run this rule (e.g., "0 0 * * *" for daily at midnight)
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="variablePattern"
render={({ field }) => (
<FormItem>
<FormLabel>Variable Pattern (Optional)</FormLabel>
<FormControl>
<Input
placeholder="{{department}}-Users"
{...field}
value={field.value || ""}
/>
</FormControl>
<FormDescription>
Pattern for dynamic group naming with variable substitution
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="enabled"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">
Enabled
</FormLabel>
<FormDescription>
Enable or disable this rule from running
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
</CardContent>
</Card>
)}
</TabsContent>
<TabsContent value="conditions" className="space-y-4 mt-4">
<Card>
<CardHeader>
<CardTitle>Rule Conditions</CardTitle>
</CardHeader>
<CardContent>
<ConditionBuilder
conditions={conditions}
onChange={handleConditionsUpdate}
connections={connections || []}
/>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="preview" className="space-y-4 mt-4">
<Card>
<CardHeader>
<CardTitle>LDAP Filter Preview</CardTitle>
</CardHeader>
<CardContent>
<div className="bg-muted rounded-md p-4 font-mono text-sm overflow-x-auto">
{/* This would show the actual LDAP filter generated from the conditions */}
{conditions.length ? (
<pre>(&(objectClass=user)(memberOf=CN=Domain Users,CN=Users,DC=example,DC=com))</pre>
) : (
<p className="text-muted-foreground">No conditions defined yet. Add conditions to see the preview.</p>
)}
</div>
</CardContent>
</Card>
</TabsContent>
<div className="flex justify-end space-x-2 mt-6">
<Button variant="outline" type="button" onClick={onCancel}>
Cancel
</Button>
<Button type="submit" disabled={saveMutation.isPending}>
{saveMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{isEditMode ? "Update Rule" : "Create Rule"}
</Button>
</div>
</form>
</Form>
</Tabs>
</div>
);
}
@@ -0,0 +1,53 @@
import React, { useState } from "react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import RuleEditor from "@/components/dynamic-groups/rule-editor";
interface DynamicGroupRuleModalProps {
isOpen: boolean;
onOpenChange: (open: boolean) => void;
ruleId?: number;
onSuccess?: () => void;
}
export default function DynamicGroupRuleModal({
isOpen,
onOpenChange,
ruleId,
onSuccess,
}: DynamicGroupRuleModalProps) {
const handleCancel = () => {
onOpenChange(false);
};
const handleSuccess = () => {
if (onSuccess) onSuccess();
onOpenChange(false);
};
return (
<Dialog open={isOpen} onOpenChange={onOpenChange}>
<DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{ruleId ? "Edit" : "Create"} Dynamic Group Rule</DialogTitle>
<DialogDescription>
{ruleId
? "Modify the existing dynamic group membership rule"
: "Create a new rule to automatically manage group memberships"}
</DialogDescription>
</DialogHeader>
<RuleEditor
ruleId={ruleId}
onSuccess={handleSuccess}
onCancel={handleCancel}
/>
</DialogContent>
</Dialog>
);
}
+415
View File
@@ -0,0 +1,415 @@
import React from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Separator } from "@/components/ui/separator";
import { useToast } from "@/hooks/use-toast";
import { queryClient, apiRequest } from "@/lib/queryClient";
import DashboardLayout from "@/layouts/dashboard-layout";
import { PlusCircle, RefreshCw, Trash2, Edit, Play, Clock, Settings } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { ScrollArea } from "@/components/ui/scroll-area";
import { format } from "date-fns";
import { Skeleton } from "@/components/ui/skeleton";
import DynamicGroupRuleModal from "@/components/modals/dynamic-group-rule-modal";
interface DynamicGroupRule {
id: number;
name: string;
description: string | null;
targetGroup: string;
enabled: boolean;
schedule: string;
createdAt: string;
updatedAt: string;
lastRun: string | null;
lastRunStatus: string | null;
variablePattern: string | null;
connections: {
id: number;
name: string;
}[];
}
export default function DynamicGroupsPage() {
const { toast } = useToast();
const [activeTab, setActiveTab] = React.useState("active");
const [modalOpen, setModalOpen] = React.useState(false);
const [selectedRuleId, setSelectedRuleId] = React.useState<number | undefined>(undefined);
const { data: dynamicGroupRules, isLoading } = useQuery({
queryKey: ["/api/dynamic-group-rules"],
retry: false,
});
const runNowMutation = useMutation({
mutationFn: async (id: number) => {
const response = await apiRequest("POST", `/api/dynamic-group-rules/${id}/run`);
return response.json();
},
onSuccess: () => {
toast({
title: "Success",
description: "Rule execution started",
variant: "default",
});
queryClient.invalidateQueries({ queryKey: ["/api/dynamic-group-rules"] });
},
onError: (error: Error) => {
toast({
title: "Error",
description: `Failed to execute rule: ${error.message}`,
variant: "destructive",
});
},
});
const toggleRuleMutation = useMutation({
mutationFn: async ({ id, enabled }: { id: number; enabled: boolean }) => {
const response = await apiRequest("PATCH", `/api/dynamic-group-rules/${id}`, { enabled });
return response.json();
},
onSuccess: () => {
toast({
title: "Success",
description: "Rule status updated",
variant: "default",
});
queryClient.invalidateQueries({ queryKey: ["/api/dynamic-group-rules"] });
},
onError: (error: Error) => {
toast({
title: "Error",
description: `Failed to update rule: ${error.message}`,
variant: "destructive",
});
},
});
const deleteRuleMutation = useMutation({
mutationFn: async (id: number) => {
await apiRequest("DELETE", `/api/dynamic-group-rules/${id}`);
},
onSuccess: () => {
toast({
title: "Success",
description: "Rule deleted successfully",
variant: "default",
});
queryClient.invalidateQueries({ queryKey: ["/api/dynamic-group-rules"] });
},
onError: (error: Error) => {
toast({
title: "Error",
description: `Failed to delete rule: ${error.message}`,
variant: "destructive",
});
},
});
const handleDeleteRule = (id: number) => {
if (window.confirm("Are you sure you want to delete this rule? This action cannot be undone.")) {
deleteRuleMutation.mutate(id);
}
};
const handleRunNow = (id: number) => {
runNowMutation.mutate(id);
};
const handleToggleRule = (id: number, currentStatus: boolean) => {
toggleRuleMutation.mutate({ id, enabled: !currentStatus });
};
const handleEditRule = (id: number) => {
setSelectedRuleId(id);
setModalOpen(true);
};
const handleCreateRule = () => {
setSelectedRuleId(undefined);
setModalOpen(true);
};
// Filter the rules based on the active tab
const filteredRules = React.useMemo(() => {
if (!dynamicGroupRules) return [];
return activeTab === "active"
? dynamicGroupRules.filter((rule: DynamicGroupRule) => rule.enabled)
: dynamicGroupRules.filter((rule: DynamicGroupRule) => !rule.enabled);
}, [dynamicGroupRules, activeTab]);
const formatLastRunTime = (lastRun: string | null) => {
if (!lastRun) return "Never";
return format(new Date(lastRun), "MMM d, yyyy 'at' h:mm a");
};
const getStatusBadge = (status: string | null) => {
if (!status) return null;
let variant: "default" | "destructive" | "outline" | "secondary" | null = null;
switch (status.toLowerCase()) {
case "success":
variant = "default";
break;
case "failed":
variant = "destructive";
break;
case "running":
variant = "secondary";
break;
default:
variant = "outline";
}
return <Badge variant={variant}>{status}</Badge>;
};
return (
<DashboardLayout>
<div className="flex items-center justify-between space-y-2">
<h2 className="text-3xl font-bold tracking-tight">Dynamic Group Management</h2>
<div className="flex items-center space-x-2">
<Button onClick={() => queryClient.invalidateQueries({ queryKey: ["/api/dynamic-group-rules"] })}>
<RefreshCw className="mr-2 h-4 w-4" />
Refresh
</Button>
<Button onClick={handleCreateRule}>
<PlusCircle className="mr-2 h-4 w-4" />
New Rule
</Button>
</div>
</div>
<Separator className="my-6" />
<div className="space-y-4">
<Tabs defaultValue="active" value={activeTab} onValueChange={setActiveTab}>
<div className="flex items-center justify-between">
<TabsList>
<TabsTrigger value="active">Active Rules</TabsTrigger>
<TabsTrigger value="disabled">Disabled Rules</TabsTrigger>
</TabsList>
</div>
<TabsContent value="active" className="space-y-4">
<RulesList
rules={filteredRules}
isLoading={isLoading}
onDelete={handleDeleteRule}
onRunNow={handleRunNow}
onToggle={handleToggleRule}
onEdit={handleEditRule}
onCreateNew={handleCreateRule}
/>
</TabsContent>
<TabsContent value="disabled" className="space-y-4">
<RulesList
rules={filteredRules}
isLoading={isLoading}
onDelete={handleDeleteRule}
onRunNow={handleRunNow}
onToggle={handleToggleRule}
onEdit={handleEditRule}
onCreateNew={handleCreateRule}
/>
</TabsContent>
</Tabs>
</div>
{/* Rule Editor Modal */}
<DynamicGroupRuleModal
isOpen={modalOpen}
onOpenChange={setModalOpen}
ruleId={selectedRuleId}
onSuccess={() => {
queryClient.invalidateQueries({ queryKey: ["/api/dynamic-group-rules"] });
}}
/>
</DashboardLayout>
);
}
interface RulesListProps {
rules: DynamicGroupRule[];
isLoading: boolean;
onDelete: (id: number) => void;
onRunNow: (id: number) => void;
onToggle: (id: number, currentStatus: boolean) => void;
onEdit: (id: number) => void;
onCreateNew: () => void;
}
function RulesList({ rules, isLoading, onDelete, onRunNow, onToggle, onEdit, onCreateNew }: RulesListProps) {
if (isLoading) {
return (
<div className="space-y-4">
{[1, 2, 3].map((i) => (
<Card key={i}>
<CardHeader className="pb-2">
<Skeleton className="h-6 w-1/3" />
<Skeleton className="h-4 w-1/2" />
</CardHeader>
<CardContent>
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-5/6" />
<Skeleton className="h-4 w-2/3" />
</div>
</CardContent>
</Card>
))}
</div>
);
}
if (!rules.length) {
return (
<Card>
<CardContent className="flex flex-col items-center justify-center py-10">
<p className="text-muted-foreground mb-4 text-center">
No rules found. Create a new dynamic group rule to get started.
</p>
<Button onClick={onCreateNew}>
<PlusCircle className="mr-2 h-4 w-4" />
Create Rule
</Button>
</CardContent>
</Card>
);
}
return (
<div className="space-y-4">
{rules.map((rule) => (
<Card key={rule.id} className="overflow-hidden">
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<div>
<CardTitle className="mb-1">{rule.name}</CardTitle>
<CardDescription>{rule.description || "No description provided"}</CardDescription>
</div>
<div className="flex items-center space-x-2">
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="icon"
onClick={() => onToggle(rule.id, rule.enabled)}
>
<Settings className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>
{rule.enabled ? "Disable Rule" : "Enable Rule"}
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="icon"
onClick={() => onRunNow(rule.id)}
disabled={!rule.enabled}
>
<Play className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>
Run Now
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="icon"
onClick={() => onEdit(rule.id)}
>
<Edit className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>
Edit Rule
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="icon"
onClick={() => onDelete(rule.id)}
>
<Trash2 className="h-4 w-4 text-destructive" />
</Button>
</TooltipTrigger>
<TooltipContent>
Delete Rule
</TooltipContent>
</Tooltip>
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
<div>
<p className="text-sm font-medium text-muted-foreground">Target Group</p>
<p className="text-sm mt-1 truncate" title={rule.targetGroup}>
{rule.targetGroup}
</p>
</div>
<div>
<p className="text-sm font-medium text-muted-foreground">Schedule</p>
<div className="flex items-center mt-1">
<Clock className="mr-1 h-4 w-4 text-muted-foreground" />
<p className="text-sm">{rule.schedule}</p>
</div>
</div>
<div>
<p className="text-sm font-medium text-muted-foreground">Last Run</p>
<div className="flex items-center space-x-2 mt-1">
<p className="text-sm">{formatLastRunTime(rule.lastRun)}</p>
{rule.lastRunStatus && getStatusBadge(rule.lastRunStatus)}
</div>
</div>
</div>
<div>
<p className="text-sm font-medium text-muted-foreground mb-2">Connected to</p>
<ScrollArea className="h-10">
<div className="flex flex-wrap gap-2">
{rule.connections.map((connection) => (
<Badge variant="outline" key={connection.id}>
{connection.name}
</Badge>
))}
{!rule.connections.length && (
<p className="text-sm text-muted-foreground">No connections</p>
)}
</div>
</ScrollArea>
</div>
{rule.variablePattern && (
<div>
<p className="text-sm font-medium text-muted-foreground">Variable Pattern</p>
<p className="text-sm font-mono mt-1 bg-muted p-1 rounded">
{rule.variablePattern}
</p>
</div>
)}
</div>
</CardContent>
</Card>
))}
</div>
);
}