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