qail-gateway 0.1.0

QAIL Gateway - Native data layer replacing REST/GraphQL
Documentation
//! Authentication middleware
//!
//! Handles JWT validation and user context extraction.

use crate::error::GatewayError;
use serde::{Deserialize, Serialize};

/// User context extracted from authentication
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthContext {
    /// User ID
    pub user_id: String,
    
    /// User role (for policy evaluation)
    pub role: String,
    
    /// Additional claims
    pub claims: std::collections::HashMap<String, serde_json::Value>,
}

impl AuthContext {
    /// Create an anonymous context (for public queries)
    pub fn anonymous() -> Self {
        Self {
            user_id: "anonymous".to_string(),
            role: "anonymous".to_string(),
            claims: std::collections::HashMap::new(),
        }
    }
    
    /// Check if user has a specific role
    pub fn has_role(&self, role: &str) -> bool {
        self.role == role
    }
}

/// Validate a JWT token and extract auth context
/// 
/// # Errors
/// Returns error if token is invalid or expired
pub fn validate_token(_token: &str) -> Result<AuthContext, GatewayError> {
    // TODO: Implement JWT validation
    // For now, return anonymous
    tracing::warn!("JWT validation not implemented, returning anonymous");
    Ok(AuthContext::anonymous())
}

/// Extract auth context from request headers
pub fn extract_auth_header(headers: &[(String, String)]) -> Option<String> {
    headers
        .iter()
        .find(|(k, _)| k.to_lowercase() == "authorization")
        .and_then(|(_, v)| v.strip_prefix("Bearer ").map(String::from))
}