1use 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#[derive(Debug, Serialize)]
15pub struct UserProfile {
16 pub id: String,
18 pub username: String,
19 pub email: String,
20 pub first_name: Option<String>,
21 pub last_name: Option<String>,
22 pub roles: crate::types::Roles,
24 pub permissions: crate::types::Permissions,
26 pub mfa_enabled: bool,
28 pub email_verified: bool,
30 pub created_at: String,
32 pub updated_at: String,
34}
35
36#[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 #[serde(default)]
45 pub email: Option<String>,
46}
47
48#[derive(Deserialize)]
54pub struct ChangePasswordRequest {
55 pub current_password: String,
56 pub new_password: String,
57}
58
59impl std::fmt::Debug for ChangePasswordRequest {
60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61 let mut d = f.debug_struct("ChangePasswordRequest");
62 d.field(
63 "current_password",
64 &crate::utils::redact::redacted(&self.current_password),
65 );
66 d.field(
67 "new_password",
68 &crate::utils::redact::redacted(&self.new_password),
69 );
70 d.finish()
71 }
72}
73
74pub async fn get_profile(
76 State(state): State<ApiState>,
77 headers: HeaderMap,
78) -> ApiResponse<UserProfile> {
79 match extract_bearer_token(&headers) {
80 Some(token) => {
81 match validate_api_token(&state.auth_framework, &token).await {
82 Ok(auth_token) => {
83 match state
85 .auth_framework
86 .get_user_profile(&auth_token.user_id)
87 .await
88 {
89 Ok(user_profile) => {
90 let mfa_enabled =
92 check_user_mfa_status(&state.auth_framework, &auth_token.user_id)
93 .await;
94
95 let (first_name, last_name) = if let Some(name) = &user_profile.name {
97 let parts: Vec<&str> = name.split_whitespace().collect();
98 if parts.len() >= 2 {
99 (Some(parts[0].to_string()), Some(parts[1..].join(" ")))
100 } else if parts.len() == 1 {
101 (Some(parts[0].to_string()), None)
102 } else {
103 (None, None)
104 }
105 } else {
106 (None, None)
107 };
108
109 let profile = UserProfile {
110 id: auth_token.user_id.clone(),
111 username: user_profile
112 .username
113 .unwrap_or_else(|| format!("user_{}", auth_token.user_id)),
114 email: user_profile.email.unwrap_or_default(),
115 first_name,
116 last_name,
117 roles: auth_token.roles,
118 permissions: auth_token.permissions,
119 mfa_enabled,
120 email_verified: user_profile.email_verified.unwrap_or(false),
121 created_at: user_profile
122 .additional_data
123 .get("created_at")
124 .and_then(|v| v.as_str())
125 .unwrap_or("")
126 .to_string(),
127 updated_at: user_profile
128 .additional_data
129 .get("updated_at")
130 .and_then(|v| v.as_str())
131 .unwrap_or("")
132 .to_string(),
133 };
134
135 ApiResponse::success(profile)
136 }
137 Err(e) => {
138 tracing::warn!(
139 "Failed to fetch user profile for user {}: {}",
140 auth_token.user_id,
141 e
142 );
143 ApiResponse::error_typed(
146 "PROFILE_UNAVAILABLE",
147 "User profile could not be retrieved; please try again",
148 )
149 }
150 }
151 }
152 Err(_e) => ApiResponse::error_typed("USER_ERROR", "User operation failed"),
153 }
154 }
155 None => ApiResponse::<UserProfile>::unauthorized_typed(),
156 }
157}
158
159pub async fn update_profile(
161 State(state): State<ApiState>,
162 headers: HeaderMap,
163 Json(req): Json<UpdateProfileRequest>,
164) -> ApiResponse<UserProfile> {
165 match extract_bearer_token(&headers) {
166 Some(token) => {
167 match validate_api_token(&state.auth_framework, &token).await {
168 Ok(auth_token) => {
169 if let Some(ref email) = req.email
172 && crate::utils::validation::validate_email(email).is_err()
173 {
174 return ApiResponse::validation_error_typed("Invalid email format");
175 }
176
177 if req.first_name.as_deref().is_some_and(|n| n.len() > 100) {
179 return ApiResponse::validation_error_typed(
180 "First name must be 100 characters or fewer",
181 );
182 }
183 if req.last_name.as_deref().is_some_and(|n| n.len() > 100) {
184 return ApiResponse::validation_error_typed(
185 "Last name must be 100 characters or fewer",
186 );
187 }
188
189 let storage = state.auth_framework.storage();
191 let user_key = format!("user:{}", auth_token.user_id);
192 let current_data = storage.get_kv(&user_key).await.ok().flatten();
193 let mut user_json: serde_json::Value = current_data
194 .and_then(|b| serde_json::from_slice(&b).ok())
195 .unwrap_or_else(|| serde_json::json!({}));
196
197 if let Some(ref new_email) = req.email {
200 let old_email = user_json["email"].as_str().unwrap_or("").to_string();
201 if old_email != *new_email {
202 let new_email_key = format!("user:email:{}", new_email);
205 if let Ok(Some(existing)) = storage.get_kv(&new_email_key).await {
206 let owner = String::from_utf8_lossy(&existing).to_string();
207 if owner != auth_token.user_id {
208 return ApiResponse::error_typed(
209 "CONFLICT",
210 "Email address is already in use",
211 );
212 }
213 }
214 if !old_email.is_empty() {
216 let _ = storage
217 .delete_kv(&format!("user:email:{}", old_email))
218 .await;
219 }
220 let _ = storage
222 .store_kv(&new_email_key, auth_token.user_id.as_bytes(), None)
223 .await;
224 }
225 user_json["email"] = serde_json::json!(new_email);
226 }
227 let name = match (&req.first_name, &req.last_name) {
228 (Some(f), Some(l)) => Some(format!("{} {}", f, l)),
229 (Some(f), None) => Some(f.clone()),
230 (None, Some(l)) => Some(l.clone()),
231 (None, None) => None,
232 };
233 if let Some(ref n) = name {
234 user_json["name"] = serde_json::json!(n);
235 }
236 user_json["updated_at"] = serde_json::json!(chrono::Utc::now().to_rfc3339());
237
238 if let Ok(serialized) = serde_json::to_vec(&user_json) {
239 let _ = storage.store_kv(&user_key, &serialized, None).await;
240 }
241
242 tracing::info!("Profile updated for user: {}", auth_token.user_id);
243
244 let (stored_username, stored_email, stored_created_at) = {
246 let fresh = storage.get_kv(&user_key).await.ok().flatten();
247 let j: serde_json::Value = fresh
248 .and_then(|b| serde_json::from_slice(&b).ok())
249 .unwrap_or_default();
250 (
251 j["username"].as_str().map(|s| s.to_string()),
252 j["email"].as_str().unwrap_or("").to_string(),
253 j["created_at"].as_str().unwrap_or("").to_string(),
254 )
255 };
256
257 let updated_profile = UserProfile {
259 id: auth_token.user_id.clone(),
260 username: stored_username
261 .unwrap_or_else(|| format!("user_{}", auth_token.user_id)),
262 email: stored_email,
263 first_name: req.first_name,
264 last_name: req.last_name,
265 roles: auth_token.roles,
266 permissions: auth_token.permissions,
267 mfa_enabled: check_user_mfa_status(
268 &state.auth_framework,
269 &auth_token.user_id,
270 )
271 .await,
272 email_verified: user_json["email_verified"].as_bool().unwrap_or(false),
273 created_at: stored_created_at,
274 updated_at: user_json["updated_at"].as_str().unwrap_or("").to_string(),
275 };
276
277 ApiResponse::success(updated_profile)
278 }
279 Err(_e) => ApiResponse::error_typed("USER_ERROR", "User operation failed"),
280 }
281 }
282 None => ApiResponse::<UserProfile>::unauthorized_typed(),
283 }
284}
285
286pub async fn change_password(
290 State(state): State<ApiState>,
291 headers: HeaderMap,
292 Json(req): Json<ChangePasswordRequest>,
293) -> ApiResponse<()> {
294 if req.current_password.is_empty() || req.new_password.is_empty() {
295 return ApiResponse::validation_error("Current password and new password are required");
296 }
297
298 if let Err(e) = crate::utils::validation::validate_password(&req.new_password) {
300 return ApiResponse::validation_error_typed(format!("{e}"));
301 }
302
303 match crate::utils::breach_check::is_password_breached(&req.new_password).await {
305 Ok(true) => {
306 return ApiResponse::validation_error(
307 "This password has appeared in a known data breach. Please choose a different password.",
308 );
309 }
310 Ok(false) => {}
311 Err(_) => {} }
313
314 match extract_bearer_token(&headers) {
315 Some(token) => {
316 match validate_api_token(&state.auth_framework, &token).await {
317 Ok(auth_token) => {
318 match state
320 .auth_framework
321 .verify_user_password(&auth_token.user_id, &req.current_password)
322 .await
323 {
324 Ok(true) => {}
325 Ok(false) => {
326 return ApiResponse::validation_error("Current password is incorrect");
327 }
328 Err(_) => {
329 return ApiResponse::validation_error("Current password is incorrect");
332 }
333 }
334
335 let username = match state
337 .auth_framework
338 .get_username_by_id(&auth_token.user_id)
339 .await
340 {
341 Ok(u) => u,
342 Err(e) => return ApiResponse::<()>::from(e),
343 };
344
345 match state
346 .auth_framework
347 .update_user_password(&username, &req.new_password)
348 .await
349 {
350 Ok(()) => {
351 tracing::info!("Password changed for user: {}", auth_token.user_id);
352 ApiResponse::<()>::ok_with_message("Password changed successfully")
353 }
354 Err(e) => ApiResponse::<()>::from(e),
355 }
356 }
357 Err(e) => ApiResponse::<()>::from(e),
358 }
359 }
360 None => ApiResponse::<()>::unauthorized(),
361 }
362}
363
364pub async fn get_user_profile(
366 State(state): State<ApiState>,
367 headers: HeaderMap,
368 Path(user_id): Path<String>,
369) -> ApiResponse<UserProfile> {
370 match extract_bearer_token(&headers) {
371 Some(token) => {
372 match validate_api_token(&state.auth_framework, &token).await {
373 Ok(auth_token) => {
374 if !auth_token.roles.contains("admin") {
375 return ApiResponse::<UserProfile>::forbidden_typed();
376 }
377
378 match state.auth_framework.get_user_profile(&user_id).await {
379 Ok(user_profile) => {
380 let user_kv_bytes = {
386 let uk = format!("user:{}", user_id);
387 state
388 .auth_framework
389 .storage()
390 .get_kv(&uk)
391 .await
392 .ok()
393 .flatten()
394 };
395 let user_kv_json: serde_json::Value = user_kv_bytes
396 .as_deref()
397 .and_then(|b| serde_json::from_slice(b).ok())
398 .unwrap_or_default();
399
400 let profile_roles: Vec<String> = user_kv_json["roles"]
401 .as_array()
402 .map(|a| {
403 a.iter()
404 .filter_map(|v| v.as_str().map(String::from))
405 .collect()
406 })
407 .unwrap_or_default();
408
409 let profile_permissions: Vec<String> = user_kv_json["permissions"]
410 .as_array()
411 .map(|a| {
412 a.iter()
413 .filter_map(|v| v.as_str().map(String::from))
414 .collect()
415 })
416 .unwrap_or_default();
417
418 let (first_name, last_name) = if let Some(name) = &user_profile.name {
419 let parts: Vec<&str> = name.split_whitespace().collect();
420 if parts.len() >= 2 {
421 (Some(parts[0].to_string()), Some(parts[1..].join(" ")))
422 } else if parts.len() == 1 {
423 (Some(parts[0].to_string()), None)
424 } else {
425 (None, None)
426 }
427 } else {
428 (None, None)
429 };
430
431 let profile = UserProfile {
432 id: user_id.clone(),
433 username: user_profile
434 .username
435 .unwrap_or_else(|| format!("user_{}", user_id)),
436 email: user_profile.email.unwrap_or_default(),
437 first_name,
438 last_name,
439 roles: profile_roles.into(),
440 permissions: profile_permissions.into(),
441 mfa_enabled: user_profile
442 .additional_data
443 .get("mfa_enabled")
444 .and_then(|v| v.as_bool())
445 .unwrap_or(false),
446 email_verified: user_kv_json["email_verified"]
447 .as_bool()
448 .unwrap_or(false),
449 created_at: user_profile
450 .additional_data
451 .get("created_at")
452 .and_then(|v| v.as_str())
453 .unwrap_or("")
454 .to_string(),
455 updated_at: user_profile
456 .additional_data
457 .get("updated_at")
458 .and_then(|v| v.as_str())
459 .unwrap_or("")
460 .to_string(),
461 };
462 ApiResponse::success(profile)
463 }
464 Err(e) => {
465 let error_response = ApiResponse::<()>::from(e);
466 ApiResponse::<UserProfile> {
467 success: error_response.success,
468 data: None,
469 error: error_response.error,
470 message: error_response.message,
471 }
472 }
473 }
474 }
475 Err(_e) => ApiResponse::error_typed("USER_ERROR", "User operation failed"),
476 }
477 }
478 None => ApiResponse::<UserProfile>::unauthorized_typed(),
479 }
480}
481
482pub async fn get_sessions(
484 State(state): State<ApiState>,
485 headers: HeaderMap,
486) -> ApiResponse<Vec<SessionInfo>> {
487 match extract_bearer_token(&headers) {
488 Some(token) => match validate_api_token(&state.auth_framework, &token).await {
489 Ok(auth_token) => {
490 let storage = state.auth_framework.storage();
491 match storage.list_user_sessions(&auth_token.user_id).await {
492 Ok(sessions) => {
493 let session_list: Vec<SessionInfo> = sessions
494 .into_iter()
495 .filter(|s| !s.is_expired())
496 .map(|s| SessionInfo {
497 id: s.session_id.clone(),
498 device: s.user_agent.unwrap_or_default(),
499 location: String::new(),
500 ip_address: s.ip_address.unwrap_or_default(),
501 created_at: s.created_at.to_rfc3339(),
502 last_active: s.last_activity.to_rfc3339(),
503 is_current: false,
504 })
505 .collect();
506 ApiResponse::success(session_list)
507 }
508 Err(_e) => {
509 ApiResponse::error_typed("SESSION_ERROR", "Failed to retrieve sessions")
510 }
511 }
512 }
513 Err(_e) => ApiResponse::error_typed("USER_ERROR", "Session operation failed"),
514 },
515 None => ApiResponse::<Vec<SessionInfo>>::unauthorized_typed(),
516 }
517}
518
519#[derive(Debug, Serialize)]
521pub struct SessionInfo {
522 pub id: String,
524 pub device: String,
526 pub location: String,
528 pub ip_address: String,
530 pub created_at: String,
532 pub last_active: String,
534 pub is_current: bool,
536}
537
538pub async fn revoke_session(
543 State(state): State<ApiState>,
544 headers: HeaderMap,
545 Path(session_id): Path<String>,
546) -> ApiResponse<()> {
547 match extract_bearer_token(&headers) {
548 Some(token) => {
549 match validate_api_token(&state.auth_framework, &token).await {
550 Ok(auth_token) => {
551 let storage = state.auth_framework.storage();
552
553 match storage.get_session(&session_id).await {
557 Ok(Some(ref session)) if session.user_id == auth_token.user_id => {}
558 Ok(Some(_)) => {
559 return ApiResponse::<()>::error_typed(
560 "FORBIDDEN",
561 "You do not have permission to revoke this session",
562 );
563 }
564 Ok(None) => {
565 return ApiResponse::<()>::error_typed(
566 "NOT_FOUND",
567 "Session not found",
568 );
569 }
570 Err(e) => return ApiResponse::<()>::from(e),
571 }
572
573 match storage.delete_session(&session_id).await {
574 Ok(()) => {
575 tracing::info!(
576 "Revoked session: {}",
577 crate::utils::redact::fingerprint(&session_id)
578 );
579 ApiResponse::<()>::ok_with_message("Session revoked successfully")
580 }
581 Err(e) => ApiResponse::<()>::from(e),
582 }
583 }
584 Err(e) => ApiResponse::<()>::from(e),
585 }
586 }
587 None => ApiResponse::<()>::unauthorized(),
588 }
589}
590
591async fn check_user_mfa_status(
597 auth_framework: &std::sync::Arc<crate::AuthFramework>,
598 user_id: &str,
599) -> bool {
600 crate::api::mfa::check_user_mfa_status(auth_framework, user_id).await
601}