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/// Full user profile returned by the `/users/profile` and `/users/:id` endpoints.
14#[derive(Debug, Serialize)]
15pub struct UserProfile {
16    /// Unique user identifier.
17    pub id: String,
18    pub username: String,
19    pub email: String,
20    pub first_name: Option<String>,
21    pub last_name: Option<String>,
22    /// Role names assigned to this user.
23    pub roles: crate::types::Roles,
24    /// Effective permissions derived from roles and direct grants.
25    pub permissions: crate::types::Permissions,
26    /// Whether multi-factor authentication is enrolled.
27    pub mfa_enabled: bool,
28    /// Whether the user's email address has been verified.
29    pub email_verified: bool,
30    /// ISO-8601 creation timestamp.
31    pub created_at: String,
32    /// ISO-8601 last-modification timestamp.
33    pub updated_at: String,
34}
35
36/// Profile update request. Only the supplied fields are modified.
37#[derive(Debug, Deserialize)]
38pub struct UpdateProfileRequest {
39    #[serde(default)]
40    pub first_name: Option<String>,
41    #[serde(default)]
42    pub last_name: Option<String>,
43    /// New email address (must not already be registered to another user).
44    #[serde(default)]
45    pub email: Option<String>,
46}
47
48/// Password change request.
49///
50/// Both fields are required.  The server will verify `current_password` before
51/// applying the change, and will validate `new_password` against the same
52/// complexity rules used during registration.
53#[derive(Debug, Deserialize)]
54pub struct ChangePasswordRequest {
55    pub current_password: String,
56    pub new_password: String,
57}
58
59/// `GET /users/profile` — fetch the authenticated user's own profile.
60pub async fn get_profile(
61    State(state): State<ApiState>,
62    headers: HeaderMap,
63) -> ApiResponse<UserProfile> {
64    match extract_bearer_token(&headers) {
65        Some(token) => {
66            match validate_api_token(&state.auth_framework, &token).await {
67                Ok(auth_token) => {
68                    // Fetch actual user profile from storage
69                    match state
70                        .auth_framework
71                        .get_user_profile(&auth_token.user_id)
72                        .await
73                    {
74                        Ok(user_profile) => {
75                            // Check MFA status from AuthFramework
76                            let mfa_enabled =
77                                check_user_mfa_status(&state.auth_framework, &auth_token.user_id)
78                                    .await;
79
80                            // Extract first_name and last_name from the name field if available
81                            let (first_name, last_name) = if let Some(name) = &user_profile.name {
82                                let parts: Vec<&str> = name.split_whitespace().collect();
83                                if parts.len() >= 2 {
84                                    (Some(parts[0].to_string()), Some(parts[1..].join(" ")))
85                                } else if parts.len() == 1 {
86                                    (Some(parts[0].to_string()), None)
87                                } else {
88                                    (None, None)
89                                }
90                            } else {
91                                (None, None)
92                            };
93
94                            let profile = UserProfile {
95                                id: auth_token.user_id.clone(),
96                                username: user_profile
97                                    .username
98                                    .unwrap_or_else(|| format!("user_{}", auth_token.user_id)),
99                                email: user_profile.email.unwrap_or_default(),
100                                first_name,
101                                last_name,
102                                roles: auth_token.roles,
103                                permissions: auth_token.permissions,
104                                mfa_enabled,
105                                email_verified: user_profile.email_verified.unwrap_or(false),
106                                created_at: user_profile
107                                    .additional_data
108                                    .get("created_at")
109                                    .and_then(|v| v.as_str())
110                                    .unwrap_or("")
111                                    .to_string(),
112                                updated_at: user_profile
113                                    .additional_data
114                                    .get("updated_at")
115                                    .and_then(|v| v.as_str())
116                                    .unwrap_or("")
117                                    .to_string(),
118                            };
119
120                            ApiResponse::success(profile)
121                        }
122                        Err(e) => {
123                            tracing::warn!(
124                                "Failed to fetch user profile for user {}: {}",
125                                auth_token.user_id,
126                                e
127                            );
128                            // M-7: Return an error instead of a fabricated profile so callers
129                            // cannot mistake placeholder data for real user information.
130                            ApiResponse::error_typed(
131                                "PROFILE_UNAVAILABLE",
132                                "User profile could not be retrieved; please try again",
133                            )
134                        }
135                    }
136                }
137                Err(_e) => ApiResponse::error_typed("USER_ERROR", "User operation failed"),
138            }
139        }
140        None => ApiResponse::<UserProfile>::unauthorized_typed(),
141    }
142}
143
144/// `PUT /users/profile` — update the authenticated user's profile fields.
145pub async fn update_profile(
146    State(state): State<ApiState>,
147    headers: HeaderMap,
148    Json(req): Json<UpdateProfileRequest>,
149) -> ApiResponse<UserProfile> {
150    match extract_bearer_token(&headers) {
151        Some(token) => {
152            match validate_api_token(&state.auth_framework, &token).await {
153                Ok(auth_token) => {
154                    // Validate email format before storing to ensure consistency with
155                    // the public registration endpoint.
156                    if let Some(ref email) = req.email
157                        && crate::utils::validation::validate_email(email).is_err()
158                    {
159                        return ApiResponse::validation_error_typed("Invalid email format");
160                    }
161
162                    // Enforce length limits on name fields to prevent storage abuse.
163                    if req.first_name.as_deref().is_some_and(|n| n.len() > 100) {
164                        return ApiResponse::validation_error_typed(
165                            "First name must be 100 characters or fewer",
166                        );
167                    }
168                    if req.last_name.as_deref().is_some_and(|n| n.len() > 100) {
169                        return ApiResponse::validation_error_typed(
170                            "Last name must be 100 characters or fewer",
171                        );
172                    }
173
174                    // Persist updated profile to storage
175                    let storage = state.auth_framework.storage();
176                    let user_key = format!("user:{}", auth_token.user_id);
177                    let current_data = storage.get_kv(&user_key).await.ok().flatten();
178                    let mut user_json: serde_json::Value = current_data
179                        .and_then(|b| serde_json::from_slice(&b).ok())
180                        .unwrap_or_else(|| serde_json::json!({}));
181
182                    // Maintain the email reverse-lookup index so duplicate-email
183                    // detection at registration keeps working after an email change.
184                    if let Some(ref new_email) = req.email {
185                        let old_email = user_json["email"].as_str().unwrap_or("").to_string();
186                        if old_email != *new_email {
187                            // SECURITY: Verify the new email is not already claimed
188                            // by another user before updating the index.
189                            let new_email_key = format!("user:email:{}", new_email);
190                            if let Ok(Some(existing)) = storage.get_kv(&new_email_key).await {
191                                let owner = String::from_utf8_lossy(&existing).to_string();
192                                if owner != auth_token.user_id {
193                                    return ApiResponse::error_typed(
194                                        "CONFLICT",
195                                        "Email address is already in use",
196                                    );
197                                }
198                            }
199                            // Delete the old mapping.
200                            if !old_email.is_empty() {
201                                let _ = storage
202                                    .delete_kv(&format!("user:email:{}", old_email))
203                                    .await;
204                            }
205                            // Write the new email → user_id mapping.
206                            let _ = storage
207                                .store_kv(&new_email_key, auth_token.user_id.as_bytes(), None)
208                                .await;
209                        }
210                        if user_json["email"].as_str() != Some(new_email.as_str()) {
211                            // A new address has not been proven yet.
212                            user_json["email_verified"] = serde_json::json!(false);
213                        }
214                        user_json["email"] = serde_json::json!(new_email);
215                    }
216                    let name = match (&req.first_name, &req.last_name) {
217                        (Some(f), Some(l)) => Some(format!("{} {}", f, l)),
218                        (Some(f), None) => Some(f.clone()),
219                        (None, Some(l)) => Some(l.clone()),
220                        (None, None) => None,
221                    };
222                    if let Some(ref n) = name {
223                        user_json["name"] = serde_json::json!(n);
224                    }
225                    user_json["updated_at"] = serde_json::json!(chrono::Utc::now().to_rfc3339());
226
227                    if let Ok(serialized) = serde_json::to_vec(&user_json) {
228                        let _ = storage.store_kv(&user_key, &serialized, None).await;
229                    }
230
231                    tracing::info!("Profile updated for user: {}", auth_token.user_id);
232
233                    // Read back the stored values to build an accurate response.
234                    let (stored_username, stored_email, stored_created_at) = {
235                        let fresh = storage.get_kv(&user_key).await.ok().flatten();
236                        let j: serde_json::Value = fresh
237                            .and_then(|b| serde_json::from_slice(&b).ok())
238                            .unwrap_or_default();
239                        (
240                            j["username"].as_str().map(|s| s.to_string()),
241                            j["email"].as_str().unwrap_or("").to_string(),
242                            j["created_at"].as_str().unwrap_or("").to_string(),
243                        )
244                    };
245
246                    // Return updated profile response
247                    let updated_profile = UserProfile {
248                        id: auth_token.user_id.clone(),
249                        username: stored_username
250                            .unwrap_or_else(|| format!("user_{}", auth_token.user_id)),
251                        email: stored_email,
252                        first_name: req.first_name,
253                        last_name: req.last_name,
254                        roles: auth_token.roles,
255                        permissions: auth_token.permissions,
256                        mfa_enabled: check_user_mfa_status(
257                            &state.auth_framework,
258                            &auth_token.user_id,
259                        )
260                        .await,
261                        email_verified: user_json["email_verified"].as_bool().unwrap_or(false),
262                        created_at: stored_created_at,
263                        updated_at: user_json["updated_at"].as_str().unwrap_or("").to_string(),
264                    };
265
266                    ApiResponse::success(updated_profile)
267                }
268                Err(_e) => ApiResponse::error_typed("USER_ERROR", "User operation failed"),
269            }
270        }
271        None => ApiResponse::<UserProfile>::unauthorized_typed(),
272    }
273}
274
275/// `POST /users/change-password` — change the authenticated user's password.
276///
277/// The current password must be verified before the new one is accepted.
278pub async fn change_password(
279    State(state): State<ApiState>,
280    headers: HeaderMap,
281    Json(req): Json<ChangePasswordRequest>,
282) -> ApiResponse<()> {
283    if req.current_password.is_empty() || req.new_password.is_empty() {
284        return ApiResponse::validation_error("Current password and new password are required");
285    }
286
287    // Enforce the same password complexity requirements as registration.
288    if let Err(e) = crate::utils::validation::validate_password(&req.new_password) {
289        return ApiResponse::validation_error_typed(format!("{e}"));
290    }
291
292    // Check new password against known data breaches (HIBP k-anonymity API)
293    match crate::utils::breach_check::is_password_breached(&req.new_password).await {
294        Ok(true) => {
295            return ApiResponse::validation_error(
296                "This password has appeared in a known data breach. Please choose a different password.",
297            );
298        }
299        Ok(false) => {}
300        Err(_) => {} // HIBP API unreachable; fail open
301    }
302
303    match extract_bearer_token(&headers) {
304        Some(token) => {
305            match validate_api_token(&state.auth_framework, &token).await {
306                Ok(auth_token) => {
307                    // Verify current password against stored hash
308                    match state
309                        .auth_framework
310                        .verify_user_password(&auth_token.user_id, &req.current_password)
311                        .await
312                    {
313                        Ok(true) => {}
314                        Ok(false) => {
315                            return ApiResponse::validation_error("Current password is incorrect");
316                        }
317                        Err(_) => {
318                            // Return the same generic message regardless of error type
319                            // to avoid distinguishing wrong-password from storage errors.
320                            return ApiResponse::validation_error("Current password is incorrect");
321                        }
322                    }
323
324                    // Get the username (update_user_password takes username)
325                    let username = match state
326                        .auth_framework
327                        .get_username_by_id(&auth_token.user_id)
328                        .await
329                    {
330                        Ok(u) => u,
331                        Err(e) => return ApiResponse::<()>::from(e),
332                    };
333
334                    match state
335                        .auth_framework
336                        .update_user_password(&username, &req.new_password)
337                        .await
338                    {
339                        Ok(()) => {
340                            tracing::info!("Password changed for user: {}", auth_token.user_id);
341                            ApiResponse::<()>::ok_with_message("Password changed successfully")
342                        }
343                        Err(e) => ApiResponse::<()>::from(e),
344                    }
345                }
346                Err(e) => ApiResponse::<()>::from(e),
347            }
348        }
349        None => ApiResponse::<()>::unauthorized(),
350    }
351}
352
353/// `GET /users/{user_id}/profile` — fetch another user's profile (admin only).
354pub async fn get_user_profile(
355    State(state): State<ApiState>,
356    headers: HeaderMap,
357    Path(user_id): Path<String>,
358) -> ApiResponse<UserProfile> {
359    match extract_bearer_token(&headers) {
360        Some(token) => {
361            match validate_api_token(&state.auth_framework, &token).await {
362                Ok(auth_token) => {
363                    if !auth_token.roles.contains("admin") {
364                        return ApiResponse::<UserProfile>::forbidden_typed();
365                    }
366
367                    match state.auth_framework.get_user_profile(&user_id).await {
368                        Ok(user_profile) => {
369                            // Load roles from the canonical user record (same
370                            // pattern as validate_api_token) rather than hard-coding [].
371                            // Load both roles and permissions from the canonical user
372                            // record so the admin profile view stays consistent with
373                            // what validate_api_token returns for the user's own token.
374                            let user_kv_bytes = {
375                                let uk = format!("user:{}", user_id);
376                                state
377                                    .auth_framework
378                                    .storage()
379                                    .get_kv(&uk)
380                                    .await
381                                    .ok()
382                                    .flatten()
383                            };
384                            let user_kv_json: serde_json::Value = user_kv_bytes
385                                .as_deref()
386                                .and_then(|b| serde_json::from_slice(b).ok())
387                                .unwrap_or_default();
388
389                            let profile_roles: Vec<String> = user_kv_json["roles"]
390                                .as_array()
391                                .map(|a| {
392                                    a.iter()
393                                        .filter_map(|v| v.as_str().map(String::from))
394                                        .collect()
395                                })
396                                .unwrap_or_default();
397
398                            let profile_permissions: Vec<String> = user_kv_json["permissions"]
399                                .as_array()
400                                .map(|a| {
401                                    a.iter()
402                                        .filter_map(|v| v.as_str().map(String::from))
403                                        .collect()
404                                })
405                                .unwrap_or_default();
406
407                            let (first_name, last_name) = if let Some(name) = &user_profile.name {
408                                let parts: Vec<&str> = name.split_whitespace().collect();
409                                if parts.len() >= 2 {
410                                    (Some(parts[0].to_string()), Some(parts[1..].join(" ")))
411                                } else if parts.len() == 1 {
412                                    (Some(parts[0].to_string()), None)
413                                } else {
414                                    (None, None)
415                                }
416                            } else {
417                                (None, None)
418                            };
419
420                            let profile = UserProfile {
421                                id: user_id.clone(),
422                                username: user_profile
423                                    .username
424                                    .unwrap_or_else(|| format!("user_{}", user_id)),
425                                email: user_profile.email.unwrap_or_default(),
426                                first_name,
427                                last_name,
428                                roles: profile_roles.into(),
429                                permissions: profile_permissions.into(),
430                                mfa_enabled: user_profile
431                                    .additional_data
432                                    .get("mfa_enabled")
433                                    .and_then(|v| v.as_bool())
434                                    .unwrap_or(false),
435                                email_verified: user_kv_json["email_verified"]
436                                    .as_bool()
437                                    .unwrap_or(false),
438                                created_at: user_profile
439                                    .additional_data
440                                    .get("created_at")
441                                    .and_then(|v| v.as_str())
442                                    .unwrap_or("")
443                                    .to_string(),
444                                updated_at: user_profile
445                                    .additional_data
446                                    .get("updated_at")
447                                    .and_then(|v| v.as_str())
448                                    .unwrap_or("")
449                                    .to_string(),
450                            };
451                            ApiResponse::success(profile)
452                        }
453                        Err(e) => {
454                            let error_response = ApiResponse::<()>::from(e);
455                            ApiResponse::<UserProfile> {
456                                success: error_response.success,
457                                data: None,
458                                error: error_response.error,
459                                message: error_response.message,
460                            }
461                        }
462                    }
463                }
464                Err(_e) => ApiResponse::error_typed("USER_ERROR", "User operation failed"),
465            }
466        }
467        None => ApiResponse::<UserProfile>::unauthorized_typed(),
468    }
469}
470
471/// `GET /users/sessions` — list the authenticated user's active sessions.
472pub async fn get_sessions(
473    State(state): State<ApiState>,
474    headers: HeaderMap,
475) -> ApiResponse<Vec<SessionInfo>> {
476    match extract_bearer_token(&headers) {
477        Some(token) => match validate_api_token(&state.auth_framework, &token).await {
478            Ok(auth_token) => {
479                let storage = state.auth_framework.storage();
480                match storage.list_user_sessions(&auth_token.user_id).await {
481                    Ok(sessions) => {
482                        let session_list: Vec<SessionInfo> = sessions
483                            .into_iter()
484                            .filter(|s| !s.is_expired())
485                            .map(|s| SessionInfo {
486                                id: s.session_id.clone(),
487                                device: s.user_agent.unwrap_or_default(),
488                                location: String::new(),
489                                ip_address: s.ip_address.unwrap_or_default(),
490                                created_at: s.created_at.to_rfc3339(),
491                                last_active: s.last_activity.to_rfc3339(),
492                                is_current: false,
493                            })
494                            .collect();
495                        ApiResponse::success(session_list)
496                    }
497                    Err(_e) => {
498                        ApiResponse::error_typed("SESSION_ERROR", "Failed to retrieve sessions")
499                    }
500                }
501            }
502            Err(_e) => ApiResponse::error_typed("USER_ERROR", "Session operation failed"),
503        },
504        None => ApiResponse::<Vec<SessionInfo>>::unauthorized_typed(),
505    }
506}
507
508/// Summary of an active browser/device session.
509#[derive(Debug, Serialize)]
510pub struct SessionInfo {
511    /// Unique session identifier.
512    pub id: String,
513    /// User-Agent string from the session’s originating request.
514    pub device: String,
515    /// Approximate geo-location derived from the client IP (may be empty).
516    pub location: String,
517    /// Client IP address recorded at session creation.
518    pub ip_address: String,
519    /// ISO-8601 timestamp of session creation.
520    pub created_at: String,
521    /// ISO-8601 timestamp of the most recent request in this session.
522    pub last_active: String,
523    /// `true` if this session belongs to the current request.
524    pub is_current: bool,
525}
526
527/// `DELETE /users/sessions/{session_id}` — revoke a specific session.
528///
529/// Only the session owner can revoke it; attempting to revoke another user's
530/// session returns `FORBIDDEN`.
531pub async fn revoke_session(
532    State(state): State<ApiState>,
533    headers: HeaderMap,
534    Path(session_id): Path<String>,
535) -> ApiResponse<()> {
536    match extract_bearer_token(&headers) {
537        Some(token) => {
538            match validate_api_token(&state.auth_framework, &token).await {
539                Ok(auth_token) => {
540                    let storage = state.auth_framework.storage();
541
542                    // SECURITY: Verify that the session belongs to the authenticated user
543                    // before deleting it; without this check any authenticated user can
544                    // terminate any other user's session by guessing the session_id.
545                    match storage.get_session(&session_id).await {
546                        Ok(Some(ref session)) if session.user_id == auth_token.user_id => {}
547                        Ok(Some(_)) => {
548                            return ApiResponse::<()>::error_typed(
549                                "FORBIDDEN",
550                                "You do not have permission to revoke this session",
551                            );
552                        }
553                        Ok(None) => {
554                            return ApiResponse::<()>::error_typed(
555                                "NOT_FOUND",
556                                "Session not found",
557                            );
558                        }
559                        Err(e) => return ApiResponse::<()>::from(e),
560                    }
561
562                    match storage.delete_session(&session_id).await {
563                        Ok(()) => {
564                            tracing::info!("Revoked session: {}", session_id);
565                            ApiResponse::<()>::ok_with_message("Session revoked successfully")
566                        }
567                        Err(e) => ApiResponse::<()>::from(e),
568                    }
569                }
570                Err(e) => ApiResponse::<()>::from(e),
571            }
572        }
573        None => ApiResponse::<()>::unauthorized(),
574    }
575}
576
577/// Helper function for MFA status integration.
578///
579/// Delegates to the canonical implementation in [`crate::api::mfa`] which
580/// checks the `mfa_enabled:{user_id}` KV key written by the MFA verification
581/// flow.
582async fn check_user_mfa_status(
583    auth_framework: &std::sync::Arc<crate::AuthFramework>,
584    user_id: &str,
585) -> bool {
586    crate::api::mfa::check_user_mfa_status(auth_framework, user_id).await
587}