mockforge_http/handlers/auth_helpers.rs
1//! Authentication helper functions for handlers
2//!
3//! This module provides utilities for extracting user information from authenticated requests.
4
5use axum::extract::Extension;
6use uuid::Uuid;
7
8use crate::auth::types::AuthClaims;
9
10/// Optional AuthClaims extractor
11///
12/// Extracts AuthClaims from request extensions if available.
13/// This allows handlers to work with or without authentication.
14/// This is a type alias for Option<Extension<AuthClaims>> which Axum supports natively.
15pub type OptionalAuthClaims = Option<Extension<AuthClaims>>;
16
17/// Extract user ID from OptionalAuthClaims
18///
19/// Returns the user ID from AuthClaims if available, otherwise returns None.
20/// For mock server purposes, this allows handlers to work with or without authentication.
21pub fn extract_user_id_from_claims(claims: &OptionalAuthClaims) -> Option<Uuid> {
22 claims
23 .as_ref()
24 .and_then(|Extension(claims)| claims.sub.as_ref())
25 .and_then(|sub| Uuid::parse_str(sub).ok())
26}
27
28/// Extract user ID from OptionalAuthClaims with fallback
29///
30/// Returns the user ID from AuthClaims if available, otherwise returns a default UUID.
31/// This is useful for mock servers where authentication may be optional.
32pub fn extract_user_id_with_fallback(claims: &OptionalAuthClaims) -> Uuid {
33 extract_user_id_from_claims(claims).unwrap_or_else(|| {
34 // For mock server, use a deterministic default user ID
35 // In production, this should return an error if authentication is required
36 Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap()
37 })
38}
39
40/// Extract username from OptionalAuthClaims
41///
42/// Returns the username from AuthClaims if available, otherwise returns None.
43pub fn extract_username_from_claims(claims: &OptionalAuthClaims) -> Option<String> {
44 claims.as_ref().and_then(|Extension(claims)| claims.username.clone())
45}