1use crate::api::{
6 ApiResponse, ApiState, extract_bearer_token, responses::Pagination, validate_api_token,
7};
8use axum::{
9 Json,
10 extract::{Path, Query, State},
11 http::HeaderMap,
12};
13use serde::{Deserialize, Serialize};
14
15#[derive(Debug, Serialize)]
17pub struct UserListItem {
18 pub id: String,
19 pub username: String,
20 pub email: String,
21 pub roles: Vec<String>,
22 pub active: bool,
23 pub created_at: String,
24 pub last_login: Option<String>,
25}
26
27#[derive(Debug, Serialize)]
29pub struct UserListResponse {
30 pub users: Vec<UserListItem>,
31 pub pagination: Pagination,
32}
33
34#[derive(Debug, Deserialize)]
36pub struct UserListQuery {
37 #[serde(default = "default_page")]
38 pub page: u32,
39 #[serde(default = "default_limit")]
40 pub limit: u32,
41 #[serde(default)]
42 pub search: Option<String>,
43 #[serde(default)]
44 pub role: Option<String>,
45 #[serde(default)]
46 pub active: Option<bool>,
47}
48
49fn default_page() -> u32 {
50 1
51}
52fn default_limit() -> u32 {
53 20
54}
55
56#[derive(Deserialize)]
58pub struct CreateUserRequest {
59 pub username: String,
60 pub password: String,
61 pub email: String,
62 #[serde(default)]
63 pub first_name: Option<String>,
64 #[serde(default)]
65 pub last_name: Option<String>,
66 #[serde(default)]
67 pub roles: Vec<String>,
68 #[serde(default = "default_active")]
69 pub active: bool,
70}
71
72impl std::fmt::Debug for CreateUserRequest {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 let mut d = f.debug_struct("CreateUserRequest");
75 d.field("username", &self.username);
76 d.field("password", &crate::utils::redact::redacted(&self.password));
77 d.field("email", &self.email);
78 d.field("first_name", &self.first_name);
79 d.field("last_name", &self.last_name);
80 d.field("roles", &self.roles);
81 d.field("active", &self.active);
82 d.finish()
83 }
84}
85
86fn default_active() -> bool {
87 true
88}
89
90#[derive(Debug, Deserialize)]
92pub struct UpdateUserRolesRequest {
93 pub roles: Vec<String>,
94}
95
96#[derive(Debug, Serialize)]
98pub struct SystemStats {
99 pub total_users: u64,
100 pub active_sessions: u64,
101 pub total_tokens: u64,
102 pub failed_logins_24h: u64,
103 pub system_uptime: String,
104 pub memory_usage: String,
105 pub cpu_usage: String,
106}
107
108pub async fn list_users(
111 State(state): State<ApiState>,
112 headers: HeaderMap,
113 Query(query): Query<UserListQuery>,
114) -> ApiResponse<UserListResponse> {
115 match extract_bearer_token(&headers) {
116 Some(token) => {
117 match validate_api_token(&state.auth_framework, &token).await {
118 Ok(auth_token) => {
119 if !auth_token.roles.contains(&"admin".to_string()) {
121 return ApiResponse::<UserListResponse>::forbidden_typed();
122 }
123
124 let total_users = 150u64; let _offset = (query.page - 1) * query.limit;
127
128 let page = if query.page == 0 { 1 } else { query.page };
130 let limit = if query.limit == 0 {
131 20
132 } else {
133 query.limit.min(100)
134 }; let total_pages = ((total_users as f64) / (limit as f64)).ceil() as u32;
138 let total_pages = if total_pages == 0 { 1 } else { total_pages };
139
140 let users = vec![
141 UserListItem {
142 id: "user_1".to_string(),
143 username: "admin@example.com".to_string(),
144 email: "admin@example.com".to_string(),
145 roles: vec!["admin".to_string()],
146 active: true,
147 created_at: "2024-01-01T00:00:00Z".to_string(),
148 last_login: Some("2024-08-17T10:30:00Z".to_string()),
149 },
150 UserListItem {
151 id: "user_2".to_string(),
152 username: "user@example.com".to_string(),
153 email: "user@example.com".to_string(),
154 roles: vec!["user".to_string()],
155 active: true,
156 created_at: "2024-01-02T00:00:00Z".to_string(),
157 last_login: Some("2024-08-16T15:45:00Z".to_string()),
158 },
159 ];
160
161 let pagination = Pagination {
162 page,
163 limit,
164 total: total_users,
165 pages: total_pages,
166 };
167
168 let response = UserListResponse { users, pagination };
169
170 ApiResponse::success(response)
171 }
172 Err(e) => {
173 let error_response = ApiResponse::<()>::from(e);
175 ApiResponse::<UserListResponse> {
176 success: error_response.success,
177 data: None,
178 error: error_response.error,
179 message: error_response.message,
180 }
181 }
182 }
183 }
184 None => ApiResponse::<UserListResponse>::unauthorized_typed(),
185 }
186}
187
188pub async fn create_user(
191 State(state): State<ApiState>,
192 headers: HeaderMap,
193 Json(req): Json<CreateUserRequest>,
194) -> ApiResponse<UserListItem> {
195 if req.username.is_empty() || req.password.is_empty() || req.email.is_empty() {
197 return ApiResponse::<UserListItem>::validation_error_typed(
198 "Username, password, and email are required",
199 );
200 }
201
202 if req.password.len() < 8 {
203 return ApiResponse::<UserListItem>::validation_error_typed(
204 "Password must be at least 8 characters long",
205 );
206 }
207
208 match extract_bearer_token(&headers) {
209 Some(token) => {
210 match validate_api_token(&state.auth_framework, &token).await {
211 Ok(auth_token) => {
212 if !auth_token.roles.contains(&"admin".to_string()) {
214 return ApiResponse::forbidden_typed();
215 }
216
217 let new_user = UserListItem {
224 id: format!("user_{}", chrono::Utc::now().timestamp()),
225 username: req.username,
226 email: req.email,
227 roles: req.roles,
228 active: req.active,
229 created_at: chrono::Utc::now().to_rfc3339(),
230 last_login: None,
231 };
232
233 tracing::info!("New user created: {}", new_user.id);
234 ApiResponse::success(new_user)
235 }
236 Err(e) => {
237 let error_response = ApiResponse::<()>::from(e);
239 ApiResponse::<UserListItem> {
240 success: error_response.success,
241 data: None,
242 error: error_response.error,
243 message: error_response.message,
244 }
245 }
246 }
247 }
248 None => ApiResponse::<UserListItem>::unauthorized_typed(),
249 }
250}
251
252pub async fn update_user_roles(
255 State(state): State<ApiState>,
256 headers: HeaderMap,
257 Path(user_id): Path<String>,
258 Json(req): Json<UpdateUserRolesRequest>,
259) -> ApiResponse<()> {
260 match extract_bearer_token(&headers) {
261 Some(token) => {
262 match validate_api_token(&state.auth_framework, &token).await {
263 Ok(auth_token) => {
264 if !auth_token.roles.contains(&"admin".to_string()) {
266 return ApiResponse::forbidden();
267 }
268
269 tracing::info!("Updated roles for user {}: {:?}", user_id, req.roles);
276 ApiResponse::<()>::ok_with_message("User roles updated successfully")
277 }
278 Err(e) => e.into(),
279 }
280 }
281 None => ApiResponse::unauthorized(),
282 }
283}
284
285pub async fn delete_user(
288 State(state): State<ApiState>,
289 headers: HeaderMap,
290 Path(user_id): Path<String>,
291) -> ApiResponse<()> {
292 match extract_bearer_token(&headers) {
293 Some(token) => {
294 match validate_api_token(&state.auth_framework, &token).await {
295 Ok(auth_token) => {
296 if !auth_token.roles.contains(&"admin".to_string()) {
298 return ApiResponse::forbidden();
299 }
300
301 if auth_token.user_id == user_id {
303 return ApiResponse::validation_error("Cannot delete your own account");
304 }
305
306 tracing::info!("User deleted: {}", user_id);
313 ApiResponse::<()>::ok_with_message("User deleted successfully")
314 }
315 Err(e) => e.into(),
316 }
317 }
318 None => ApiResponse::unauthorized(),
319 }
320}
321
322#[derive(Debug, Deserialize)]
325pub struct ActivateUserRequest {
326 pub active: bool,
327}
328
329pub async fn activate_user(
330 State(state): State<ApiState>,
331 headers: HeaderMap,
332 Path(user_id): Path<String>,
333 Json(req): Json<ActivateUserRequest>,
334) -> ApiResponse<()> {
335 match extract_bearer_token(&headers) {
336 Some(token) => {
337 match validate_api_token(&state.auth_framework, &token).await {
338 Ok(auth_token) => {
339 if !auth_token.roles.contains(&"admin".to_string()) {
341 return ApiResponse::forbidden();
342 }
343
344 let action = if req.active {
350 "activated"
351 } else {
352 "deactivated"
353 };
354 tracing::info!("User {} {}", user_id, action);
355 ApiResponse::<()>::ok_with_message(format!("User {} successfully", action))
356 }
357 Err(e) => e.into(),
358 }
359 }
360 None => ApiResponse::unauthorized(),
361 }
362}
363
364pub async fn get_system_stats(
367 State(state): State<ApiState>,
368 headers: HeaderMap,
369) -> ApiResponse<SystemStats> {
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".to_string()) {
376 return ApiResponse::forbidden_typed();
377 }
378
379 let stats = SystemStats {
381 total_users: 1250,
382 active_sessions: 45,
383 total_tokens: 892,
384 failed_logins_24h: 12,
385 system_uptime: "15 days, 4 hours".to_string(),
386 memory_usage: "256 MB / 1 GB".to_string(),
387 cpu_usage: "12%".to_string(),
388 };
389
390 ApiResponse::success(stats)
391 }
392 Err(_e) => ApiResponse::error_typed("AUTH_ERROR", "Token validation failed"),
393 }
394 }
395 None => ApiResponse::unauthorized_typed(),
396 }
397}
398
399#[derive(Debug, Serialize)]
402pub struct AuditLogEntry {
403 pub id: String,
404 pub timestamp: String,
405 pub user_id: String,
406 pub action: String,
407 pub resource: String,
408 pub ip_address: String,
409 pub user_agent: String,
410 pub result: String,
411}
412
413#[derive(Debug, Serialize)]
414pub struct AuditLogResponse {
415 pub logs: Vec<AuditLogEntry>,
416 pub pagination: Pagination,
417}
418
419#[derive(Debug, Deserialize)]
420pub struct AuditLogQuery {
421 #[serde(default = "default_page")]
422 pub page: u32,
423 #[serde(default = "default_limit")]
424 pub limit: u32,
425 #[serde(default)]
426 pub user_id: Option<String>,
427 #[serde(default)]
428 pub action: Option<String>,
429 #[serde(default)]
430 pub start_date: Option<String>,
431 #[serde(default)]
432 pub end_date: Option<String>,
433}
434
435pub async fn get_audit_logs(
436 State(state): State<ApiState>,
437 headers: HeaderMap,
438 Query(query): Query<AuditLogQuery>,
439) -> ApiResponse<AuditLogResponse> {
440 match extract_bearer_token(&headers) {
441 Some(token) => {
442 match validate_api_token(&state.auth_framework, &token).await {
443 Ok(auth_token) => {
444 if !auth_token.roles.contains(&"admin".to_string()) {
446 return ApiResponse::forbidden_typed();
447 }
448
449 let total_logs = 1500u64; let _offset = (query.page - 1) * query.limit;
452
453 let page = if query.page == 0 { 1 } else { query.page };
455 let limit = if query.limit == 0 {
456 20
457 } else {
458 query.limit.min(100)
459 }; let total_pages = ((total_logs as f64) / (limit as f64)).ceil() as u32;
463 let total_pages = if total_pages == 0 { 1 } else { total_pages };
464
465 let logs = vec![
466 AuditLogEntry {
467 id: "audit_1".to_string(),
468 timestamp: "2024-08-17T10:30:00Z".to_string(),
469 user_id: "user_123".to_string(),
470 action: "login".to_string(),
471 resource: "/auth/login".to_string(),
472 ip_address: "192.168.1.100".to_string(),
473 user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64)".to_string(),
474 result: "success".to_string(),
475 },
476 AuditLogEntry {
477 id: "audit_2".to_string(),
478 timestamp: "2024-08-17T10:25:00Z".to_string(),
479 user_id: "user_456".to_string(),
480 action: "password_change".to_string(),
481 resource: "/users/change-password".to_string(),
482 ip_address: "192.168.1.101".to_string(),
483 user_agent: "Mozilla/5.0 (macOS; Intel Mac OS X 10_15_7)".to_string(),
484 result: "success".to_string(),
485 },
486 ];
487
488 let pagination = Pagination {
489 page,
490 limit,
491 total: total_logs,
492 pages: total_pages,
493 };
494
495 let response = AuditLogResponse { logs, pagination };
496
497 ApiResponse::success(response)
498 }
499 Err(_e) => ApiResponse::error_typed("AUTH_ERROR", "Token validation failed"),
500 }
501 }
502 None => ApiResponse::unauthorized_typed(),
503 }
504}