Rustelo/info/quick_start_auth.md
Jesús Pérex 2f0f807331 feat: add dark mode functionality and improve navigation system
- 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>
2025-07-11 20:53:20 +01:00

8.2 KiB

Quick Start Guide: Authentication & Authorization System

This guide will help you get the comprehensive authentication system up and running quickly.

🚀 What You Get

Complete Authentication System

  • JWT Authentication with access and refresh tokens
  • Password-based login with Argon2 hashing
  • OAuth2 Integration (Google, GitHub, Discord, Microsoft)
  • Role-Based Access Control (RBAC) with permissions
  • Secure Session Management with HTTP-only cookies
  • Password Reset functionality
  • Audit Logging for all user actions

Frontend Components

  • AuthProvider - React-style authentication context
  • LoginForm - Complete login UI with OAuth buttons
  • RegisterForm - Registration with password strength indicator
  • Route Protection - Authentication guards for pages

Backend Security

  • CSRF Protection - Built-in token validation
  • Rate Limiting - Prevent brute force attacks
  • Security Headers - Comprehensive HTTP security
  • Token Blacklisting - Invalidate compromised tokens
  • Password Validation - Strength requirements and common password detection

🏃‍♂️ Quick Setup (5 minutes)

1. Database Setup

# Install PostgreSQL (if not already installed)
# macOS
brew install postgresql

# Ubuntu/Debian
sudo apt install postgresql postgresql-contrib

# Create database
createdb rustelo_dev

# Run migrations
psql rustelo_dev < migrations/001_create_auth_tables.sql

2. Environment Configuration

Create .env file in the project root:

# Required - Database
DATABASE_URL=postgres://localhost:5432/rustelo_dev

# Required - JWT Security
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production

# Optional - OAuth (configure as needed)
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret

3. Start the Server

cargo leptos watch

4. Test Default Admin Account

  • Email: admin@example.com
  • Password: admin123
  • ⚠️ Change this password immediately in production!

🔌 Using the System

Frontend Authentication

use leptos::prelude::*;
use auth::{AuthProvider, use_auth, LoginForm};

#[component]
fn App() -> impl IntoView {
    view! {
        <AuthProvider>
            <Router>
                <Routes>
                    <Route path="/login" view=LoginPage />
                    <Route path="/dashboard" view=ProtectedDashboard />
                </Routes>
            </Router>
        </AuthProvider>
    }
}

#[component]
fn LoginPage() -> impl IntoView {
    view! {
        <div class="min-h-screen flex items-center justify-center">
            <LoginForm />
        </div>
    }
}

#[component]
fn ProtectedDashboard() -> impl IntoView {
    let auth = use_auth();
    
    view! {
        <Show 
            when=move || auth.0.is_authenticated()
            fallback=move || view! { <Redirect path="/login" /> }
        >
            <div>
                <h1>"Welcome, " {move || auth.0.user().map(|u| u.display_name_or_username().to_string()).unwrap_or_default()}</h1>
                <button on:click=move |_| (auth.0.actions.logout)()>
                    "Logout"
                </button>
            </div>
        </Show>
    }
}

Backend Route Protection

use auth::middleware::{require_auth, require_admin, AuthContext};
use axum::{Router, routing::get};

fn create_protected_routes() -> Router {
    Router::new()
        // Public routes
        .route("/", get(home_handler))
        
        // Protected routes (require login)
        .route("/profile", get(profile_handler))
        .layer(axum::middleware::from_fn(require_auth))
        
        // Admin routes
        .route("/admin", get(admin_handler))
        .layer(axum::middleware::from_fn(require_admin))
}

async fn profile_handler(auth: AuthContext) -> String {
    format!("Hello, {}!", auth.user().unwrap().username)
}

📡 API Endpoints Ready to Use

Authentication

  • POST /api/auth/register - Register new user
  • POST /api/auth/login - Login with email/password
  • POST /api/auth/logout - Logout current user
  • GET /api/auth/profile - Get user profile
  • PUT /api/auth/profile - Update profile

OAuth (if configured)

  • GET /api/auth/oauth/providers - List available providers
  • GET /api/auth/oauth/google/authorize - Google OAuth URL
  • GET /api/auth/oauth/github/authorize - GitHub OAuth URL

Password Reset

  • POST /api/auth/password-reset/request - Request reset
  • POST /api/auth/password-reset/confirm - Confirm reset

🛡️ Security Features Enabled

Built-in Security

  • CSRF Protection - Automatic token validation
  • Rate Limiting - 100 requests per minute per IP
  • Security Headers - HSTS, CSP, X-Frame-Options, etc.
  • Password Hashing - Argon2 with secure defaults
  • JWT Security - HS256 signing, 15-minute access tokens

Data Protection

  • HTTP-Only Cookies - XSS protection
  • Secure Cookies - HTTPS-only transmission
  • SameSite Cookies - CSRF prevention
  • Input Validation - SQL injection prevention

🎯 Role-Based Access Control

Default Roles

// Check user roles
if user.has_role(&Role::Admin) {
    // Admin actions
}

if user.has_permission(&Permission::WriteContent) {
    // Content creation allowed
}

Available Roles

  • Admin - Full system access
  • Moderator - Content management
  • User - Standard user access
  • Guest - Read-only access

Available Permissions

  • ReadUsers, WriteUsers, DeleteUsers
  • ReadContent, WriteContent, DeleteContent
  • ManageRoles, ManageSystem

🔧 Configuration Options

JWT Configuration

JWT_ACCESS_TOKEN_EXPIRES_IN=15   # minutes
JWT_REFRESH_TOKEN_EXPIRES_IN=7   # days

Password Security

# Argon2 uses secure defaults, no configuration needed

OAuth Configuration

OAUTH_REDIRECT_BASE_URL=http://localhost:3030/api/auth/oauth/callback

🐛 Common Issues & Solutions

Database Connection Failed

# Check if PostgreSQL is running
pg_ctl -D /usr/local/var/postgres status

# Start if not running
brew services start postgresql

OAuth Not Working

  1. Verify redirect URLs match exactly in provider settings
  2. Check client ID/secret are correct
  3. Ensure HTTPS in production

JWT Token Issues

  1. Ensure JWT_SECRET is consistent across restarts
  2. Check token expiration times
  3. Verify server time synchronization

📈 Production Checklist

⚠️ Security (Critical)

  • Change default admin password
  • Use strong JWT_SECRET (64+ random characters)
  • Enable HTTPS in production
  • Set secure environment variables
  • Review and update CORS settings

🔧 Performance

  • Configure connection pooling
  • Set up Redis for session storage (optional)
  • Enable database query logging
  • Monitor authentication metrics

📊 Monitoring

  • Set up logging aggregation
  • Monitor failed login attempts
  • Track token refresh rates
  • Alert on suspicious activity

📚 Next Steps

Extend the System

  1. Add Multi-Factor Authentication

    • TOTP support with totp-lite
    • SMS verification with Twilio
  2. Email Integration

    • Password reset emails
    • Welcome emails
    • Security notifications
  3. Advanced Features

    • WebAuthn/Passkeys
    • Social login providers
    • API key authentication

Custom OAuth Provider

// Add custom OAuth provider
let custom_provider = OAuthProvider::Custom("company".to_string());
oauth_service.configure_custom_provider(custom_provider, config).await?;

🆘 Support & Documentation

🎉 You're Ready!

Your authentication system is now fully functional with:

  • Secure user registration and login
  • OAuth integration with major providers
  • Role-based access control
  • Session management
  • Password reset functionality
  • Comprehensive security features
  • Production-ready architecture

Start building your application with confidence! 🚀