auth_framework/api/
mod.rs

1//! REST API Server Module
2//!
3//! This module provides a comprehensive REST API server implementation
4//! that exposes all AuthFramework functionality through HTTP endpoints.
5
6pub mod admin;
7pub mod auth;
8pub mod error_codes;
9pub mod health;
10pub mod metrics;
11pub mod mfa;
12pub mod middleware;
13pub mod oauth;
14pub mod openapi;
15pub mod responses;
16pub mod server;
17pub mod users;
18pub mod validation;
19pub mod versioning;
20
21#[cfg(feature = "enhanced-rbac")]
22#[cfg(feature = "role-system")]
23pub mod rbac_endpoints;
24
25pub use responses::{ApiError, ApiResponse, ApiResult};
26pub use server::ApiServer;
27
28use crate::AuthFramework;
29use crate::errors::AuthError;
30use std::sync::Arc;
31
32/// API server state
33#[derive(Clone)]
34pub struct ApiState {
35    pub auth_framework: Arc<AuthFramework>,
36    #[cfg(feature = "enhanced-rbac")]
37    pub authorization_service: Arc<crate::authorization_enhanced::AuthorizationService>,
38}
39
40impl ApiState {
41    pub async fn new(auth_framework: Arc<AuthFramework>) -> crate::errors::Result<Self> {
42        Ok(Self {
43            auth_framework,
44            #[cfg(feature = "enhanced-rbac")]
45            authorization_service: Arc::new(
46                crate::authorization_enhanced::AuthorizationService::new().await?,
47            ),
48        })
49    }
50
51    #[cfg(feature = "enhanced-rbac")]
52    pub fn with_authorization_service(
53        auth_framework: Arc<AuthFramework>,
54        authorization_service: Arc<crate::authorization_enhanced::AuthorizationService>,
55    ) -> Self {
56        Self {
57            auth_framework,
58            authorization_service,
59        }
60    }
61}
62
63/// Extract bearer token from Authorization header
64pub fn extract_bearer_token(headers: &axum::http::HeaderMap) -> Option<String> {
65    headers
66        .get("authorization")
67        .and_then(|header| header.to_str().ok())
68        .and_then(|auth_str| auth_str.strip_prefix("Bearer "))
69        .map(|token| token.to_string())
70}
71
72/// Validate API token and extract user information
73pub async fn validate_api_token(
74    auth_framework: &AuthFramework,
75    token: &str,
76) -> Result<crate::tokens::AuthToken, AuthError> {
77    // Use the existing token validation from AuthFramework
78    let token_obj = auth_framework.token_manager().validate_jwt_token(token)?;
79
80    // Convert the validated token claims to AuthToken
81    Ok(crate::tokens::AuthToken {
82        token_id: token_obj.jti.clone(),
83        user_id: token_obj.sub.clone(),
84        access_token: token.to_string(),
85        token_type: Some("Bearer".to_string()),
86        subject: Some(token_obj.sub.clone()),
87        issuer: Some(token_obj.iss.clone()),
88        refresh_token: None,
89        issued_at: chrono::DateTime::from_timestamp(token_obj.iat, 0)
90            .unwrap_or_else(chrono::Utc::now),
91        expires_at: chrono::DateTime::from_timestamp(token_obj.exp, 0)
92            .unwrap_or_else(chrono::Utc::now),
93        scopes: token_obj
94            .scope
95            .split_whitespace()
96            .map(|s| s.to_string())
97            .collect(),
98        auth_method: "jwt".to_string(),
99        client_id: token_obj.client_id,
100        user_profile: None,
101        permissions: token_obj.permissions.unwrap_or_default(),
102        roles: token_obj.roles.unwrap_or_default(),
103        metadata: crate::tokens::TokenMetadata {
104            session_id: None, // JWT tokens don't have session_id in claims by default
105            ..Default::default()
106        },
107    })
108}
109
110