backend/service/
users.rs

1//! Service layer for user data.
2
3use actix_web::http::StatusCode;
4use uuid::Uuid;
5
6use crate::{
7    config::data::{SharedHttpClient, SharedKeycloakApi},
8    error::ServiceError,
9    keycloak_api::dtos::UserDto,
10    model::dto::{PageParameters, UserSearchParameters},
11};
12
13/// Get a user by its id.
14///
15/// # Errors
16/// * If the connection to the Keycloak API could not be established.
17pub async fn find_by_id(
18    user_id: Uuid,
19    keycloak_api: &SharedKeycloakApi,
20    http_client: &SharedHttpClient,
21) -> Result<UserDto, ServiceError> {
22    let user = keycloak_api
23        .get_user_by_id(http_client, user_id)
24        .await
25        .map_err(|e| {
26            log::error!("Error getting user data from Keycloak API: {e}");
27            ServiceError::new(
28                StatusCode::INTERNAL_SERVER_ERROR,
29                "Error getting user data from Keycloak API",
30            )
31        })?;
32
33    Ok(user)
34}
35
36/// Get users by their ids.
37///
38/// # Errors
39/// * If the connection to the Keycloak API could not be established.
40pub async fn find_by_ids(
41    user_ids: Vec<Uuid>,
42    keycloak_api: &SharedKeycloakApi,
43    http_client: &SharedHttpClient,
44) -> Result<Vec<UserDto>, ServiceError> {
45    let users = keycloak_api
46        .get_users_by_ids(http_client, user_ids)
47        .await
48        .map_err(|e| {
49            log::error!("Error getting user data from Keycloak API: {e}");
50            ServiceError::new(
51                StatusCode::INTERNAL_SERVER_ERROR,
52                "Error getting user data from Keycloak API",
53            )
54        })?;
55
56    Ok(users)
57}
58
59/// Search for users by their username.
60///
61/// # Errors
62/// * If the connection to the Keycloak API could not be established.
63pub async fn search_by_username(
64    search_params: &UserSearchParameters,
65    pagination: &PageParameters,
66    user_id: Uuid,
67    keycloak_api: &SharedKeycloakApi,
68    http_client: &SharedHttpClient,
69) -> Result<Vec<UserDto>, ServiceError> {
70    let users = keycloak_api
71        .search_users_by_username(search_params, pagination, http_client)
72        .await
73        .map_err(|e| {
74            log::error!("Error getting user data from Keycloak API: {e}");
75            ServiceError::new(
76                StatusCode::INTERNAL_SERVER_ERROR,
77                format!("Error getting user data from Keycloak API: {e}").as_str(),
78            )
79        })?;
80
81    // Filter out the user making the request
82    let filtered_users = users
83        .iter()
84        .filter(|user| user.id != user_id)
85        .cloned()
86        .collect::<Vec<_>>();
87
88    Ok(filtered_users)
89}