junobuild_auth/state/
store.rs

1use crate::errors::{JUNO_AUTH_ERROR_NOT_CONFIGURED, JUNO_AUTH_ERROR_OPENID_DISABLED};
2use crate::state::assert::assert_set_config;
3use crate::state::heap::get_config;
4use crate::state::heap::insert_config;
5use crate::state::types::config::{AuthenticationConfig, OpenIdProviders};
6use crate::state::types::interface::SetAuthenticationConfig;
7use crate::state::{get_salt, insert_salt};
8use crate::strategies::AuthHeapStrategy;
9use junobuild_shared::ic::api::print;
10use junobuild_shared::random::raw_rand;
11
12pub fn set_config(
13    auth_heap: &impl AuthHeapStrategy,
14    proposed_config: &SetAuthenticationConfig,
15) -> Result<AuthenticationConfig, String> {
16    let current_config = get_config(auth_heap);
17
18    assert_set_config(proposed_config, &current_config)?;
19
20    let config = AuthenticationConfig::prepare(&current_config, proposed_config);
21
22    insert_config(auth_heap, &config);
23
24    Ok(config)
25}
26
27pub async fn init_salt(auth_heap: &impl AuthHeapStrategy) -> Result<(), String> {
28    let existing_salt = get_salt(auth_heap);
29
30    // Salt should be initialized only once.
31    if existing_salt.is_some() {
32        #[allow(clippy::disallowed_methods)]
33        print("Authentication salt exists. Skipping initialization.");
34        return Ok(());
35    }
36
37    let salt = raw_rand()
38        .await
39        .map_err(|e| format!("Failed to obtain authentication seed: {:?}", e))?;
40
41    insert_salt(auth_heap, &salt);
42
43    #[allow(clippy::disallowed_methods)]
44    print("Authentication salt initialized.");
45
46    Ok(())
47}
48
49pub fn get_providers(auth_heap: &impl AuthHeapStrategy) -> Result<OpenIdProviders, String> {
50    let config = get_config(auth_heap).ok_or(JUNO_AUTH_ERROR_NOT_CONFIGURED.to_string())?;
51    let openid = config
52        .openid
53        .ok_or(JUNO_AUTH_ERROR_OPENID_DISABLED.to_string())?;
54
55    Ok(openid.providers.clone())
56}