/template recipe-super-admin
Commercial License Required
MakerKit requires a commercial license. While Orchestre can help you build with it, you must obtain a valid license from MakerKit for commercial use.
Access: /template recipe-super-admin or /t recipe-super-admin
Purpose
Implements a comprehensive super admin system with god-mode capabilities for SaaS platforms. This recipe creates infrastructure for platform-wide administration, user impersonation, system monitoring, configuration management, and advanced debugging tools.
How It Actually Works
The recipe:
- Analyzes your current admin and security setup
- Creates super admin role and permission systems
- Implements secure authentication and audit trails
- Adds platform management dashboards
- Integrates monitoring and debugging tools
- Sets up emergency response capabilities
Use Cases
- SaaS Platforms: Complete platform administration
- Enterprise Software: System-wide configuration
- Multi-tenant Apps: Cross-tenant management
- Support Systems: Customer issue resolution
- Compliance Tools: Audit and monitoring
- Emergency Response: System recovery and fixes
Examples
Full Super Admin Suite
bash
/template recipe-super-admin
# Implements complete admin system with:
# - User impersonation
# - System configuration
# - Platform analytics
# - Debug toolsSupport-Focused Admin
bash
/template recipe-super-admin support
# Creates support admin tools with:
# - Customer impersonation
# - Ticket integration
# - Account debugging
# - Data export toolsCompliance Admin
bash
/template recipe-super-admin compliance
# Compliance-focused admin with:
# - Audit logging
# - Data retention controls
# - GDPR tools
# - Security monitoringWhat Gets Created
Database Schema
sql
-- Super admin roles
create table super_admin_roles (
id uuid primary key default gen_random_uuid(),
user_id uuid references auth.users(id) on delete cascade,
role text not null check (role in ('super_admin', 'platform_admin', 'support_admin')),
permissions jsonb default '{}',
granted_by uuid references auth.users(id),
granted_at timestamp with time zone default now(),
expires_at timestamp with time zone,
is_active boolean default true,
metadata jsonb default '{}'
);
-- Admin actions audit log
create table super_admin_audit_log (
id uuid primary key default gen_random_uuid(),
admin_id uuid references auth.users(id),
action text not null,
resource_type text not null,
resource_id text,
affected_user_id uuid references auth.users(id),
affected_team_id uuid references teams(id),
details jsonb default '{}',
ip_address inet,
user_agent text,
created_at timestamp with time zone default now()
);
-- Impersonation sessions
create table impersonation_sessions (
id uuid primary key default gen_random_uuid(),
admin_id uuid references auth.users(id) on delete cascade,
target_user_id uuid references auth.users(id) on delete cascade,
reason text not null,
started_at timestamp with time zone default now(),
ended_at timestamp with time zone,
actions_taken jsonb default '[]',
is_active boolean default true
);
-- System configuration
create table system_configuration (
key text primary key,
value jsonb not null,
description text,
category text not null,
is_sensitive boolean default false,
last_modified_by uuid references auth.users(id),
last_modified_at timestamp with time zone default now(),
version integer default 1
);
-- Feature flags
create table feature_flags (
id uuid primary key default gen_random_uuid(),
name text unique not null,
description text,
is_enabled boolean default false,
rollout_percentage integer default 0,
targeting_rules jsonb default '{}',
created_by uuid references auth.users(id),
created_at timestamp with time zone default now(),
updated_at timestamp with time zone default now()
);
-- Platform metrics
create table platform_metrics (
id uuid primary key default gen_random_uuid(),
metric_name text not null,
metric_value jsonb not null,
timestamp timestamp with time zone default now(),
dimensions jsonb default '{}',
created_at timestamp with time zone default now()
);API Routes
typescript
// app/api/super-admin/auth/route.ts
POST /api/super-admin/auth
- Verify super admin access
- 2FA requirement
- Session management
- Audit logging
// app/api/super-admin/impersonate/route.ts
POST /api/super-admin/impersonate
- Start impersonation session
- Generate secure token
- Log reason and context
- Set time limits
// app/api/super-admin/users/route.ts
GET/POST/PATCH /api/super-admin/users
- List all users
- Modify user data
- Suspend/activate accounts
- Reset passwords
// app/api/super-admin/config/route.ts
GET/PATCH /api/super-admin/config
- View system configuration
- Update settings
- Feature flag management
- Environment variables
// app/api/super-admin/metrics/route.ts
GET /api/super-admin/metrics
- Platform statistics
- Performance metrics
- Error tracking
- Usage analytics
// app/api/super-admin/debug/route.ts
POST /api/super-admin/debug
- Execute debug commands
- Query database
- Clear caches
- System diagnosticsReact Components
typescript
// components/super-admin/dashboard.tsx
- Platform overview
- Key metrics display
- Quick actions
- Alert center
// components/super-admin/user-manager.tsx
- User search and filter
- Bulk operations
- Account details
- Impersonation controls
// components/super-admin/system-config.tsx
- Configuration editor
- Feature flag toggles
- Environment settings
- Service health
// components/super-admin/audit-log-viewer.tsx
- Action history
- Filtering and search
- Export capabilities
- Compliance reports
// components/super-admin/debug-console.tsx
- SQL query runner
- Cache inspector
- Log viewer
- Performance profiler
// components/super-admin/emergency-controls.tsx
- Maintenance mode
- Rate limit overrides
- Service toggles
- Data recoveryHooks and Utilities
typescript
// hooks/use-super-admin.ts
- useSuperAdminAuth()
- useImpersonation()
- useSystemConfig()
- useAuditLog()
// lib/super-admin/auth.ts
- Verify admin status
- Check permissions
- Manage sessions
- 2FA enforcement
// lib/super-admin/audit.ts
- Log all actions
- Track changes
- Generate reports
- Compliance exports
// lib/super-admin/security.ts
- IP restrictions
- Time-based access
- Emergency lockdown
- Threat detectionTechnical Details
Secure Authentication Layer
typescript
// Multi-factor admin authentication
class SuperAdminAuth {
async authenticate(email: string, password: string, otp: string) {
// Verify credentials
const admin = await verifyAdminCredentials(email, password);
// Check super admin role
if (!admin.roles.includes('super_admin')) {
throw new UnauthorizedError('Not a super admin');
}
// Verify 2FA
const isValidOTP = await verify2FA(admin.id, otp);
if (!isValidOTP) {
await logFailedAttempt(admin.id);
throw new UnauthorizedError('Invalid 2FA code');
}
// Create secure session
const session = await createAdminSession(admin.id, {
ip: getClientIP(),
userAgent: getUserAgent(),
expiresIn: '2h', // Short-lived sessions
});
// Log successful authentication
await auditLog('admin_login', admin.id);
return session;
}
}Impersonation System
typescript
// Secure user impersonation
class ImpersonationManager {
async startImpersonation(adminId: string, targetUserId: string, reason: string) {
// Verify permissions
await this.verifyImpersonationPermission(adminId, targetUserId);
// Create impersonation session
const session = await db.impersonation_sessions.create({
admin_id: adminId,
target_user_id: targetUserId,
reason,
started_at: new Date(),
});
// Generate special token
const token = await generateImpersonationToken({
sessionId: session.id,
adminId,
targetUserId,
expiresIn: '1h',
});
// Audit log
await auditLog('impersonation_start', adminId, {
targetUser: targetUserId,
reason,
});
// Send notification to target user
await notifyUserOfImpersonation(targetUserId, adminId, reason);
return { token, session };
}
async trackAction(sessionId: string, action: any) {
// Log every action during impersonation
await db.impersonation_sessions.update(sessionId, {
actions_taken: db.raw('actions_taken || ?', [action]),
});
}
}System Configuration Management
typescript
// Dynamic configuration system
class SystemConfigManager {
private cache = new Map();
async get(key: string): Promise<any> {
// Check cache first
if (this.cache.has(key)) {
return this.cache.get(key);
}
// Get from database
const config = await db.system_configuration.findOne({ key });
if (!config) {
throw new Error(`Config key not found: ${key}`);
}
// Decrypt if sensitive
const value = config.is_sensitive
? await decrypt(config.value)
: config.value;
// Cache for performance
this.cache.set(key, value);
return value;
}
async set(key: string, value: any, adminId: string) {
// Validate permission
await this.verifyConfigPermission(adminId, key);
// Encrypt sensitive values
const storedValue = await this.isKeySensitive(key)
? await encrypt(value)
: value;
// Update with versioning
await db.system_configuration.upsert({
key,
value: storedValue,
last_modified_by: adminId,
version: db.raw('version + 1'),
});
// Clear cache
this.cache.delete(key);
// Audit log
await auditLog('config_change', adminId, { key, oldValue, newValue });
// Notify other services
await broadcastConfigChange(key, value);
}
}Memory Evolution
The recipe creates comprehensive admin system memory:
markdown
## Super Admin System Configuration
### Admin Roles
- Super Admin: Full platform access (2 users)
- Platform Admin: Configuration and monitoring (5 users)
- Support Admin: User management and debugging (10 users)
### Security Policies
- 2FA: Required for all admin actions
- Session timeout: 2 hours
- IP whitelist: Office networks only
- Audit retention: 2 years
### Impersonation Rules
- Max duration: 1 hour
- Requires reason documentation
- User notification: Automatic
- Action logging: All activities tracked
### Emergency Procedures
- Maintenance mode: Toggle via dashboard
- Data recovery: S3 backup integration
- Service restart: Kubernetes integration
- Lockdown mode: Disable all non-admin access
### Integration Points
- Monitoring: DataDog dashboards
- Alerting: PagerDuty integration
- Logging: Elasticsearch cluster
- Compliance: Automated GDPR exportsBest Practices
Security First
- Always require 2FA for admin actions
- Log every admin operation
- Implement IP restrictions
- Use time-limited sessions
- Regular permission audits
Responsible Impersonation
- Always document reason
- Notify users when possible
- Log all actions taken
- Set automatic timeouts
- Review impersonation logs
Change Management
- Test configuration changes
- Use feature flags for rollouts
- Maintain change history
- Implement rollback capabilities
- Document all modifications
Emergency Preparedness
- Regular backup testing
- Documented procedures
- On-call rotation
- Incident response plan
- Communication protocols
Integration Points
With Authentication System
typescript
// Enhanced auth for admins
const adminAuthMiddleware = async (req, res, next) => {
const session = await verifyAdminSession(req);
// Additional checks for super admin
if (session.role === 'super_admin') {
await verify2FA(session);
await checkIPWhitelist(req.ip);
await enforceTimeRestrictions(session);
}
req.admin = session;
next();
};With Monitoring Systems
typescript
// Real-time platform monitoring
const platformMonitor = {
async collectMetrics() {
const metrics = await Promise.all([
this.getUserMetrics(),
this.getPerformanceMetrics(),
this.getErrorMetrics(),
this.getBusinessMetrics(),
]);
await this.sendToDataDog(metrics);
await this.updateDashboard(metrics);
await this.checkAlertThresholds(metrics);
},
};With Support Systems
typescript
// Customer support integration
const supportIntegration = {
async handleTicket(ticketId: string, adminId: string) {
const ticket = await getTicket(ticketId);
// Auto-impersonate for investigation
const session = await impersonateUser(
adminId,
ticket.userId,
`Support ticket: ${ticketId}`
);
// Gather diagnostic data
const diagnostics = await gatherUserDiagnostics(ticket.userId);
// Update ticket with findings
await updateTicket(ticketId, { diagnostics });
return session;
},
};Troubleshooting
Common Issues
Admin Access Denied
- Verify role assignment
- Check 2FA setup
- Review IP whitelist
- Confirm session validity
Impersonation Failures
- Check target user exists
- Verify permissions
- Review security policies
- Check session limits
Configuration Errors
- Validate JSON format
- Check encryption keys
- Review permissions
- Test in staging first
Debug Tools
typescript
// Admin debugging utilities
const adminDebugger = {
async inspectUser(userId: string) {
return {
profile: await getUserProfile(userId),
permissions: await getUserPermissions(userId),
sessions: await getActiveSessions(userId),
logs: await getRecentActivity(userId),
subscriptions: await getSubscriptions(userId),
};
},
async systemDiagnostics() {
return {
database: await checkDatabaseHealth(),
cache: await checkCacheStatus(),
queues: await checkQueueBacklog(),
services: await checkServiceHealth(),
};
},
};Advanced Features
Automated Compliance
typescript
// GDPR compliance automation
const complianceAutomation = {
async generateGDPRExport(userId: string, adminId: string) {
await auditLog('gdpr_export', adminId, { userId });
const data = await collectAllUserData(userId);
const encrypted = await encryptExport(data);
const url = await uploadToSecureStorage(encrypted);
await notifyUser(userId, 'GDPR export ready', { url });
return { url, expiresAt: addDays(new Date(), 7) };
},
};Intelligent Monitoring
typescript
// ML-powered anomaly detection
const anomalyDetector = {
async analyzeUserBehavior(userId: string) {
const patterns = await getUserPatterns(userId);
const anomalies = await mlModel.detectAnomalies(patterns);
if (anomalies.severity > 0.8) {
await alertSuperAdmin('High severity anomaly detected', {
userId,
anomalies,
});
}
return anomalies;
},
};Related Commands
/template add-admin-panel- Basic admin interface/template add-audit-log- Audit logging system/template add-monitoring- Platform monitoring/template add-security-headers- Enhanced security
