@well-prado/blok-admin-dashboard
v1.0.14
Published
Complete admin dashboard system for Blok Framework applications with authentication, user management, and security features
Maintainers
Readme
@well-prado/blok-admin-dashboard
Complete admin dashboard with authentication, user management, security, and database operations for Blok Framework.
Overview
The @well-prado/blok-admin-dashboard is a comprehensive backend solution that provides everything you need to build secure, scalable admin applications. It includes 25+ pre-built nodes, 15+ workflows, complete authentication system, user management, security features, and database operations.
Features
- 🔐 Complete Authentication System - Login, register, session management, password reset
- 👥 User Management - CRUD operations, role management, profile updates
- 🛡️ Advanced Security - Rate limiting, audit logging, request interception, 2FA
- 📊 Database Operations - SQLite with Drizzle ORM, migrations, schemas
- 📧 Email Integration - Templated emails, verification, notifications
- 🔍 Workflow Discovery - Automatic API documentation and type generation
- 📝 Audit Logging - Complete activity tracking and system logs
- ⚡ High Performance - Optimized queries, caching, connection pooling
Installation
npm install @well-prado/blok-admin-dashboardOr use the CLI for automatic setup:
npx @well-prado/blok-cli install admin-dashboardQuick Start
1. Basic Setup
// src/index.ts
import { AdminDashboard } from "@well-prado/blok-admin-dashboard";
const dashboard = new AdminDashboard({
database: {
url: "file:./database/app.db",
},
auth: {
sessionDuration: 3600, // 1 hour
requireEmailVerification: true,
},
security: {
rateLimiting: true,
auditLogging: true,
},
});
// Start the server
dashboard.start(4000);2. With Custom Configuration
import { AdminDashboard, AdminConfig } from "@well-prado/blok-admin-dashboard";
const config: AdminConfig = {
database: {
url: process.env.DATABASE_URL || "file:./database/app.db",
enableWAL: true,
connectionPooling: true,
},
auth: {
sessionDuration: 7200, // 2 hours
passwordMinLength: 8,
requireEmailVerification: false,
allowRegistration: true,
},
security: {
rateLimiting: {
enabled: true,
windowMs: 15 * 60 * 1000, // 15 minutes
maxRequests: 100,
},
auditLogging: true,
requestInterception: true,
},
email: {
provider: "smtp",
config: {
host: process.env.SMTP_HOST,
port: parseInt(process.env.SMTP_PORT || "587"),
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
},
},
};
const dashboard = new AdminDashboard(config);
dashboard.start(process.env.PORT || 4000);Architecture
Node Categories
The package includes 25+ nodes organized into 8 categories:
🔐 Authentication Nodes (7 nodes)
authentication-checker- Validates user sessions and permissionspassword-hash- Secure password hashing with bcryptpassword-verify- Password verification and validationuser-login- User login with session creationuser-logout- Session cleanup and logoutuser-register- New user registration with validation
👥 Database Nodes (4 nodes)
user-find- Find users by various criteriauser-list- Paginated user listings with filteringuser-update- Update user information with validationuser-delete- Safe user deletion with audit trail
🛡️ Security Nodes (6 nodes)
audit-logger- Log all system activitiesrate-limiter- Prevent abuse with configurable limitsrequest-interceptor- Inspect and modify requestssystem-action-logger- Track administrative actionstwo-factor-auth- TOTP-based 2FA implementation
✅ Validation Nodes (3 nodes)
email-validator- Email format and domain validationinput-sanitizer- Clean and sanitize user inputspassword-validator- Password strength validation
📧 Email Nodes (3 nodes)
EmailServiceManager- Multi-provider email handlingEmailTemplates- Template management and renderingEmailVerification- Email verification workflows
📊 Profile Nodes (3 nodes)
profile-image-upload- Handle avatar uploadstheme-preference-update- User theme preferencesuser-profile-update- Complete profile management
🔍 Meta Nodes (2 nodes)
workflow-discovery- Automatic API documentation
🔔 Notification Nodes (5 nodes)
clear-all-notifications- Bulk notification managementcreate-notification- Create system notificationsget-user-notifications- Fetch user notificationsmark-notification-read- Mark notifications as read
Workflow Categories
The package includes 15+ workflows organized by functionality:
Authentication Workflows
auth/login- User login with session creationauth/logout- Session cleanupauth/register- User registrationauth/verify-session- Session validationauth/protected-example- Protected route example
Admin Workflows
admin/dashboard- Admin dashboard dataadmin/user-management- User CRUD operationsadmin/user-role-management- Role assignmentsadmin/admin-logs- System activity logs
Profile Workflows
profile/profile-update- User profile updatesprofile/profile-image-upload- Avatar managementprofile/theme-preferences- Theme settings
Security Workflows
security/audit-logs- Security event logssecurity/two-factor-auth- 2FA setup and verificationsecurity/rate-limit-test- Rate limiting demonstrations
Database Schema
The package includes complete database schemas with migrations:
Users Table
CREATE TABLE users (
id TEXT PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
name TEXT NOT NULL,
role TEXT DEFAULT 'user',
avatar TEXT,
email_verified BOOLEAN DEFAULT FALSE,
theme_preference TEXT DEFAULT 'system',
notification_preferences TEXT DEFAULT '{}',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);Sessions Table
CREATE TABLE sessions (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
expires_at DATETIME NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);Audit Logs Table
CREATE TABLE audit_logs (
id TEXT PRIMARY KEY,
user_id TEXT,
action TEXT NOT NULL,
resource TEXT,
resource_id TEXT,
details TEXT,
ip_address TEXT,
user_agent TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);System Logs Table
CREATE TABLE system_logs (
id TEXT PRIMARY KEY,
level TEXT NOT NULL,
message TEXT NOT NULL,
category TEXT,
user_id TEXT,
session_id TEXT,
metadata TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);API Endpoints
Authentication Endpoints
POST /auth/login
Login with email and password.
Request:
{
"email": "[email protected]",
"password": "securepassword"
}Response:
{
"success": true,
"data": {
"user": {
"id": "user_123",
"email": "[email protected]",
"name": "John Doe",
"role": "user"
},
"session": {
"id": "session_456",
"expiresAt": "2024-01-01T12:00:00Z"
}
}
}POST /auth/register
Register a new user.
Request:
{
"email": "[email protected]",
"password": "securepassword",
"name": "Jane Doe"
}POST /auth/logout
Logout and destroy session.
Request:
{
"sessionId": "session_456"
}User Management Endpoints
GET /admin/users
Get paginated list of users (admin only).
Query Parameters:
page- Page number (default: 1)limit- Items per page (default: 10)search- Search termrole- Filter by role
Response:
{
"success": true,
"data": {
"users": [...],
"pagination": {
"page": 1,
"limit": 10,
"total": 50,
"totalPages": 5
}
}
}PUT /admin/users/:id
Update user information (admin only).
DELETE /admin/users/:id
Delete user (admin only).
Profile Endpoints
GET /profile
Get current user profile.
PUT /profile
Update current user profile.
Request:
{
"name": "Updated Name",
"themePreference": "dark",
"notificationPreferences": {
"email": true,
"push": false
}
}POST /profile/avatar
Upload profile avatar.
Security Endpoints
GET /admin/audit-logs
Get audit logs (admin only).
GET /admin/system-logs
Get system logs (admin only).
POST /security/2fa/setup
Setup two-factor authentication.
POST /security/2fa/verify
Verify 2FA token.
Configuration Options
Complete Configuration
interface AdminConfig {
// Database configuration
database: {
url: string;
enableWAL?: boolean;
connectionPooling?: boolean;
maxConnections?: number;
queryTimeout?: number;
};
// Authentication settings
auth: {
sessionDuration?: number; // seconds
passwordMinLength?: number;
passwordRequireSpecialChar?: boolean;
requireEmailVerification?: boolean;
allowRegistration?: boolean;
maxLoginAttempts?: number;
lockoutDuration?: number; // seconds
};
// Security configuration
security: {
rateLimiting?: {
enabled: boolean;
windowMs: number;
maxRequests: number;
};
auditLogging?: boolean;
requestInterception?: boolean;
corsOrigins?: string[];
trustedProxies?: string[];
};
// Email configuration
email: {
provider: "smtp" | "sendgrid" | "mailgun";
config: {
// SMTP configuration
host?: string;
port?: number;
secure?: boolean;
auth?: {
user: string;
pass: string;
};
// Or API key for other providers
apiKey?: string;
};
templates?: {
welcome?: string;
passwordReset?: string;
emailVerification?: string;
};
};
// Server configuration
server: {
port?: number;
host?: string;
cors?: {
origin: string | string[];
credentials: boolean;
};
bodyParser?: {
limit: string;
};
};
}Advanced Usage
Custom Nodes
Extend the dashboard with custom nodes:
import { AdminDashboard, BaseNode } from "@well-prado/blok-admin-dashboard";
class CustomReportNode extends BaseNode {
async handle(input: any) {
// Custom logic here
return {
success: true,
data: { report: "Generated report data" },
};
}
}
const dashboard = new AdminDashboard(config);
dashboard.registerNode("custom-report", CustomReportNode);Custom Workflows
Add custom workflows:
const customWorkflow = {
name: "custom-analytics",
steps: [
{
node: "authentication-checker",
config: { requireAuth: true, requiredRole: "admin" },
},
{
node: "custom-report",
config: { reportType: "analytics" },
},
],
};
dashboard.registerWorkflow(customWorkflow);Middleware
Add custom middleware:
dashboard.use((req, res, next) => {
console.log(`${req.method} ${req.path}`);
next();
});
// Authentication middleware
dashboard.use("/admin/*", async (req, res, next) => {
const session = await validateSession(req);
if (!session || session.user.role !== "admin") {
return res.status(403).json({ error: "Admin access required" });
}
next();
});Database Operations
Direct database access:
import { database } from "@well-prado/blok-admin-dashboard";
import { users, sessions } from "@well-prado/blok-admin-dashboard/schemas";
// Query users
const allUsers = await database.select().from(users);
// Create user
const newUser = await database.insert(users).values({
id: generateId(),
email: "[email protected]",
passwordHash: await hashPassword("password"),
name: "New User",
});
// Update user
await database
.update(users)
.set({ name: "Updated Name" })
.where(eq(users.id, userId));
// Delete user
await database.delete(users).where(eq(users.id, userId));Security Features
Rate Limiting
Configurable rate limiting per endpoint:
const config = {
security: {
rateLimiting: {
enabled: true,
windowMs: 15 * 60 * 1000, // 15 minutes
maxRequests: 100,
skipSuccessfulRequests: false,
skipFailedRequests: false,
},
},
};Audit Logging
All actions are automatically logged:
// Automatically logged actions:
// - User login/logout
// - User creation/update/deletion
// - Admin actions
// - Security events
// - System errors
// Custom audit logging
import { auditLogger } from "@well-prado/blok-admin-dashboard";
await auditLogger.log({
userId: "user_123",
action: "CUSTOM_ACTION",
resource: "custom_resource",
resourceId: "resource_456",
details: { customData: "value" },
});Two-Factor Authentication
Built-in TOTP-based 2FA:
// Setup 2FA for user
const setup2FA = useWorkflowMutation("security/two-factor-auth");
const { qrCode, secret } = await setup2FA.mutateAsync({ action: "setup" });
// Verify 2FA token
const verify2FA = useWorkflowMutation("security/two-factor-auth");
const result = await verify2FA.mutateAsync({
action: "verify",
token: "123456",
});Email Integration
SMTP Configuration
const config = {
email: {
provider: "smtp",
config: {
host: "smtp.gmail.com",
port: 587,
secure: false,
auth: {
user: "[email protected]",
pass: "your-app-password",
},
},
},
};Email Templates
Customize email templates:
const config = {
email: {
templates: {
welcome: `
<h1>Welcome to {{appName}}!</h1>
<p>Hello {{userName}}, welcome to our platform.</p>
`,
passwordReset: `
<h1>Password Reset</h1>
<p>Click <a href="{{resetLink}}">here</a> to reset your password.</p>
`,
},
},
};Sending Emails
import { emailService } from "@well-prado/blok-admin-dashboard";
await emailService.send({
to: "[email protected]",
subject: "Welcome!",
template: "welcome",
data: {
userName: "John Doe",
appName: "My App",
},
});Monitoring and Logging
System Logs
View system logs:
import { systemLogger } from "@well-prado/blok-admin-dashboard";
// Log custom events
systemLogger.info("Custom event", {
category: "CUSTOM",
userId: "user_123",
metadata: { customData: "value" },
});
// Query logs
const logs = await systemLogger.query({
level: "error",
category: "AUTH",
startDate: new Date("2024-01-01"),
endDate: new Date("2024-01-31"),
});Health Checks
Built-in health check endpoints:
# Check system health
GET /health
# Response
{
"status": "healthy",
"timestamp": "2024-01-01T12:00:00Z",
"checks": {
"database": "healthy",
"email": "healthy",
"cache": "healthy"
}
}Testing
Unit Tests
import { AdminDashboard } from "@well-prado/blok-admin-dashboard";
import { createTestConfig } from "@well-prado/blok-admin-dashboard/testing";
describe("Admin Dashboard", () => {
let dashboard: AdminDashboard;
beforeEach(() => {
dashboard = new AdminDashboard(createTestConfig());
});
test("should authenticate user", async () => {
const result = await dashboard.executeWorkflow("auth/login", {
email: "[email protected]",
password: "password",
});
expect(result.success).toBe(true);
expect(result.data.user.email).toBe("[email protected]");
});
});Integration Tests
import request from "supertest";
import { AdminDashboard } from "@well-prado/blok-admin-dashboard";
describe("API Integration", () => {
let app: AdminDashboard;
beforeAll(async () => {
app = new AdminDashboard(testConfig);
await app.start();
});
test("POST /auth/login", async () => {
const response = await request(app.server).post("/auth/login").send({
email: "[email protected]",
password: "password",
});
expect(response.status).toBe(200);
expect(response.body.success).toBe(true);
});
});Deployment
Production Configuration
const productionConfig = {
database: {
url: process.env.DATABASE_URL,
enableWAL: true,
connectionPooling: true,
maxConnections: 20,
},
auth: {
sessionDuration: 3600, // 1 hour
requireEmailVerification: true,
},
security: {
rateLimiting: {
enabled: true,
windowMs: 15 * 60 * 1000,
maxRequests: 1000,
},
auditLogging: true,
corsOrigins: [process.env.FRONTEND_URL],
},
server: {
port: process.env.PORT || 4000,
host: "0.0.0.0",
},
};Docker Deployment
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
EXPOSE 4000
CMD ["npm", "start"]Environment Variables
# Database
DATABASE_URL=file:./database/app.db
# Authentication
SESSION_DURATION=3600
REQUIRE_EMAIL_VERIFICATION=true
# Email
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
[email protected]
SMTP_PASS=your-app-password
# Security
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100
# Server
PORT=4000
NODE_ENV=productionMigration Guide
From v0.x to v1.x
Update configuration format:
// Old const config = { databaseUrl: "file:./app.db", sessionDuration: 3600, }; // New const config = { database: { url: "file:./app.db" }, auth: { sessionDuration: 3600 }, };Update imports:
// Old import { AdminDashboard } from "@well-prado/blok-admin-dashboard/core"; // New import { AdminDashboard } from "@well-prado/blok-admin-dashboard";
Troubleshooting
Common Issues
Database connection errors
- Check file permissions for SQLite database
- Ensure database directory exists
- Verify connection string format
Authentication failures
- Check session configuration
- Verify password hashing
- Ensure cookies are being sent
Email sending failures
- Verify SMTP credentials
- Check firewall settings
- Test with email provider's test tools
Debug Mode
Enable debug logging:
DEBUG=blok-admin:* npm startPerformance Tips
Database Optimization
- Enable WAL mode for better concurrency
- Use connection pooling
- Add appropriate indexes
Caching
- Enable session caching
- Cache frequently accessed data
- Use Redis for distributed caching
Rate Limiting
- Configure appropriate limits
- Use distributed rate limiting for multiple servers
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
Related Packages
@well-prado/blok-frontend-app- Complete React frontend@well-prado/blok-react-sdk- React hooks and components@well-prado/blok-codegen- TypeScript code generation@well-prado/blok-cli- CLI for project management
