1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//! Configurations for shared data that is available to all controllers.

use std::sync::Arc;

use actix_web::web::Data;
use secrecy::ExposeSecret;

use crate::config::app::Config;
use crate::db::connection;
use crate::keycloak_api;
use crate::sse::broadcaster::Broadcaster;

/// Helper-Type - Connection pool to the database.
pub type SharedPool = Data<connection::Pool>;

/// Helper-Type - Server-Sent Events broadcaster.
pub type SharedBroadcaster = Data<Broadcaster>;

/// Helper-Type - Keycloak admin API.
pub type SharedKeycloakApi = Data<dyn keycloak_api::traits::KeycloakApi + Send + Sync + 'static>;

/// Helper-Type - Pooled HTTP client.
pub type SharedHttpClient = Data<reqwest::Client>;

/// Data-structure holding the initialized shared data.
pub struct SharedInit {
    /// Connection pool to the database.
    pub pool: SharedPool,
    /// Server-Sent Events broadcaster.
    pub broadcaster: SharedBroadcaster,
    /// Keycloak admin API.
    pub keycloak_api: SharedKeycloakApi,
    /// Pooled HTTP client.
    pub http_client: SharedHttpClient,
}

/// Initializes shared data.
///
/// # Panics
/// If the database pool can not be initialized.
#[must_use]
pub fn init(config: &Config) -> SharedInit {
    let api = Data::from(create_api(config));

    SharedInit {
        keycloak_api: api,
        pool: Data::new(connection::init_pool(config.database_url.expose_secret())),
        broadcaster: Data::new(Broadcaster::new()),
        http_client: Data::new(reqwest::Client::new()),
    }
}

/// Creates a new Keycloak API.
/// If the admin client ID and secret are not set, a mock API is created.
#[must_use]
pub fn create_api(
    config: &Config,
) -> Arc<dyn keycloak_api::traits::KeycloakApi + Send + Sync + 'static> {
    if let (Some(client_id), Some(client_secret)) = (
        config.auth_admin_client_id.clone(),
        config.auth_admin_client_secret.clone(),
    ) {
        Arc::new(keycloak_api::api::Api::new(keycloak_api::api::Config {
            token_url: config.auth_token_uri.clone(),
            client_id,
            client_secret,
        }))
    } else {
        log::info!("Using mock Keycloak API");
        Arc::new(keycloak_api::mock_api::MockApi)
    }
}