Files
projectmycelium/docs/dev/design/archive/authentication-flow.md
2025-09-01 21:37:01 -04:00

6.3 KiB

Authentication Flow Implementation

Overview

This document describes the authentication flow implementation for the Project Mycelium, specifically addressing the requirements for dashboard access, marketplace purchases, and cart functionality.

Requirements Implemented

1. Dashboard Route Protection

  • Requirement: All dashboard pages show welcome page with login/register options when not logged in
  • Implementation: All dashboard routes show the nice welcome page for unauthenticated users instead of redirecting to register
  • Rationale: Better UX - existing users can login, new users can register, all from the same welcoming interface

2. Marketplace Buy Now Protection

  • Requirement: If on marketplace and clicking "buy now" while not logged in, show "register first" message
  • Implementation: Frontend authentication check before purchase attempt

3. Cart Functionality

  • Requirement: Add to cart is OK without registration (common estore UX), register at checkout
  • Implementation: Cart allows unauthenticated users, authentication required only at checkout

Technical Implementation

Authentication Check Methods

Dashboard Controllers

// In DashboardController and WalletController
fn check_authentication(session: &Session) -> Result<(), actix_web::HttpResponse> {
    match session.get::<String>("user") {
        Ok(Some(_)) => Ok(()),
        _ => Err(actix_web::HttpResponse::Found()
            .append_header((actix_web::http::header::LOCATION, "/register"))
            .finish())
    }
}

Frontend Buy Now Check

// In buy-now.js
async checkAuthentication() {
    try {
        const response = await fetch('/api/auth/status');
        const result = await response.json();
        return result.authenticated === true;
    } catch (error) {
        console.error('Authentication check failed:', error);
        return false;
    }
}

Protected Routes

Dashboard Routes

All dashboard routes have consistent authentication behavior:

All Dashboard Pages (show welcome page when unauthenticated):

  • /dashboard - Main dashboard
  • /dashboard/user - User section
  • /dashboard/farmer - Farmer section
  • /dashboard/app-provider - App provider section
  • /dashboard/service-provider - Service provider section
  • /dashboard/wallet - Wallet page
  • /dashboard/settings - Settings page

Authentication Flow:

  • Unauthenticated: Shows welcome page with login/register options
  • Authenticated: Shows the specific dashboard functionality

API Endpoints

  • /api/auth/status - Check authentication status (returns JSON)

Cart System

The cart system allows unauthenticated users:

// In OrderController::add_to_cart
pub async fn add_to_cart(session: Session, request: web::Json<AddToCartRequest>) -> Result<impl Responder> {
    // Allow both authenticated and guest users to add to cart
    let user_id = session.get::<String>("user_id").unwrap_or(None).unwrap_or_default();
    let cart_key = if user_id.is_empty() { "guest_cart" } else { "user_cart" };
    // ... rest of implementation
}

User Experience Flow

Unauthenticated User Journey

  1. Marketplace Browsing: Allowed

    • User can browse all marketplace pages
    • User can view product details
    • User can add items to cart
  2. Dashboard Access: Shows welcome page with login/register options

    • All dashboard pages show the same welcoming interface
    • Users can choose to login (existing users) or register (new users)
    • Much better UX than forcing users to register page
  3. Buy Now: Blocked with Message

    • "Please register first to make purchases"
    • Option to redirect to registration page
  4. Add to Cart: Allowed

    • Items stored in guest cart
    • Can proceed to checkout (where authentication will be required)

Authenticated User Journey

  1. Full Access: Complete functionality
    • Dashboard access granted
    • Buy now functionality works
    • Cart functionality works
    • All features available

Files Modified

Backend Controllers

Frontend JavaScript

Templates

Routes

Testing

The implementation has been tested for:

  • Compilation success (no errors)
  • Route configuration
  • Authentication logic
  • Frontend integration

Security Considerations

  1. Session-based Authentication: Uses secure session management
  2. CSRF Protection: Session-based CSRF protection maintained
  3. Input Validation: Proper validation on all endpoints
  4. Redirect Safety: Safe redirect to registration page only

Future Enhancements

  1. Enhanced Error Messages: More specific error messages for different scenarios
  2. Remember Cart: Persist guest cart across sessions
  3. Social Login: Integration with OAuth providers
  4. Two-Factor Authentication: Additional security layer

Troubleshooting

Common Issues

  1. Redirect Loop: Ensure registration page doesn't require authentication
  2. Cart Loss: Guest cart is session-based, will be lost on session expiry
  3. JavaScript Errors: Ensure buy-now.js is loaded on marketplace pages

Debug Endpoints

  • GET /api/auth/status - Check current authentication status
  • Session data available in browser developer tools

Conclusion

The authentication flow has been successfully implemented according to the requirements:

  • Dashboard routes are protected and redirect to registration
  • Buy now functionality requires authentication with clear messaging
  • Cart functionality allows unauthenticated users for optimal UX
  • All changes maintain backward compatibility and security best practices