- Add complete dark mode system with theme context and toggle - Implement dark mode toggle component in navigation menu - Add client-side routing with SSR-safe signal handling - Fix language selector styling for better dark mode compatibility - Add documentation system with mdBook integration - Improve navigation menu with proper external/internal link handling - Add comprehensive project documentation and configuration - Enhance theme system with localStorage persistence - Fix arena panic issues during server-side rendering - Add proper TypeScript configuration and build optimizations 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
13 KiB
Admin Dashboard System
A comprehensive admin dashboard built on top of the existing Rustelo authentication and content management infrastructure.
🚀 Features
✅ User Management
- View, create, edit, and manage users
- Role assignment and permission management
- User status management (Active, Inactive, Suspended, Pending)
- Bulk user operations
- User activity tracking
✅ Role-Based Access Control (RBAC)
- Create and manage custom roles
- Assign granular permissions
- Hierarchical role inheritance
- System role protection
- Permission auditing
✅ Content Management
- Multi-source content support (Database + Files)
- Content types: Blog, Page, Article, Documentation, Tutorial
- Content formats: Markdown, HTML, Plain Text
- Content states: Draft, Published, Archived, Scheduled
- SEO metadata management
- File upload capabilities
- Content analytics and view tracking
✅ Internationalization
- Full i18n support (English/Spanish)
- Localized admin interface
- Easy to extend with additional languages
✅ Database Abstraction
- Works with PostgreSQL and SQLite
- Automatic database type detection
- Unified query interface
📁 Project Structure
template/client/src/
├── components/admin/ # Admin-specific components
│ ├── AdminLayout.rs # Main admin layout with navigation
│ └── mod.rs
├── pages/admin/ # Admin page components
│ ├── Dashboard.rs # Admin dashboard with stats
│ ├── Users.rs # User management
│ ├── Roles.rs # Role management
│ ├── Content.rs # Content management
│ └── mod.rs
└── examples/
└── admin_integration.rs # Integration examples
template/server/src/
├── auth/ # Authentication system
│ ├── rbac_service.rs # RBAC implementation
│ ├── middleware.rs # Auth middleware
│ └── routes.rs # Auth routes
├── content/ # Content management
│ ├── service.rs # Content service
│ ├── repository.rs # Data access
│ ├── file_loader.rs # File-based content
│ └── routes.rs # Content API routes
└── database/ # Database abstraction
├── mod.rs # Database pool management
├── auth.rs # Auth-related queries
└── rbac.rs # RBAC queries
template/shared/src/
├── auth.rs # Shared auth types
└── content.rs # Shared content types
template/content/
└── texts.toml # i18n translations
🛠️ Setup
1. Enable Required Features
In your Cargo.toml:
[features]
default = ["auth", "content-db", "rbac"]
auth = ["dep:jsonwebtoken", "dep:argon2"]
content-db = ["dep:pulldown-cmark", "dep:syntect"]
rbac = ["dep:serde_json"]
2. Database Setup
The admin dashboard works with your existing database. Ensure migrations are run:
# PostgreSQL
sqlx migrate run --database-url postgresql://user:pass@localhost/db
# SQLite
sqlx migrate run --database-url sqlite:data/app.db
3. Environment Configuration
Add to your .env file:
# Database (choose one)
DATABASE_URL=postgresql://user:pass@localhost/db
# DATABASE_URL=sqlite:data/app.db
# Authentication
JWT_SECRET=your-super-secret-jwt-key
JWT_EXPIRATION_HOURS=24
# Content Management
CONTENT_SOURCE=both # database, files, or both
CONTENT_DIR=./content
4. Admin User Setup
Create an initial admin user:
# Using the existing auth system
cargo run --bin create-admin-user
Or via API:
curl -X POST http://localhost:3030/api/auth/register \
-H "Content-Type: application/json" \
-d '{
"email": "admin@yourapp.com",
"password": "secure-password",
"roles": ["admin"]
}'
🔗 Integration
Router Integration
Add admin routes to your main app:
use crate::components::admin::AdminLayout;
use leptos_router::*;
#[component]
pub fn App() -> impl IntoView {
view! {
<Router>
<Routes>
// Public routes
<Route path="/" view=HomePage />
<Route path="/about" view=AboutPage />
// Protected admin routes
<Route path="/admin/*" view=AdminLayout />
</Routes>
</Router>
}
}
Navigation Integration
Add admin link to your navigation:
use crate::auth::use_auth;
#[component]
pub fn Navigation() -> impl IntoView {
let auth = use_auth();
view! {
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
// Admin link - only for admin users
<Show when=move || auth.has_role("admin")>
<a href="/admin">Admin Dashboard</a>
</Show>
</nav>
}
}
Authentication Guard
Protect admin routes with authentication:
#[component]
pub fn ProtectedAdminRoute() -> impl IntoView {
let auth = use_auth();
view! {
<Show
when=move || auth.is_authenticated() && auth.has_role("admin")
fallback=|| view! { <div>"Access Denied"</div> }
>
<AdminLayout />
</Show>
}
}
🎨 Customization
Styling
The admin dashboard uses Tailwind CSS classes. Customize the appearance by:
- Override CSS classes in your components
- Extend Tailwind config for custom colors/spacing
- Create custom admin themes by modifying the AdminLayout component
Adding New Admin Pages
- Create a new component in
pages/admin/:
// pages/admin/Analytics.rs
#[component]
pub fn AdminAnalytics() -> impl IntoView {
let i18n = use_i18n();
view! {
<div class="min-h-screen bg-gray-50">
<div class="py-6">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<h1 class="text-3xl font-bold text-gray-900">
{move || i18n.t("admin.analytics.title")}
</h1>
// Your analytics content here
</div>
</div>
</div>
}
}
- Add the route to AdminLayout:
// In AdminLayout.rs
<Routes>
<Route path="/admin" view=AdminDashboard />
<Route path="/admin/users" view=AdminUsers />
<Route path="/admin/roles" view=AdminRoles />
<Route path="/admin/content" view=AdminContent />
<Route path="/admin/analytics" view=AdminAnalytics /> // New route
</Routes>
- Add navigation item:
// In AdminLayout.rs navigation
<AdminNavItem
section=AdminSection::Analytics
current_section=current_section
i18n=i18n.clone()
/>
Adding Translations
Add new translations to content/texts.toml:
[en]
"admin.analytics.title" = "Analytics Dashboard"
"admin.analytics.subtitle" = "View application metrics and insights"
[es]
"admin.analytics.title" = "Panel de Analíticas"
"admin.analytics.subtitle" = "Ver métricas y conocimientos de la aplicación"
🔒 Security
Authentication
- JWT-based authentication
- Secure password hashing with Argon2
- Session management
- OAuth2 integration (Google, GitHub)
- Two-factor authentication (2FA/TOTP)
Authorization
- Role-based access control (RBAC)
- Granular permissions
- Route-level protection
- API endpoint protection
- Hierarchical roles
Best Practices
- Always verify admin role before showing admin UI
- Protect API endpoints with RBAC middleware
- Use HTTPS in production
- Implement rate limiting for admin actions
- Audit admin activities for security compliance
📊 Content Management
Content Sources
The system supports multiple content sources:
- Database: Dynamic content stored in PostgreSQL/SQLite
- Files: Static content from markdown/HTML files
- Both: Hybrid approach combining database and file content
Content Types
- Blog: Blog posts and articles
- Page: Static pages
- Article: Long-form content
- Documentation: Technical documentation
- Tutorial: Step-by-step guides
- Custom: User-defined content types
Content Workflow
- Create: Content starts as a draft
- Edit: Authors can modify content
- Review: Optional review process
- Publish: Make content live
- Schedule: Publish at a specific time
- Archive: Remove from public view
File Upload
Support for various file types:
- Markdown (.md, .markdown)
- HTML (.html)
- Text (.txt)
- Images (for featured images)
- Documents (PDFs, etc.)
🌐 API Endpoints
Authentication
POST /api/auth/login- User loginPOST /api/auth/logout- User logoutGET /api/auth/me- Get current userPOST /api/auth/refresh- Refresh token
User Management
GET /api/admin/users- List usersPOST /api/admin/users- Create userPUT /api/admin/users/:id- Update userDELETE /api/admin/users/:id- Delete user
Role Management
GET /api/admin/roles- List rolesPOST /api/admin/roles- Create rolePUT /api/admin/roles/:id- Update roleDELETE /api/admin/roles/:id- Delete role
Content Management
GET /api/admin/content- List contentPOST /api/admin/content- Create contentPUT /api/admin/content/:id- Update contentDELETE /api/admin/content/:id- Delete contentPOST /api/admin/content/upload- Upload files
Analytics
GET /api/admin/stats- Dashboard statisticsGET /api/admin/analytics- Detailed analytics
🧪 Testing
Unit Tests
# Test admin components
cargo test admin --features "auth,content-db,rbac"
# Test specific functionality
cargo test auth::rbac::tests
cargo test content::service::tests
Integration Tests
# Test full admin workflow
cargo test integration::admin --features "auth,content-db,rbac"
End-to-End Tests
# Run with headless browser
cargo test e2e::admin_dashboard
🚀 Deployment
Production Build
# Build with all admin features
cargo build --release --features "tls,auth,content-db,rbac"
Docker Deployment
FROM rust:1.75 as builder
WORKDIR /app
COPY . .
RUN cargo build --release --features "tls,auth,content-db,rbac"
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y ca-certificates
COPY --from=builder /app/target/release/server /usr/local/bin/
COPY --from=builder /app/content /app/content
EXPOSE 3030
CMD ["server"]
Environment Variables
# Production configuration
DATABASE_URL=postgresql://user:pass@db:5432/production_db
JWT_SECRET=super-secure-production-secret
RUST_LOG=info
ENVIRONMENT=production
# TLS configuration
TLS_CERT_PATH=/etc/ssl/certs/app.crt
TLS_KEY_PATH=/etc/ssl/private/app.key
# Admin settings
ADMIN_EMAIL=admin@yourcompany.com
ADMIN_REGISTRATION_ENABLED=false
📈 Performance
Optimization Tips
- Database Indexing: Ensure proper indexes on user/content tables
- Caching: Enable content caching for better performance
- Pagination: Use pagination for large datasets
- Lazy Loading: Load admin components only when needed
- Bundle Optimization: Split admin code into separate bundles
Monitoring
- Database queries: Monitor slow queries
- Memory usage: Track memory consumption
- Response times: Monitor API response times
- Error rates: Track error rates and patterns
🔧 Troubleshooting
Common Issues
Admin dashboard not loading
- Check authentication state
- Verify admin role assignment
- Check browser console for errors
Permission denied errors
- Verify user has admin role
- Check RBAC configuration
- Review middleware setup
Content not displaying
- Check content source configuration
- Verify database connection
- Check file permissions for file-based content
Database connection issues
- Verify DATABASE_URL format
- Check database connectivity
- Review migration status
Debug Mode
Enable debug logging:
RUST_LOG=debug cargo run
Check specific modules:
RUST_LOG=rustelo::auth=debug,rustelo::content=debug cargo run
🤝 Contributing
Adding Features
- Follow the existing architecture patterns
- Add comprehensive tests
- Update documentation
- Add i18n translations
- Ensure accessibility compliance
Code Style
- Use
rustfmtfor formatting - Follow Rust naming conventions
- Add documentation comments
- Write descriptive commit messages
Pull Request Process
- Create feature branch
- Implement changes with tests
- Update documentation
- Submit PR with description
- Address review feedback
📄 License
This admin dashboard system is part of the Rustelo framework and is licensed under the MIT License.
🆘 Support
- Documentation: Full Documentation
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Examples: See
examples/admin_integration.rsfor complete integration examples
Built with ❤️ using Rust, Leptos, and modern web technologies.