# 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! {
        <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:

```rust
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:

```rust
#[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:

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! {
        <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>
    }
}
```

2. Add the route to AdminLayout:

```rust
// 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>
```

3. Add navigation item:

```rust
// In AdminLayout.rs navigation
<AdminNavItem
    section=AdminSection::Analytics
    current_section=current_section
    i18n=i18n.clone()
/>
```

### 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.
