diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..934e6cc --- /dev/null +++ b/.dockerignore @@ -0,0 +1,63 @@ +# Version control +.git +.gitignore +.github + +# Node.js +node_modules +npm-debug.log +yarn-debug.log +yarn-error.log + +# Build output +dist +build +coverage + +# Environment variables and secrets +.env +.env.* +!.env.example + +# Docker +Dockerfile +docker-compose.yml +.dockerignore + +# Documentation +README.md +DEPLOYMENT.md +docs +*.md + +# Development tools and configuration +.vscode +.idea +*.sublime-* +.editorconfig +.eslintrc +.eslintignore +.prettierrc +.prettierignore +nodemon.json +tsconfig.tsbuildinfo + +# Temporary files +.tmp +.temp +*.log +*.swp +*.swo +.DS_Store +Thumbs.db + +# Other configurations +# (nginx removed) + +# Tests +__tests__ +*.test.ts +*.test.tsx +*.spec.ts +*.spec.tsx +jest.config.js \ No newline at end of file diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..8532172 --- /dev/null +++ b/.env.example @@ -0,0 +1,30 @@ +# Database Configuration +POSTGRES_USER=admanagement +POSTGRES_PASSWORD=strong_password_here +POSTGRES_DB=admanagement +DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB} + +# Redis Configuration +REDIS_URL=redis://redis:6379 + +# Application Configuration +NODE_ENV=production +PORT=5000 +SESSION_SECRET=change_this_to_a_random_string +DEBUG=api:* + +# JWT Secret for API tokens +JWT_SECRET=change_this_to_a_different_random_string +JWT_EXPIRY=24h + +# LDAP Connection Default Settings +LDAP_CONNECT_TIMEOUT=10000 +LDAP_IDLE_TIMEOUT=60000 +LDAP_RECONNECT_TIMEOUT=10000 + +# Rate Limiting +RATE_LIMIT_WINDOW_MS=900000 +RATE_LIMIT_MAX_REQUESTS=1000 + +# Logging +LOG_LEVEL=info \ No newline at end of file diff --git a/.env.production b/.env.production new file mode 100644 index 0000000..ce7499a --- /dev/null +++ b/.env.production @@ -0,0 +1,25 @@ +# Production Environment Settings + +# Node Environment +NODE_ENV=production + +# Server Configuration +PORT=5000 +HOST=0.0.0.0 + +# Logging +LOG_LEVEL=info +DEBUG=api:error,api:cache + +# Performance Tuning +COMPRESSION_LEVEL=6 +BODY_PARSER_LIMIT=10mb + +# Security Settings +RATE_LIMIT_WINDOW_MS=900000 +RATE_LIMIT_MAX_REQUESTS=500 +SESSION_COOKIE_SECURE=true +SESSION_COOKIE_HTTPONLY=true + +# API Settings +SWAGGER_ENABLED=true \ No newline at end of file diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md new file mode 100644 index 0000000..4fea112 --- /dev/null +++ b/DEPLOYMENT.md @@ -0,0 +1,487 @@ +# Deployment Guide + +This document provides detailed instructions for deploying the Active Directory Management Platform in various environments. + +## Table of Contents + +- [Docker Deployment](#docker-deployment) + - [Prerequisites](#prerequisites) + - [Deployment Steps](#deployment-steps) + - [Configuration](#configuration) + - [Health Monitoring](#health-monitoring) + - [Backups](#backups) + - [Scaling](#scaling) +- [Manual Deployment](#manual-deployment) + - [Prerequisites](#prerequisites-1) + - [Installation Steps](#installation-steps) + - [Service Configuration](#service-configuration) + - [Reverse Proxy Setup](#reverse-proxy-setup) +- [Cloud Deployment](#cloud-deployment) + - [AWS Deployment](#aws-deployment) + - [Azure Deployment](#azure-deployment) + - [Google Cloud Deployment](#google-cloud-deployment) +- [Production Best Practices](#production-best-practices) + - [Security Considerations](#security-considerations) + - [Performance Tuning](#performance-tuning) + - [Monitoring and Logging](#monitoring-and-logging) + - [High Availability Setup](#high-availability-setup) + +## Docker Deployment + +### Prerequisites + +- Docker Engine v20.10.0 or later +- Docker Compose v2.0.0 or later +- At least 2GB of RAM +- 10GB of disk space +- Access to LDAP/Active Directory server(s) +- Domain name with SSL certificates (recommended for production) + +### Deployment Steps + +1. **Prepare the Environment** + + Clone the repository: + ```bash + git clone https://github.com/yourusername/ad-management-platform.git + cd ad-management-platform + ``` + +2. **Configure Environment Variables** + + Create a .env file from the example: + ```bash + cp .env.example .env + ``` + + Edit the .env file with your specific configuration: + ```bash + nano .env + ``` + +3. **SSL Configuration** + + For production environments, the application is designed to work behind a reverse proxy or load balancer that handles SSL termination. + + If you need to implement SSL directly in your environment, consider: + + - Using a reverse proxy like Nginx or Traefik in front of the application + - Setting up SSL termination at the infrastructure level (e.g., using AWS Application Load Balancer) + - Configuring your cloud provider's SSL management services + +4. **Start the Application Stack** + + ```bash + docker-compose up -d + ``` + +5. **Initialize the Database** + + The first time you run the application, you need to apply migrations: + ```bash + docker-compose exec app npm run db:push + ``` + +6. **Create an Admin User** + + ```bash + docker-compose exec app npm run create-admin + ``` + +7. **Verify Deployment** + + Access the application at: + - Frontend: https://your-server-domain + - API: https://your-server-domain/api + - Swagger Documentation: https://your-server-domain/api/docs + +### Configuration + +The application is configured through environment variables defined in the .env file. Key configuration sections: + +#### Database Configuration +``` +POSTGRES_USER=admanagement +POSTGRES_PASSWORD=your_secure_password +POSTGRES_DB=admanagement +DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB} +``` + +#### Redis Configuration +``` +REDIS_URL=redis://redis:6379 +``` + +#### Application Configuration +``` +NODE_ENV=production +PORT=5000 +SESSION_SECRET=your_session_secret +JWT_SECRET=your_jwt_secret +JWT_EXPIRY=24h +``` + +#### LDAP Connection Settings +``` +LDAP_CONNECT_TIMEOUT=10000 +LDAP_IDLE_TIMEOUT=60000 +LDAP_RECONNECT_TIMEOUT=10000 +``` + +### Health Monitoring + +The application provides health check endpoints: + +- **API Health**: `https://your-server-domain/api/health` +- **Database Health**: `https://your-server-domain/api/health/db` +- **Redis Health**: `https://your-server-domain/api/health/redis` +- **LDAP Health**: `https://your-server-domain/api/health/ldap` + +These endpoints can be used with monitoring tools like Prometheus, Grafana, or cloud provider health checks. + +### Backups + +#### Database Backups + +Use the following command to backup the PostgreSQL database: + +```bash +docker-compose exec postgres pg_dump -U ${POSTGRES_USER} ${POSTGRES_DB} > backup_$(date +%Y%m%d%H%M%S).sql +``` + +Set up a cron job for regular backups: + +```bash +0 2 * * * cd /path/to/ad-management-platform && docker-compose exec -T postgres pg_dump -U ${POSTGRES_USER} ${POSTGRES_DB} > backups/backup_$(date +%Y%m%d%H%M%S).sql +``` + +#### Restore from Backup + +```bash +cat backup_file.sql | docker-compose exec -T postgres psql -U ${POSTGRES_USER} ${POSTGRES_DB} +``` + +### Scaling + +For higher loads, consider scaling the application: + +1. **Horizontal Scaling**: + - Modify docker-compose.yml to add more application instances + - Set up load balancing with an appropriate solution for your environment + +2. **Vertical Scaling**: + - Allocate more resources to containers + - Optimize database and Redis configurations + +3. **Database Scaling**: + - Consider PostgreSQL replication for read-heavy workloads + - Implement connection pooling + +## Manual Deployment + +### Prerequisites + +- Node.js v18 or later +- PostgreSQL v13 or later +- Redis v6 or later +- PM2 or systemd for process management +- (Optional) A reverse proxy for production environments + +### Installation Steps + +1. **System Preparation** + + Update system packages and install dependencies: + ```bash + apt update && apt upgrade -y + apt install -y curl git build-essential + ``` + +2. **Install Node.js** + + ```bash + curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - + apt install -y nodejs + ``` + +3. **Install PostgreSQL** + + ```bash + apt install -y postgresql postgresql-contrib + ``` + + Create a database and user: + ```bash + sudo -u postgres psql -c "CREATE USER admanagement WITH PASSWORD 'your_secure_password';" + sudo -u postgres psql -c "CREATE DATABASE admanagement OWNER admanagement;" + ``` + +4. **Install Redis** + + ```bash + apt install -y redis-server + ``` + + Configure Redis: + ```bash + sed -i 's/supervised no/supervised systemd/g' /etc/redis/redis.conf + systemctl restart redis + ``` + +5. **Clone and Configure the Application** + + ```bash + git clone https://github.com/yourusername/ad-management-platform.git /opt/ad-management + cd /opt/ad-management + npm install --production + ``` + + Create and configure .env file: + ```bash + cp .env.example .env + nano .env + ``` + +6. **Build the Application** + + ```bash + npm run build + ``` + +7. **Set Up Database** + + ```bash + npm run db:push + ``` + +8. **Create Admin User** + + ```bash + npm run create-admin + ``` + +9. **Set Up Process Management with PM2** + + Install PM2: + ```bash + npm install -g pm2 + ``` + + Create a process file (ecosystem.config.js): + ```bash + cat > ecosystem.config.js << EOF + module.exports = { + apps: [{ + name: 'ad-management', + script: 'dist/server/index.js', + instances: 'max', + exec_mode: 'cluster', + env: { + NODE_ENV: 'production' + } + }] + }; + EOF + ``` + + Start the application: + ```bash + pm2 start ecosystem.config.js + pm2 save + pm2 startup + ``` + +### Service Configuration + +Alternatively, you can use systemd for process management: + +```bash +cat > /etc/systemd/system/ad-management.service << EOF +[Unit] +Description=Active Directory Management Platform +After=network.target postgresql.service redis.service + +[Service] +Type=simple +User=www-data +WorkingDirectory=/opt/ad-management +ExecStart=/usr/bin/node dist/server/index.js +Restart=on-failure +Environment=NODE_ENV=production +Environment=PORT=5000 + +[Install] +WantedBy=multi-user.target +EOF +``` + +Enable and start the service: +```bash +systemctl enable ad-management +systemctl start ad-management +``` + +### Reverse Proxy Setup (Optional) + +In production, you may choose to place your application behind a reverse proxy for SSL termination, load balancing, or additional security. Options include: + +#### Common Reverse Proxy Options + +1. **Nginx** - Lightweight, high-performance web server and reverse proxy +2. **Apache** - Full-featured web server with mod_proxy +3. **Traefik** - Modern, auto-configuring reverse proxy designed for microservices +4. **HAProxy** - High-performance TCP/HTTP load balancer +5. **Caddy** - Modern web server with automatic HTTPS + +Key configurations to include when setting up a reverse proxy: + +1. **SSL Termination** - Handle HTTPS traffic and forward to your application +2. **Security Headers** - Add headers like X-Frame-Options, X-XSS-Protection, and Content-Security-Policy +3. **Caching** - Configure appropriate caching for static assets +4. **Compression** - Enable gzip/brotli compression for faster content delivery +5. **WebSocket Support** - Ensure WebSocket connections are properly handled +6. **Health Checks** - Configure checks to detect application failures + +For specific configuration examples, refer to the documentation for your chosen reverse proxy. + +## Cloud Deployment + +### AWS Deployment + +For deployment on AWS, you can use several approaches: + +1. **EC2 Instances**: + - Launch EC2 instances (t3.medium or higher recommended) + - Set up the application using either Docker or manual deployment methods + - Use Amazon RDS for PostgreSQL + - Use Amazon ElastiCache for Redis + - Configure Application Load Balancer for high availability + +2. **ECS/Fargate**: + - Create a task definition using the Dockerfile + - Set up an ECS cluster with Fargate + - Configure Auto Scaling + - Use RDS for PostgreSQL + - Use ElastiCache for Redis + +3. **EKS (Kubernetes)**: + - Use Kubernetes manifests or Helm charts + - Deploy to Amazon EKS + - Use RDS for PostgreSQL + - Use ElastiCache for Redis + +Detailed AWS deployment instructions can be found in [AWS_DEPLOYMENT.md](AWS_DEPLOYMENT.md). + +### Azure Deployment + +For deployment on Microsoft Azure: + +1. **Virtual Machines**: + - Deploy to Azure VMs + - Follow Docker or manual deployment procedures + +2. **App Service**: + - Deploy as a containerized application + - Use Azure Database for PostgreSQL + - Use Azure Cache for Redis + +3. **Azure Kubernetes Service (AKS)**: + - Deploy using Kubernetes manifests + - Use managed PostgreSQL and Redis services + +Detailed Azure deployment instructions can be found in [AZURE_DEPLOYMENT.md](AZURE_DEPLOYMENT.md). + +### Google Cloud Deployment + +For deployment on Google Cloud Platform: + +1. **Compute Engine**: + - Deploy to Compute Engine VMs + - Follow Docker or manual deployment procedures + +2. **Google Kubernetes Engine (GKE)**: + - Deploy using Kubernetes manifests + - Use Cloud SQL for PostgreSQL + - Use Memorystore for Redis + +3. **Cloud Run**: + - Deploy as a containerized application + - Use Cloud SQL for PostgreSQL + - Use Memorystore for Redis + +Detailed GCP deployment instructions can be found in [GCP_DEPLOYMENT.md](GCP_DEPLOYMENT.md). + +## Production Best Practices + +### Security Considerations + +1. **Secrets Management**: + - Never store secrets in the codebase + - Use environment variables or a secrets manager + - Rotate credentials regularly + +2. **Network Security**: + - Use HTTPS everywhere + - Implement proper firewall rules + - Consider using a Web Application Firewall (WAF) + +3. **Authentication and Authorization**: + - Enforce strong password policies + - Implement multi-factor authentication + - Apply the principle of least privilege + +4. **Regular Updates**: + - Keep all dependencies up to date + - Apply security patches promptly + - Enable automatic updates where possible + +### Performance Tuning + +1. **Database Optimization**: + - Index frequently queried fields + - Monitor query performance + - Optimize slow queries + +2. **Caching Strategy**: + - Configure appropriate TTL values + - Cache frequently accessed data + - Use Redis cache for session storage + +3. **Application Performance**: + - Use compression for HTTP responses + - Implement efficient pagination + - Optimize JavaScript bundle size + +### Monitoring and Logging + +1. **Application Monitoring**: + - Use monitoring solutions like Prometheus + Grafana + - Set up alerts for critical metrics + - Monitor application health endpoints + +2. **Logging**: + - Implement structured logging + - Use a central log management solution + - Set up log rotation + +3. **Error Tracking**: + - Implement error tracking with services like Sentry + - Set up alerts for critical errors + - Regularly review error logs + +### High Availability Setup + +1. **Load Balancing**: + - Deploy multiple application instances + - Use a load balancer to distribute traffic + - Implement health checks + +2. **Database High Availability**: + - Set up PostgreSQL replication + - Implement automated failover + - Regularly test failover procedures + +3. **Backup and Recovery**: + - Implement automated database backups + - Test restore procedures regularly + - Store backups in multiple locations \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..1a30008 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,52 @@ +FROM node:20-alpine AS builder + +# Set working directory +WORKDIR /app + +# Copy package.json and package-lock.json +COPY package*.json ./ + +# Install dependencies +RUN npm ci + +# Copy project files +COPY . . + +# Build the application +RUN npm run build + +# Production image +FROM node:20-alpine AS production + +# Set working directory +WORKDIR /app + +# Set environment variables +ENV NODE_ENV=production +ENV PORT=5000 + +# Copy package files +COPY package*.json ./ + +# Install production dependencies only +RUN npm ci --only=production + +# Copy built application from builder stage +COPY --from=builder /app/dist ./dist +COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma + +# Copy migration files +COPY --from=builder /app/migrations ./migrations + +# Create a non-root user and set ownership +RUN addgroup -S appgroup && adduser -S appuser -G appgroup +RUN chown -R appuser:appgroup /app + +# Switch to non-root user +USER appuser + +# Expose the port the app runs on +EXPOSE 5000 + +# Start the application +CMD ["node", "dist/server/index.js"] \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..91c0b5e --- /dev/null +++ b/README.md @@ -0,0 +1,231 @@ +# Active Directory Management Platform + +A comprehensive REST API and admin interface for Active Directory management, designed for efficient user and resource management with advanced configuration and monitoring capabilities. + +## Table of Contents + +- [Features](#features) +- [Technology Stack](#technology-stack) +- [Architecture](#architecture) +- [Installation](#installation) + - [Prerequisites](#prerequisites) + - [Development Setup](#development-setup) + - [Production Deployment](#production-deployment) +- [API Documentation](#api-documentation) +- [Configuration](#configuration) +- [LDAP Query Builder](#ldap-query-builder) +- [Contributing](#contributing) +- [License](#license) + +## Features + +The Active Directory Management Platform provides the following key features: + +### Core Functionality +- **User Management**: Create, read, update, and delete Active Directory users with comprehensive attribute support +- **Group Management**: Manage security and distribution groups, including nested group structures +- **Organizational Unit (OU) Management**: Create and manage the hierarchical OU structure +- **Computer Management**: Manage computer accounts with detailed property configuration +- **Domain Management**: View and configure domain controllers and settings + +### Administration +- **API Token Management**: Create and manage API tokens for secure programmatic access +- **LDAP Connection Management**: Configure and test multiple LDAP server connections +- **Role-Based Access Control**: Granular permissions system for secure delegation of administrative tasks +- **User Management**: Admin interface for managing platform users and their permissions + +### Advanced Features +- **LDAP Query Builder**: Visual interface for building, testing, and saving complex LDAP queries + - Filter version history with revision control + - Revert to previous filter versions + - Test filters against live Active Directory data + - Save frequently used filters for reuse +- **API Filtering**: Dynamic property filtering on all API endpoints +- **Bulk Operations**: Efficient batch processing for operations on multiple directory objects +- **Audit Logging**: Comprehensive audit trail for all directory changes +- **Caching**: Redis-based caching for improved performance + +## Technology Stack + +### Backend +- **Express.js**: Fast, unopinionated, minimalist web framework for Node.js +- **PostgreSQL**: Advanced open-source relational database with JSON support +- **Drizzle ORM**: Type-safe SQL query builder and ORM for TypeScript +- **Redis**: In-memory data structure store used for caching +- **Passport.js**: Authentication middleware for Node.js +- **Swagger/OpenAPI**: API documentation and specification + +### Frontend +- **React**: JavaScript library for building user interfaces +- **Material UI**: React components that implement Google's Material Design +- **React Query**: Powerful data synchronization for React applications +- **Recharts**: Composable charting library built on React components +- **React Hook Form**: Performant forms with easy-to-use validation + +### DevOps +- **Docker**: Containerization platform for consistent deployment + +## Architecture + +The application follows a modern web architecture with clear separation of concerns: + +1. **Client Layer**: React-based SPA that provides the user interface +2. **API Layer**: Express.js REST API with comprehensive endpoint coverage +3. **Service Layer**: Business logic implementation with domain-specific services +4. **Data Access Layer**: Database interaction through Drizzle ORM +5. **Infrastructure Layer**: PostgreSQL database, Redis cache, and LDAP connectivity + +## Installation + +### Prerequisites + +- Node.js v18 or later +- PostgreSQL v13 or later +- Redis v6 or later +- Docker and Docker Compose (for containerized deployment) + +### Development Setup + +1. Clone the repository: + ```bash + git clone https://github.com/yourusername/ad-management-platform.git + cd ad-management-platform + ``` + +2. Install dependencies: + ```bash + npm install + ``` + +3. Create a .env file from the example: + ```bash + cp .env.example .env + # Edit .env with your configuration + ``` + +4. Set up the database: + ```bash + npm run db:push + ``` + +5. Start the development server: + ```bash + npm run dev + ``` + +6. The application will be available at: + - Frontend: http://localhost:5000 + - API: http://localhost:5000/api + - Swagger Documentation: http://localhost:5000/api/docs + +### Production Deployment + +#### Using Docker Compose + +1. Clone the repository: + ```bash + git clone https://github.com/yourusername/ad-management-platform.git + cd ad-management-platform + ``` + +2. Create a .env file from the example: + ```bash + cp .env.example .env + # Edit .env with your production configuration + ``` + +3. Set up environment variables for production: + ```bash + # Make sure to set appropriate values in your .env file + # For production deployments, ensure secure values for SESSION_SECRET and other security settings + ``` + +4. Start the application stack: + ```bash + docker-compose up -d + ``` + +5. The application will be available at: + - Frontend: https://your-server-domain + - API: https://your-server-domain/api + - Swagger Documentation: https://your-server-domain/api/docs + +#### Manual Deployment + +For manual deployment instructions, refer to the [Deployment Guide](DEPLOYMENT.md). + +## API Documentation + +The API is thoroughly documented using the OpenAPI specification (Swagger): + +- **Interactive Documentation**: Available at `/api/docs` when the application is running +- **Downloadable Specification**: Available at `/api/docs/download` +- **Advanced Usage Guide**: Available at `/api/docs/more-info` + +### API Standards + +- **Authentication**: JWT tokens via Authorization header +- **Request Format**: JSON with proper content-type headers +- **Response Format**: Consistent JSON structure with appropriate status codes +- **Error Handling**: Descriptive error messages and appropriate HTTP status codes + +### Filterable Endpoints + +All list endpoints support filtering with a flexible query syntax: + +``` +GET /api/users?filter[firstName]=John&filter[lastName]=Doe +GET /api/groups?filter[description]=contains:Marketing +``` + +## Configuration + +Configuration is managed through environment variables. See [.env.example](.env.example) for a complete list of available options. + +### Key Configuration Options + +- **Database**: PostgreSQL connection settings +- **Redis**: Caching configuration +- **Session**: Security settings for user sessions +- **JWT**: Settings for API tokens +- **LDAP**: Connection parameters for Active Directory +- **Rate Limiting**: API request restrictions +- **Logging**: Debug and audit log configuration + +## LDAP Query Builder + +The LDAP Query Builder is an advanced feature that helps administrators construct complex LDAP queries through a visual interface. + +### Features + +- **Visual Query Construction**: Build LDAP filters without knowing the exact syntax +- **Object Class Selection**: Pre-configured attribute lists based on Active Directory object classes +- **Condition Groups**: Create complex queries with nested AND/OR logic +- **Live Preview**: See the generated LDAP filter syntax as you build +- **Testing**: Execute the query against your Active Directory to validate results +- **Saving**: Store frequently used queries for later use +- **Version History**: Track changes to queries with full revision history +- **Rollback**: Revert to previous versions if needed + +### Usage + +1. Navigate to the LDAP Query Builder page from the main navigation +2. Select a connection and object class +3. Build your filter by adding conditions or groups +4. Test the filter to see results +5. Save the filter with a descriptive name +6. Access saved filters for later use or sharing + +## Contributing + +Contributions are welcome! Please feel free to submit a Pull Request. + +1. Fork the repository +2. Create your feature branch (`git checkout -b feature/amazing-feature`) +3. Commit your changes (`git commit -m 'Add some amazing feature'`) +4. Push to the branch (`git push origin feature/amazing-feature`) +5. Open a Pull Request + +## License + +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. \ No newline at end of file diff --git a/client/src/components/theme-toggle.tsx b/client/src/components/theme-toggle.tsx new file mode 100644 index 0000000..60fa977 --- /dev/null +++ b/client/src/components/theme-toggle.tsx @@ -0,0 +1,40 @@ +import * as React from "react"; +import { Moon, Sun, Laptop } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { useTheme } from "@/hooks/use-theme"; + +export function ThemeToggle() { + const { theme, setTheme } = useTheme(); + + return ( + + + + + + setTheme("light")}> + + Light + + setTheme("dark")}> + + Dark + + setTheme("system")}> + + System + + + + ); +} \ No newline at end of file diff --git a/client/src/hooks/use-theme.tsx b/client/src/hooks/use-theme.tsx new file mode 100644 index 0000000..ba42e4e --- /dev/null +++ b/client/src/hooks/use-theme.tsx @@ -0,0 +1,66 @@ +import { createContext, useContext, useEffect, useState, ReactNode } from 'react'; + +type Theme = 'dark' | 'light' | 'system'; + +interface ThemeContextType { + theme: Theme; + setTheme: (theme: Theme) => void; +} + +const ThemeContext = createContext(undefined); + +interface ThemeProviderProps { + children: ReactNode; + defaultTheme?: Theme; + storageKey?: string; +} + +export function ThemeProvider({ + children, + defaultTheme = 'system', + storageKey = 'ui-theme', + ...props +}: ThemeProviderProps) { + const [theme, setTheme] = useState( + () => (localStorage.getItem(storageKey) as Theme) || defaultTheme + ); + + useEffect(() => { + const root = window.document.documentElement; + root.classList.remove('light', 'dark'); + + if (theme === 'system') { + const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches + ? 'dark' + : 'light'; + + root.classList.add(systemTheme); + return; + } + + root.classList.add(theme); + }, [theme]); + + const value = { + theme, + setTheme: (theme: Theme) => { + localStorage.setItem(storageKey, theme); + setTheme(theme); + }, + }; + + return ( + + {children} + + ); +} + +export const useTheme = (): ThemeContextType => { + const context = useContext(ThemeContext); + + if (context === undefined) + throw new Error('useTheme must be used within a ThemeProvider'); + + return context; +}; \ No newline at end of file diff --git a/client/src/index.css b/client/src/index.css index 2439cdb..7537a16 100644 --- a/client/src/index.css +++ b/client/src/index.css @@ -88,6 +88,32 @@ --border: 240 3.7% 15.9%; --input: 240 3.7% 15.9%; --ring: 142.4 71.8% 29.2%; + + --sidebar-background: 20 14.3% 4.1%; + --sidebar-foreground: 0 0% 95%; + --sidebar-primary: 221.2 83.2% 53.3%; + --sidebar-primary-foreground: 210 40% 98%; + --sidebar-accent: 240 3.7% 15.9%; + --sidebar-accent-foreground: 0 0% 98%; + --sidebar-border: 240 3.7% 15.9%; + --sidebar-ring: 142.4 71.8% 29.2%; + } + + /* Smooth theme transition */ + *, + ::before, + ::after { + transition-property: color, background-color, border-color, text-decoration-color, fill, stroke; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 300ms; + } + + /* Exclude transitions for specific elements that shouldn't animate */ + .no-transition, + .no-transition *, + .no-transition::before, + .no-transition::after { + transition: none !important; } * { diff --git a/client/src/layouts/dashboard-layout.tsx b/client/src/layouts/dashboard-layout.tsx index 785c2d7..7542400 100644 --- a/client/src/layouts/dashboard-layout.tsx +++ b/client/src/layouts/dashboard-layout.tsx @@ -32,6 +32,7 @@ import { } from "lucide-react"; import { useMobile } from "@/hooks/use-mobile"; import { useToast } from "@/hooks/use-toast"; +import { ThemeToggle } from "@/components/theme-toggle"; type MenuItem = { title: string; @@ -157,7 +158,7 @@ export function DashboardLayout({ children, title, description }: DashboardLayou
{/* Sidebar */}
@@ -206,7 +207,7 @@ export function DashboardLayout({ children, title, description }: DashboardLayou {/* Main Content */}
{/* Top App Bar */} -
+
@@ -265,8 +268,8 @@ export function DashboardLayout({ children, title, description }: DashboardLayou {/* Main Content Area */}
-

{title}

- {description &&

{description}

} +

{title}

+ {description &&

{description}

}
{children} diff --git a/client/src/main.tsx b/client/src/main.tsx index cf28a4f..48d6243 100644 --- a/client/src/main.tsx +++ b/client/src/main.tsx @@ -3,12 +3,15 @@ import { QueryClientProvider } from "@tanstack/react-query"; import App from "./App"; import "./index.css"; import { AuthProvider } from "./hooks/use-auth"; +import { ThemeProvider } from "./hooks/use-theme"; import { queryClient } from "./lib/queryClient"; createRoot(document.getElementById("root")!).render( - - - + + + + + ); diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..2d3bc01 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,72 @@ +services: + app: + build: + context: . + dockerfile: Dockerfile + container_name: ad-management-api + restart: unless-stopped + ports: + - "5000:5000" + environment: + - NODE_ENV=production + - PORT=5000 + - DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB} + - REDIS_URL=redis://redis:6379 + - SESSION_SECRET=${SESSION_SECRET} + depends_on: + - postgres + - redis + networks: + - app-network + healthcheck: + test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:5000/api/health"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 30s + + postgres: + image: postgres:15-alpine + container_name: ad-management-postgres + restart: unless-stopped + environment: + - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} + - POSTGRES_USER=${POSTGRES_USER} + - POSTGRES_DB=${POSTGRES_DB} + volumes: + - postgres-data:/var/lib/postgresql/data + ports: + - "5432:5432" + networks: + - app-network + healthcheck: + test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"] + interval: 10s + timeout: 5s + retries: 5 + start_period: 10s + + redis: + image: redis:7-alpine + container_name: ad-management-redis + restart: unless-stopped + command: redis-server --appendonly yes + volumes: + - redis-data:/data + ports: + - "6379:6379" + networks: + - app-network + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 10s + timeout: 5s + retries: 5 + +networks: + app-network: + driver: bridge + +volumes: + postgres-data: + redis-data: \ No newline at end of file diff --git a/docs/LDAP_QUERY_BUILDER.md b/docs/LDAP_QUERY_BUILDER.md new file mode 100644 index 0000000..c2b3985 --- /dev/null +++ b/docs/LDAP_QUERY_BUILDER.md @@ -0,0 +1,194 @@ +# LDAP Query Builder Documentation + +The LDAP Query Builder is a powerful feature that allows administrators to visually construct, test, save, and manage complex LDAP filters without requiring specialized knowledge of LDAP filter syntax. + +## Table of Contents + +- [Overview](#overview) +- [Getting Started](#getting-started) +- [User Interface](#user-interface) +- [Building Queries](#building-queries) + - [Basic Conditions](#basic-conditions) + - [Condition Groups](#condition-groups) + - [Operators](#operators) + - [Generated LDAP Filter](#generated-ldap-filter) +- [Testing Filters](#testing-filters) +- [Saving and Managing Filters](#saving-and-managing-filters) +- [Version History](#version-history) +- [Advanced Usage](#advanced-usage) +- [Troubleshooting](#troubleshooting) +- [Best Practices](#best-practices) + +## Overview + +LDAP (Lightweight Directory Access Protocol) is used to query and modify directory services, but writing complex LDAP filters requires specialized knowledge of the syntax. The LDAP Query Builder provides a visual interface to simplify this process, allowing administrators to: + +- Create complex filters through a user-friendly interface +- Test filters against live Active Directory data +- Save frequently used filters for reuse +- Track changes with version history +- Revert to previous versions when needed + +## Getting Started + +To access the LDAP Query Builder: + +1. Log in to the Active Directory Management Platform +2. Navigate to **Administration** in the sidebar +3. Click on **LDAP Query Builder** + +You'll need at least one configured LDAP connection before you can use the Query Builder. If you haven't set up a connection yet, go to **LDAP Connections** first. + +## User Interface + +The LDAP Query Builder interface consists of several key sections: + +1. **Connection Settings**: Select an LDAP connection and object class +2. **Filter Builder**: Create and edit the filter conditions +3. **Generated Filter**: View the resulting LDAP filter syntax +4. **Saved Filters**: Access previously saved filters +5. **Test Results**: View the results when testing a filter + +## Building Queries + +### Basic Conditions + +To build a query: + +1. Select a connection and object class (e.g., User, Group, Computer) +2. Enter a name and optional description for your filter +3. Click **Add Condition** to add your first condition +4. For each condition, select: + - **Attribute**: The Active Directory attribute to filter by + - **Operator**: How to match the attribute (equals, contains, etc.) + - **Value**: The value to match against (not required for exists/not exists) + +Example: Finding users with "Smith" in their last name: +- Attribute: `sn` (surname) +- Operator: `contains` +- Value: `Smith` + +### Condition Groups + +For more complex queries, you can use condition groups: + +1. Choose the filter type at the top: + - **Match ALL conditions (AND)**: All conditions must be true + - **Match ANY condition (OR)**: Any condition can be true +2. Add multiple conditions as needed +3. Use the **Add Group** button to create nested logic (limited in current version) + +### Operators + +The following operators are available: + +| Operator | Description | LDAP Equivalent | +|----------|-------------|-----------------| +| Equals | Exact match | (attribute=value) | +| Not equals | Negated exact match | (!(attribute=value)) | +| Contains | Value appears anywhere | (attribute=*value*) | +| Starts with | Value appears at beginning | (attribute=value*) | +| Ends with | Value appears at end | (attribute=*value) | +| Exists | Attribute is present | (attribute=*) | +| Not exists | Attribute is not present | (!(attribute=*)) | + +### Generated LDAP Filter + +As you build your query, the system automatically generates the corresponding LDAP filter syntax in the "Generated LDAP Filter" field. Advanced users can modify this syntax directly, but be aware that manual edits won't be reflected in the visual builder. + +## Testing Filters + +To test a filter against your Active Directory: + +1. Build your filter as described above +2. Click the **Test Filter** button +3. View the matching results in the "Test Results" tab +4. The results show objects that match your filter criteria + +The test results display key attributes such as names and distinguished names (DNs). + +## Saving and Managing Filters + +To save a filter for later use: + +1. Enter a descriptive name in the "Filter Name" field +2. Optionally add a description +3. Click the **Save Filter** button + +To manage saved filters: + +1. View your saved filters in the "Saved Filters" tab +2. Click the pencil icon to edit a filter +3. Click the trash icon to delete a filter +4. Click on a filter row to select it for viewing or editing + +## Version History + +The system automatically maintains a version history for each filter: + +1. When editing a saved filter, click the **Show History** button +2. View the revision history, including version numbers, timestamps, and comments +3. To revert to a previous version, click the **Revert to this version** button +4. Confirm the revert action in the confirmation dialog + +When you revert to a previous version, a new revision is created with the reverted content, preserving the full history. + +## Advanced Usage + +### Direct LDAP Syntax Editing + +Advanced users can edit the generated LDAP filter syntax directly: + +1. Make changes in the "Generated LDAP Filter" field +2. Be aware that manual edits won't update the visual builder interface +3. The manually edited filter will still be used when testing or saving + +### Complex Filters with Nested Logic + +While the current version has limited support for deeply nested conditions, you can create complex filters by: + +1. Using the top-level AND/OR operator effectively +2. Adding multiple simple conditions +3. Using selective attribute queries +4. For very complex queries, consider direct LDAP syntax editing + +## Troubleshooting + +Common issues and solutions: + +### No Test Results + +If your filter doesn't return any results: +- Check that the attribute names are correct +- Verify the values you're searching for +- Ensure the object class is appropriate for the attributes +- Check the LDAP connection status +- Try a simpler query first to verify connectivity + +### Syntax Errors + +If your filter has syntax errors: +- Look for unmatched parentheses +- Check attribute names for typos +- Ensure values are properly formatted + +### Performance Issues + +If queries are slow: +- Avoid wildcard searches at the beginning of values when possible +- Use more specific filters +- Check if the attributes you're filtering on are indexed +- Limit result sets with more specific criteria + +## Best Practices + +For effective use of the LDAP Query Builder: + +1. **Use descriptive names**: Make filter names clear and descriptive +2. **Add helpful descriptions**: Document the purpose and expected results +3. **Start simple**: Begin with simple conditions and build complexity gradually +4. **Test thoroughly**: Always test filters before deploying them +5. **Use version comments**: Add meaningful comments when updating filters +6. **Organize filters logically**: Create separate filters for different purposes +7. **Use AND/OR appropriately**: Understand how condition logic affects results +8. **Be specific**: More specific filters perform better and return more relevant results \ No newline at end of file