aboutsummaryrefslogtreecommitdiff
path: root/crates/secd/src/command/mod.rs
blob: c14cf6c7a81c87e30da3ba4934d0300ff4d055ed (plain)
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
73
74
pub mod authn;

use super::{AuthEmailMessenger, AuthStore, Secd, SecdError};
use crate::{
    client::{
        email,
        store::sql_db::{PgClient, SqliteClient},
    },
    ENV_AUTH_STORE_CONN_STRING, ENV_EMAIL_MESSENGER, ENV_EMAIL_MESSENGER_CLIENT_ID,
    ENV_EMAIL_MESSENGER_CLIENT_SECRET,
};
use log::{error, info};
use std::{env::var, str::FromStr, sync::Arc};

impl Secd {
    /// init
    ///
    /// Initialize SecD with the specified configuration, established the necessary
    /// constraints, persistance stores, and options.
    pub async fn init() -> Result<Self, SecdError> {
        let auth_store = AuthStore::from(var(ENV_AUTH_STORE_CONN_STRING).ok());
        let email_messenger = AuthEmailMessenger::from_str(
            &var(ENV_EMAIL_MESSENGER).unwrap_or(AuthEmailMessenger::Local.to_string()),
        )
        .expect("unreachable f4ad0f48-0812-427f-b477-0f9c67bb69c5");
        let email_messenger_client_id = var(ENV_EMAIL_MESSENGER_CLIENT_ID).ok();
        let email_messenger_client_secret = var(ENV_EMAIL_MESSENGER_CLIENT_SECRET).ok();

        info!("starting client with auth_store: {:?}", auth_store);
        info!("starting client with email_messenger: {:?}", auth_store);

        let store = match auth_store {
            AuthStore::Sqlite { conn } => {
                SqliteClient::new(
                    sqlx::sqlite::SqlitePoolOptions::new()
                        .connect(&conn)
                        .await
                        .map_err(|e| {
                            SecdError::StoreInitFailure(format!("failed to init sqlite: {}", e))
                        })?,
                )
                .await
            }
            AuthStore::Postgres { conn } => {
                PgClient::new(
                    sqlx::postgres::PgPoolOptions::new()
                        .connect(&conn)
                        .await
                        .map_err(|e| {
                            SecdError::StoreInitFailure(format!("failed to init sqlite: {}", e))
                        })?,
                )
                .await
            }
            rest @ _ => {
                error!(
                    "requested an AuthStore which has not yet been implemented: {:?}",
                    rest
                );
                unimplemented!()
            }
        };

        let email_sender = match email_messenger {
            AuthEmailMessenger::Local => email::LocalMailer {},
            _ => unimplemented!(),
        };

        Ok(Secd {
            store,
            email_messenger: Arc::new(email_sender),
        })
    }
}