Docs.rs comments

Comments for generating the docs with cargo doc
This commit is contained in:
2026-05-09 23:00:15 +02:00
parent 8ddfe2ba14
commit b87a6ff297
19 changed files with 1447 additions and 15 deletions
+228
View File
@@ -21,6 +21,26 @@ use crate::{
models::{FilteredUser, LoginScheme, User, UserCreateScheme, UserUpdateScheme},
};
/// Registers a new user in the system.
///
/// Creates a new user account with the provided credentials. The password is hashed using Argon2
/// before being stored. Only administrators can create new users.
///
/// # Arguments
/// - `request`: User creation details including first/last name, username, admin flag, and password
///
/// # Returns
/// - `200 OK` on successful user creation
/// - `400 Bad Request` if username/password missing or user already exists
/// - `500 Internal Server Error` if database insertion fails
///
/// # Password Hashing
/// Uses Argon2 with a cryptographically secure random salt:
/// ```ignore
/// let argon = Argon2::default();
/// let salt = SaltString::generate(&mut OsRng);
/// let hashed_pwd = argon.hash_password(password.as_bytes(), &salt)?;
/// ```
pub async fn create_user(
State(data): State<Arc<AppState>>,
Json(request): Json<UserCreateScheme>,
@@ -84,6 +104,39 @@ pub async fn create_user(
}
}
/// Authenticates a user and creates a JWT token for session management.
///
/// Verifies the provided username and password against stored credentials using Argon2 verification.
/// On successful authentication, generates a JWT token and sets it as an HTTP-only cookie.
/// The token is valid for 1 hour.
///
/// # Arguments
/// - `request`: Login credentials (username, password)
///
/// # Returns
/// - `200 OK` with JSON containing token and filtered user info
/// - `400 Bad Request` if username not found or password invalid
/// - `500 Internal Server Error` if database query fails
///
/// # Security Features
/// - HTTP-only cookie prevents JavaScript access
/// - SameSite=Lax protects against CSRF attacks
/// - Password verification uses Argon2:
/// ```ignore
/// let valid_pwd = Argon2::default()
/// .verify_password(&request.pwd.as_bytes(), &pwd_hash.unwrap())
/// .is_ok();
/// ```
/// - JWT token includes user ID and expiration timestamp
///
/// # Example Response
/// ```json
/// {
/// "status": "success",
/// "token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
/// "user": {"id": 1, "first_name": "Admin", "last_name": "User", "username": "admin", "is_admin": true}
/// }
/// ```
pub async fn login(
State(data): State<Arc<AppState>>,
Json(request): Json<LoginScheme>,
@@ -139,6 +192,24 @@ pub async fn login(
Ok(response)
}
/// Logs out the current user by invalidating their session cookie.
///
/// Sets the authentication cookie to expire immediately (max_age = -1 hour) which causes
/// the browser to discard it. This effectively logs the user out without requiring server-side
/// session invalidation.
///
/// # Returns
/// Always returns `200 OK` with success message and an expired cookie header
///
/// # Security
/// - HTTP-only cookie prevents client-side manipulation
/// - SameSite=Lax protects against CSRF
/// - Setting max_age to negative value causes immediate expiration
///
/// # Example Response
/// ```json
/// {"status": "success", "message": "successfully logged out"}
/// ```
pub async fn logout() -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
let cookie = Cookie::build(("token", ""))
.path("/")
@@ -155,6 +226,27 @@ pub async fn logout() -> Result<impl IntoResponse, (StatusCode, Json<serde_json:
Ok(response)
}
/// Retrieves the currently authenticated user's information.
///
/// Uses the user data embedded in the JWT token (via middleware).
/// Useful for frontends to display logged-in user info or verify authentication.
///
/// # Returns
/// - `200 OK` with user data (excluding password)
/// - Automatically returns `401 Unauthorized` if not authenticated (middleware)
///
/// # Example Response
/// ```json
/// {
/// "status": "success",
/// "data": {
/// "id": 1,
/// "first_name": "Admin",
/// "last_name": "User",
/// "is_admin": true
/// }
/// }
/// ```
pub async fn get_current_user(
Extension(user): Extension<FilteredUser>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
@@ -171,6 +263,18 @@ pub async fn get_current_user(
Ok(Json(response))
}
/// Deletes a user account from the system.
///
/// Only admins can delete users. The user account and all associated data is removed.
/// Note: Tickets created by deleted users will have NULL user_id references.
///
/// # Arguments
/// - `id`: User ID to delete
///
/// # Returns
/// - `204 No Content` on successful deletion
/// - `404 Not Found` if user doesn't exist
/// - `500 Internal Server Error` if database error occurs
pub async fn delete_user(
Path(id): Path<i32>,
State(data): State<Arc<AppState>>,
@@ -197,6 +301,34 @@ pub async fn delete_user(
Ok(StatusCode::NO_CONTENT)
}
/// Retrieves all users in the system.
///
/// Only admins can call this endpoint. Returns all users sorted alphabetically by last name.
/// Password hashes are not included in the response.
///
/// # Returns
/// - `200 OK` with array of FilteredUser objects
/// - `500 Internal Server Error` if database query fails
///
/// # Example Response
/// ```json
/// [
/// {
/// "id": 1,
/// "first_name": "Admin",
/// "last_name": "User",
/// "username": "admin",
/// "is_admin": true
/// },
/// {
/// "id": 2,
/// "first_name": "Regular",
/// "last_name": "User",
/// "username": "regularuser",
/// "is_admin": false
/// }
/// ]
/// ```
pub async fn get_users(
State(data): State<Arc<AppState>>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
@@ -219,6 +351,20 @@ pub async fn get_users(
Ok(Json(json_respnse))
}
/// Retrieves a single user's details by their ID.
///
/// This endpoint allows fetching a specific user's information. It returns a `FilteredUser`
/// object, ensuring sensitive data like password hashes are not exposed.
///
/// # Arguments
/// - `Path(id)`: The ID of the user to retrieve, extracted from the URL path.
/// - `State(data)`: Application state containing `AppState` for database access.
///
/// # Returns
/// - `200 OK` with a `FilteredUser` JSON object if the user is found.
/// - `404 Not Found` if a user with the given ID does not exist.
/// - `500 Internal Server Error` if a database query error occurs.
///
pub async fn get_user_by_id(
Path(id): Path<i16>,
State(data): State<Arc<AppState>>,
@@ -249,6 +395,25 @@ pub async fn get_user_by_id(
};
}
/// Updates an existing user's information.
///
/// This endpoint allows administrators to modify a user's `first_name`, `last_name`,
/// `username`, `is_admin` status, and optionally their password. If `new_pwd` in the
/// request body is an empty string, the user's password remains unchanged.
///
/// # Arguments
/// - `Path(id)`: The ID of the user to update, extracted from the URL path.
/// - `State(data)`: Application state containing `AppState` for database access.
/// - `Json(body)`: `UserUpdateScheme` containing the fields to update.
///
/// # Returns
/// - `200 OK` with the `FilteredUser` object of the updated user.
/// - `404 Not Found` if a user with the given ID does not exist.
/// - `500 Internal Server Error` if a database query or password hashing error occurs.
///
/// # Security Note
/// - Passwords are hashed using Argon2 before storage.
/// - This endpoint typically requires admin privileges (enforced by middleware).
pub async fn update_user(
Path(id): Path<i32>,
State(data): State<Arc<AppState>>,
@@ -304,6 +469,19 @@ pub async fn update_user(
Ok(Json(response))
}
/// Checks if any administrator user exists in the system.
///
/// This endpoint is used during initialization to determine if the setup page should be displayed.
/// It counts all users with `is_admin = true` in the database.
///
/// # Returns
/// - `200 OK` with JSON: `{"has_admin": bool}` - Whether at least one admin exists
/// - `500 Internal Server Error` if database query fails
///
/// # Example Response
/// ```json
/// {"has_admin": false}
/// ```
pub async fn check_admin_exists(
State(data): State<Arc<AppState>>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
@@ -321,6 +499,30 @@ pub async fn check_admin_exists(
Ok(Json(json!({"has_admin": has_admin})))
}
/// Creates the initial administrator account for a fresh system.
///
/// This function handles the one-time setup of the first admin user. It checks that no admin exists
/// before allowing creation. This endpoint is only functional when the system has no administrators.
/// Once created, subsequent admin registrations must go through the normal `create_user` endpoint
/// with proper authorization.
///
/// # Arguments
/// - `request`: User creation details (first_name, last_name, username, password)
///
/// # Returns
/// - `200 OK` with success message if admin account created
/// - `400 Bad Request` if:
/// - Admin already exists
/// - Username or password is empty
/// - `500 Internal Server Error` if database insertion fails
///
/// # Security Note
/// The password is hashed using Argon2 with a random salt before storage:
/// ```ignore
/// let argon = Argon2::default();
/// let salt = SaltString::generate(&mut OsRng);
/// let hashed_pwd = argon.hash_password(request.pwd.as_bytes(), &salt)?;
/// ```
pub async fn setup_initial_admin(
State(data): State<Arc<AppState>>,
Json(request): Json<UserCreateScheme>,
@@ -382,6 +584,32 @@ pub async fn setup_initial_admin(
}
}
/// Converts a User with sensitive data into a FilteredUser safe for API responses.
///
/// This function removes password hashes and other sensitive information before
/// returning user data to clients. Always use this helper instead of directly
/// serializing User objects.
///
/// # Arguments
/// - `user`: Reference to the internal User struct containing password hash
///
/// # Returns
/// FilteredUser with only safe-to-share information:
/// - `id`: User ID
/// - `first_name`, `last_name`: User name
/// - `username`: Login username
/// - `is_admin`: Admin privilege flag
///
/// # Important
/// The password hash is explicitly **NOT** included in the output. This prevents
/// accidental exposure of sensitive authentication data.
///
/// # Example
/// ```ignore
/// let user = get_user_from_db(1).await?;
/// let safe_user = filter_user(&user);
/// // safe_user can be safely serialized and sent to client
/// ```
pub fn filter_user(user: &User) -> FilteredUser {
FilteredUser {
id: user.id,
+4
View File
@@ -1,2 +1,6 @@
//! This module aggregates and re-exports all API endpoint handler functions.
//!
//! It serves as a central point for managing the logic that responds to various
//! HTTP requests, categorizing handlers by their domain (e.g., authentication, tickets).
pub mod auth;
pub mod ticket;
+107 -3
View File
@@ -14,6 +14,23 @@ use crate::{
models::{FilteredUser, TicketCreateScheme, TicketResponse, TicketUpdateScheme},
};
/// Creates a new support ticket.
///
/// Associates the ticket with the authenticated user and sets the current timestamp.
/// Tickets are automatically created with "open" status.
///
/// # Arguments
/// - `user`: Authenticated user (extracted from JWT token)
/// - `body`: Ticket details (category, subject, description, room)
///
/// # Returns
/// - `200 OK` on successful creation
/// - `500 Internal Server Error` if database insertion fails
///
/// # Database Fields Set Automatically
/// - `user_id`: From authenticated user
/// - `status`: Defaults to "open"
/// - `date`: Current UTC timestamp
pub async fn create_ticket(
Extension(user): Extension<FilteredUser>,
State(data): State<Arc<AppState>>,
@@ -41,6 +58,17 @@ pub async fn create_ticket(
Ok(Json(response_status))
}
/// Deletes a ticket by ID.
///
/// Only admins can delete tickets. Marks the ticket as deleted or removes from database.
///
/// # Arguments
/// - `id`: Ticket ID to delete
///
/// # Returns
/// - `204 No Content` on successful deletion
/// - `404 Not Found` if ticket doesn't exist
/// - `500 Internal Server Error` if database error occurs
pub async fn delete_ticket(
Path(id): Path<i32>,
State(data): State<Arc<AppState>>,
@@ -67,10 +95,40 @@ pub async fn delete_ticket(
Ok(StatusCode::NO_CONTENT)
}
/// Retrieves all non-archived tickets.
///
/// Returns a list of all active tickets with user information denormalized for easier rendering.
/// Tickets are ordered by creation date (newest first).
///
/// # Filtering
/// - Excludes tickets with status "Archived"
/// - Uses LEFT JOIN to include creator information
///
/// # Returns
/// - `200 OK` with array of TicketResponse objects
/// - `500 Internal Server Error` if database query fails
///
/// # Example Response
/// ```json
/// [
/// {
/// "id": 1,
/// "category": "maintenance",
/// "betreff": "Broken light",
/// "description": "Ceiling light not working",
/// "room": 101,
/// "status": "open",
/// "date": "2024-01-15T10:30:00Z",
/// "user_id": 5,
/// "user_first_name": "John",
/// "user_last_name": "Doe"
/// }
/// ]
/// ```
pub async fn get_tickets(
State(data): State<Arc<AppState>>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
println!("get_tickets called");
// Query tickets with denormalized user info, excluding archived tickets
let tickets = sqlx::query(
r#"SELECT t.id, t.category, t.betreff, t.description, t.room, t.status, t.date, t.user_id, u.first_name, u.last_name
FROM tickets t
@@ -86,8 +144,8 @@ pub async fn get_tickets(
});
(StatusCode::INTERNAL_SERVER_ERROR, Json(error_response))
})?;
println!("Tickets fetched");
// Transform raw database rows into TicketResponse structs
let ticket_response: Vec<TicketResponse> = tickets
.iter()
.map(|row| TicketResponse {
@@ -105,10 +163,36 @@ pub async fn get_tickets(
.collect();
let json_response = serde_json::json!(ticket_response);
println!("Json contructed");
Ok(Json(json_response))
}
/// Retrieves a specific ticket by ID.
///
/// Includes full ticket details and denormalized user information (creator name).
///
/// # Arguments
/// - `id`: Ticket ID to retrieve
///
/// # Returns
/// - `200 OK` with TicketResponse object
/// - `404 Not Found` if ticket doesn't exist
/// - `500 Internal Server Error` if database error occurs
///
/// # Example Response
/// ```json
/// {
/// "id": 1,
/// "category": "maintenance",
/// "betreff": "Broken light in room 101",
/// "description": "The ceiling light is not working",
/// "room": 101,
/// "status": "open",
/// "date": "2024-01-15T10:30:00Z",
/// "user_id": 5,
/// "user_first_name": "John",
/// "user_last_name": "Doe"
/// }
/// ```
pub async fn get_ticket_by_id(
Path(id): Path<i32>,
State(data): State<Arc<AppState>>,
@@ -156,11 +240,30 @@ pub async fn get_ticket_by_id(
};
}
/// Updates a ticket's status.
///
/// Only admins can update ticket status. This is typically used to transition tickets
/// through their lifecycle (open → in_progress → resolved → archived).
///
/// # Arguments
/// - `id`: Ticket ID to update
/// - `body`: Update payload containing new status
///
/// # Returns
/// - `200 OK` with updated TicketResponse
/// - `500 Internal Server Error` if ticket not found or database error
///
/// # Typical Status Flow
/// - `open`: Initial state, waiting for action
/// - `in_progress`: Currently being worked on
/// - `resolved`: Issue fixed
/// - `archived`: Closed/hidden from normal view
pub async fn edit_ticket(
Path(id): Path<i32>,
State(data): State<Arc<AppState>>,
Json(body): Json<TicketUpdateScheme>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
// Update the ticket status
let update_result = sqlx::query(r#"UPDATE tickets SET status = $1 WHERE id = $2"#)
.bind(body.status.to_owned())
.bind(id)
@@ -181,6 +284,7 @@ pub async fn edit_ticket(
return Err((StatusCode::INTERNAL_SERVER_ERROR, Json(error_response)));
}
// Fetch and return the updated ticket
let updated_ticket = sqlx::query(
r#"SELECT t.id, t.category, t.betreff, t.description, t.room, t.status, t.date, t.user_id, u.first_name, u.last_name
FROM tickets t