api/routes/users/
delete.rs

1use axum::{
2    extract::{State, Extension, Path},
3    http::StatusCode,
4    response::IntoResponse,
5    Json,
6};
7use sea_orm::{EntityTrait};
8use util::state::AppState;
9use crate::{
10    auth::claims::AuthUser,
11    response::ApiResponse,
12};
13use db::models::user::{Entity as UserEntity};
14
15/// DELETE /users/{user_id}
16///
17/// Delete a user by their ID. Only admins can access this endpoint.
18/// Users cannot delete their own account.
19///
20/// ### Path Parameters
21/// - `id` - The ID of the user to delete
22///
23/// ### Responses
24///
25/// - `200 OK`  
26/// ```json
27/// {
28///   "success": true,
29///   "message": "User deleted successfully"
30/// }
31/// ```
32///
33/// - `404 Not Found`  
34/// ```json
35/// {
36///   "success": false,
37///   "message": "User not found"
38/// }
39/// ```
40///
41/// - `400 Bad Request` (invalid ID format)  
42/// ```json
43/// {
44///   "success": false,
45///   "message": "Invalid user ID format"
46/// }
47/// ```
48///
49/// - `403 Forbidden`  
50/// ```json
51/// {
52///   "success": false,
53///   "message": "You cannot delete your own account"
54/// }
55/// ```
56///
57/// - `500 Internal Server Error`  
58/// ```json
59/// {
60///   "success": false,
61///   "message": "Database error: detailed error here"
62/// }
63/// ```
64pub async fn delete_user(
65    State(app_state): State<AppState>,
66    Path(user_id): Path<i64>,
67    Extension(AuthUser(claims)): Extension<AuthUser>,
68) -> impl IntoResponse {
69    let db = app_state.db();
70
71    if user_id == claims.sub {
72        return (
73            StatusCode::FORBIDDEN,
74            Json(ApiResponse::<()>::error("You cannot delete your own account")),
75        );
76    }
77
78    match UserEntity::delete_by_id(user_id).exec(db).await {
79        Ok(_) => (
80            StatusCode::OK,
81            Json(ApiResponse::success_without_data("User deleted successfully")),
82        ),
83        Err(e) => (
84            StatusCode::INTERNAL_SERVER_ERROR,
85            Json(ApiResponse::<()>::error(format!("Database error: {}", e))),
86        ),
87    }
88}