Skip to main content

auth_framework/api/
users.rs

1//! User Management API Endpoints
2//!
3//! Handles user profile, password changes, and related user operations
4
5use crate::api::{ApiResponse, ApiState, extract_bearer_token, validate_api_token};
6use axum::{
7    Json,
8    extract::{Path, State},
9    http::HeaderMap,
10};
11use serde::{Deserialize, Serialize};
12
13/// User profile information
14#[derive(Debug, Serialize)]
15pub struct UserProfile {
16    pub id: String,
17    pub username: String,
18    pub email: String,
19    pub first_name: Option<String>,
20    pub last_name: Option<String>,
21    pub roles: Vec<String>,
22    pub permissions: Vec<String>,
23    pub mfa_enabled: bool,
24    pub created_at: String,
25    pub updated_at: String,
26}
27
28/// Update profile request
29#[derive(Debug, Deserialize)]
30pub struct UpdateProfileRequest {
31    #[serde(default)]
32    pub first_name: Option<String>,
33    #[serde(default)]
34    pub last_name: Option<String>,
35    #[serde(default)]
36    pub email: Option<String>,
37}
38
39/// Change password request
40#[derive(Deserialize)]
41pub struct ChangePasswordRequest {
42    pub current_password: String,
43    pub new_password: String,
44}
45
46impl std::fmt::Debug for ChangePasswordRequest {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        let mut d = f.debug_struct("ChangePasswordRequest");
49        d.field(
50            "current_password",
51            &crate::utils::redact::redacted(&self.current_password),
52        );
53        d.field(
54            "new_password",
55            &crate::utils::redact::redacted(&self.new_password),
56        );
57        d.finish()
58    }
59}
60
61/// GET /users/profile
62/// Get current user profile
63pub async fn get_profile(
64    State(state): State<ApiState>,
65    headers: HeaderMap,
66) -> ApiResponse<UserProfile> {
67    match extract_bearer_token(&headers) {
68        Some(token) => {
69            match validate_api_token(&state.auth_framework, &token).await {
70                Ok(auth_token) => {
71                    // Fetch actual user profile from storage
72                    match state
73                        .auth_framework
74                        .get_user_profile(&auth_token.user_id)
75                        .await
76                    {
77                        Ok(user_profile) => {
78                            // Check MFA status from AuthFramework
79                            let mfa_enabled =
80                                check_user_mfa_status(&state.auth_framework, &auth_token.user_id)
81                                    .await;
82
83                            // Extract first_name and last_name from the name field if available
84                            let (first_name, last_name) = if let Some(name) = &user_profile.name {
85                                let parts: Vec<&str> = name.split_whitespace().collect();
86                                if parts.len() >= 2 {
87                                    (Some(parts[0].to_string()), Some(parts[1..].join(" ")))
88                                } else if parts.len() == 1 {
89                                    (Some(parts[0].to_string()), None)
90                                } else {
91                                    (None, None)
92                                }
93                            } else {
94                                (None, None)
95                            };
96
97                            let profile = UserProfile {
98                                id: auth_token.user_id.clone(),
99                                username: user_profile
100                                    .username
101                                    .unwrap_or_else(|| format!("user_{}", auth_token.user_id)),
102                                email: user_profile.email.unwrap_or_else(|| {
103                                    format!("{}@example.com", auth_token.user_id)
104                                }),
105                                first_name,
106                                last_name,
107                                roles: auth_token.roles,
108                                permissions: auth_token.permissions,
109                                mfa_enabled,
110                                created_at: chrono::Utc::now().to_rfc3339(), // Default to current time
111                                updated_at: chrono::Utc::now().to_rfc3339(),
112                            };
113
114                            ApiResponse::success(profile)
115                        }
116                        Err(e) => {
117                            tracing::warn!(
118                                "Failed to fetch user profile for user {}: {}",
119                                auth_token.user_id,
120                                e
121                            );
122
123                            // Fallback profile if storage fetch fails
124                            let profile = UserProfile {
125                                id: auth_token.user_id.clone(),
126                                username: format!("user_{}", auth_token.user_id),
127                                email: format!("{}@example.com", auth_token.user_id),
128                                first_name: Some("Unknown".to_string()),
129                                last_name: Some("User".to_string()),
130                                roles: auth_token.roles,
131                                permissions: auth_token.permissions,
132                                mfa_enabled: false,
133                                created_at: "2024-01-01T00:00:00Z".to_string(),
134                                updated_at: chrono::Utc::now().to_rfc3339(),
135                            };
136
137                            ApiResponse::success(profile)
138                        }
139                    }
140                }
141                Err(_e) => ApiResponse::error_typed("USER_ERROR", "User operation failed"),
142            }
143        }
144        None => ApiResponse::<UserProfile>::unauthorized_typed(),
145    }
146}
147
148/// PUT /users/profile
149/// Update user profile
150pub async fn update_profile(
151    State(state): State<ApiState>,
152    headers: HeaderMap,
153    Json(req): Json<UpdateProfileRequest>,
154) -> ApiResponse<UserProfile> {
155    match extract_bearer_token(&headers) {
156        Some(token) => {
157            match validate_api_token(&state.auth_framework, &token).await {
158                Ok(auth_token) => {
159                    // Update user profile in storage
160                    let updated_profile_data = crate::providers::UserProfile {
161                        id: Some(auth_token.user_id.clone()),
162                        provider: Some("local".to_string()),
163                        username: Some(format!("user_{}", auth_token.user_id)),
164                        name: match (&req.first_name, &req.last_name) {
165                            (Some(first), Some(last)) => Some(format!("{} {}", first, last)),
166                            (Some(first), None) => Some(first.clone()),
167                            (None, Some(last)) => Some(last.clone()),
168                            (None, None) => None,
169                        },
170                        email: req.email.clone(),
171                        email_verified: Some(false),
172                        picture: None,
173                        locale: None,
174                        additional_data: std::collections::HashMap::new(),
175                    };
176
177                    // Store updated profile (in a real implementation, update storage)
178                    tracing::info!(
179                        "Updating profile for user: {} with data: {:?}",
180                        auth_token.user_id,
181                        updated_profile_data
182                    );
183
184                    // Return updated profile response
185                    let updated_profile = UserProfile {
186                        id: auth_token.user_id.clone(),
187                        username: format!("user_{}", auth_token.user_id),
188                        email: req
189                            .email
190                            .unwrap_or_else(|| format!("{}@example.com", auth_token.user_id)),
191                        first_name: req.first_name,
192                        last_name: req.last_name,
193                        roles: auth_token.roles,
194                        permissions: auth_token.permissions,
195                        mfa_enabled: check_user_mfa_status(
196                            &state.auth_framework,
197                            &auth_token.user_id,
198                        )
199                        .await,
200                        created_at: chrono::Utc::now().to_rfc3339(), // Default to current time
201                        updated_at: chrono::Utc::now().to_rfc3339(),
202                    };
203
204                    ApiResponse::success(updated_profile)
205                }
206                Err(_e) => ApiResponse::error_typed("USER_ERROR", "User operation failed"),
207            }
208        }
209        None => ApiResponse::<UserProfile>::unauthorized_typed(),
210    }
211}
212
213/// POST /users/change-password
214/// Change user password
215pub async fn change_password(
216    State(state): State<ApiState>,
217    headers: HeaderMap,
218    Json(req): Json<ChangePasswordRequest>,
219) -> ApiResponse<()> {
220    if req.current_password.is_empty() || req.new_password.is_empty() {
221        return ApiResponse::validation_error("Current password and new password are required");
222    }
223
224    if req.new_password.len() < 8 {
225        return ApiResponse::validation_error("New password must be at least 8 characters long");
226    }
227
228    match extract_bearer_token(&headers) {
229        Some(token) => {
230            match validate_api_token(&state.auth_framework, &token).await {
231                Ok(auth_token) => {
232                    // In a real implementation:
233                    // 1. Verify current password
234                    // 2. Hash new password
235                    // 3. Update password in storage
236                    // 4. Optionally invalidate all existing sessions
237
238                    tracing::info!("Password changed for user: {}", auth_token.user_id);
239                    ApiResponse::<()>::ok_with_message("Password changed successfully")
240                }
241                Err(e) => ApiResponse::<()>::from(e),
242            }
243        }
244        None => ApiResponse::<()>::unauthorized(),
245    }
246}
247
248/// GET /users/{user_id}/profile
249/// Get specific user profile (admin only)
250pub async fn get_user_profile(
251    State(state): State<ApiState>,
252    headers: HeaderMap,
253    Path(user_id): Path<String>,
254) -> ApiResponse<UserProfile> {
255    match extract_bearer_token(&headers) {
256        Some(token) => {
257            match validate_api_token(&state.auth_framework, &token).await {
258                Ok(auth_token) => {
259                    // Check if user has admin permissions
260                    if !auth_token.roles.contains(&"admin".to_string()) {
261                        return ApiResponse::<UserProfile>::forbidden_typed();
262                    }
263
264                    // In a real implementation, fetch user profile from storage
265                    let profile = UserProfile {
266                        id: user_id.clone(),
267                        username: format!("user_{}", user_id),
268                        email: format!("{}@example.com", user_id),
269                        first_name: Some("User".to_string()),
270                        last_name: Some("Name".to_string()),
271                        roles: vec!["user".to_string()],
272                        permissions: vec!["read:profile".to_string()],
273                        mfa_enabled: false,
274                        created_at: "2024-01-01T00:00:00Z".to_string(),
275                        updated_at: "2024-01-01T00:00:00Z".to_string(),
276                    };
277
278                    ApiResponse::success(profile)
279                }
280                Err(_e) => ApiResponse::error_typed("USER_ERROR", "User operation failed"),
281            }
282        }
283        None => ApiResponse::<UserProfile>::unauthorized_typed(),
284    }
285}
286
287/// GET /users/sessions
288/// Get user's active sessions
289pub async fn get_sessions(
290    State(state): State<ApiState>,
291    headers: HeaderMap,
292) -> ApiResponse<Vec<SessionInfo>> {
293    match extract_bearer_token(&headers) {
294        Some(token) => {
295            match validate_api_token(&state.auth_framework, &token).await {
296                Ok(_auth_token) => {
297                    // In a real implementation, fetch sessions from storage
298                    let sessions = vec![
299                        SessionInfo {
300                            id: "session_1".to_string(),
301                            device: "Chrome on Windows".to_string(),
302                            location: "New York, NY".to_string(),
303                            ip_address: "192.168.1.1".to_string(),
304                            created_at: "2024-01-01T10:00:00Z".to_string(),
305                            last_active: "2024-01-01T12:00:00Z".to_string(),
306                            is_current: true,
307                        },
308                        SessionInfo {
309                            id: "session_2".to_string(),
310                            device: "Safari on iPhone".to_string(),
311                            location: "San Francisco, CA".to_string(),
312                            ip_address: "10.0.0.1".to_string(),
313                            created_at: "2023-12-30T08:00:00Z".to_string(),
314                            last_active: "2023-12-31T09:30:00Z".to_string(),
315                            is_current: false,
316                        },
317                    ];
318
319                    ApiResponse::success(sessions)
320                }
321                Err(_e) => ApiResponse::error_typed("USER_ERROR", "Session operation failed"),
322            }
323        }
324        None => ApiResponse::<Vec<SessionInfo>>::unauthorized_typed(),
325    }
326}
327
328/// Session information
329#[derive(Debug, Serialize)]
330pub struct SessionInfo {
331    pub id: String,
332    pub device: String,
333    pub location: String,
334    pub ip_address: String,
335    pub created_at: String,
336    pub last_active: String,
337    pub is_current: bool,
338}
339
340/// DELETE /users/sessions/{session_id}
341/// Revoke a specific session
342pub async fn revoke_session(
343    State(state): State<ApiState>,
344    headers: HeaderMap,
345    Path(session_id): Path<String>,
346) -> ApiResponse<()> {
347    match extract_bearer_token(&headers) {
348        Some(token) => {
349            match validate_api_token(&state.auth_framework, &token).await {
350                Ok(_auth_token) => {
351                    // In a real implementation, remove session from storage
352                    tracing::info!(
353                        "Revoking session: {}",
354                        crate::utils::redact::fingerprint(&session_id)
355                    );
356                    ApiResponse::<()>::ok_with_message("Session revoked successfully")
357                }
358                Err(e) => ApiResponse::<()>::from(e),
359            }
360        }
361        None => ApiResponse::<()>::unauthorized(),
362    }
363}
364
365/// Helper function for MFA status integration
366async fn check_user_mfa_status(
367    auth_framework: &std::sync::Arc<crate::AuthFramework>,
368    user_id: &str,
369) -> bool {
370    // Check if user has MFA enabled in storage
371    // This is a simplified check - in a real implementation, you would query the MFA service
372    match auth_framework.get_user_profile(user_id).await {
373        Ok(profile) => {
374            // Check for MFA-related attributes in user profile
375            profile
376                .additional_data
377                .get("mfa_enabled")
378                .and_then(|v| v.as_bool())
379                .unwrap_or(false)
380        }
381        Err(_) => false, // Default to false if profile fetch fails
382    }
383}