# 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`:
```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:
```bash
# 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:
```env
# 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:
```bash
# Using the existing auth system
cargo run --bin create-admin-user
```
Or via API:
```bash
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:
```rust
use crate::components::admin::AdminLayout;
use leptos_router::*;
#[component]
pub fn App() -> impl IntoView {
view! {
// Public routes
// Protected admin routes
}
}
```
### Navigation Integration
Add admin link to your navigation:
```rust
use crate::auth::use_auth;
#[component]
pub fn Navigation() -> impl IntoView {
let auth = use_auth();
view! {
}
}
```
### Authentication Guard
Protect admin routes with authentication:
```rust
#[component]
pub fn ProtectedAdminRoute() -> impl IntoView {
let auth = use_auth();
view! {
"Access Denied" }
>
}
}
```
## π¨ Customization
### Styling
The admin dashboard uses Tailwind CSS classes. Customize the appearance by:
1. **Override CSS classes** in your components
2. **Extend Tailwind config** for custom colors/spacing
3. **Create custom admin themes** by modifying the AdminLayout component
### Adding New Admin Pages
1. Create a new component in `pages/admin/`:
```rust
// pages/admin/Analytics.rs
#[component]
pub fn AdminAnalytics() -> impl IntoView {
let i18n = use_i18n();
view! {
{move || i18n.t("admin.analytics.title")}
// Your analytics content here
}
}
```
2. Add the route to AdminLayout:
```rust
// In AdminLayout.rs
// New route
```
3. Add navigation item:
```rust
// In AdminLayout.rs navigation
```
### Adding Translations
Add new translations to `content/texts.toml`:
```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
1. **Always verify admin role** before showing admin UI
2. **Protect API endpoints** with RBAC middleware
3. **Use HTTPS** in production
4. **Implement rate limiting** for admin actions
5. **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
1. **Create**: Content starts as a draft
2. **Edit**: Authors can modify content
3. **Review**: Optional review process
4. **Publish**: Make content live
5. **Schedule**: Publish at a specific time
6. **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 login
- `POST /api/auth/logout` - User logout
- `GET /api/auth/me` - Get current user
- `POST /api/auth/refresh` - Refresh token
### User Management
- `GET /api/admin/users` - List users
- `POST /api/admin/users` - Create user
- `PUT /api/admin/users/:id` - Update user
- `DELETE /api/admin/users/:id` - Delete user
### Role Management
- `GET /api/admin/roles` - List roles
- `POST /api/admin/roles` - Create role
- `PUT /api/admin/roles/:id` - Update role
- `DELETE /api/admin/roles/:id` - Delete role
### Content Management
- `GET /api/admin/content` - List content
- `POST /api/admin/content` - Create content
- `PUT /api/admin/content/:id` - Update content
- `DELETE /api/admin/content/:id` - Delete content
- `POST /api/admin/content/upload` - Upload files
### Analytics
- `GET /api/admin/stats` - Dashboard statistics
- `GET /api/admin/analytics` - Detailed analytics
## π§ͺ Testing
### Unit Tests
```bash
# 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
```bash
# Test full admin workflow
cargo test integration::admin --features "auth,content-db,rbac"
```
### End-to-End Tests
```bash
# Run with headless browser
cargo test e2e::admin_dashboard
```
## π Deployment
### Production Build
```bash
# Build with all admin features
cargo build --release --features "tls,auth,content-db,rbac"
```
### Docker Deployment
```dockerfile
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
```env
# 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
1. **Database Indexing**: Ensure proper indexes on user/content tables
2. **Caching**: Enable content caching for better performance
3. **Pagination**: Use pagination for large datasets
4. **Lazy Loading**: Load admin components only when needed
5. **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:
```bash
RUST_LOG=debug cargo run
```
Check specific modules:
```bash
RUST_LOG=rustelo::auth=debug,rustelo::content=debug cargo run
```
## π€ Contributing
### Adding Features
1. Follow the existing architecture patterns
2. Add comprehensive tests
3. Update documentation
4. Add i18n translations
5. Ensure accessibility compliance
### Code Style
- Use `rustfmt` for formatting
- Follow Rust naming conventions
- Add documentation comments
- Write descriptive commit messages
### Pull Request Process
1. Create feature branch
2. Implement changes with tests
3. Update documentation
4. Submit PR with description
5. 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](https://yourusername.github.io/rustelo)
- **Issues**: [GitHub Issues](https://github.com/yourusername/rustelo/issues)
- **Discussions**: [GitHub Discussions](https://github.com/yourusername/rustelo/discussions)
- **Examples**: See `examples/admin_integration.rs` for complete integration examples
---
Built with β€οΈ using Rust, Leptos, and modern web technologies.