use crate::errors::{
JUNO_AUTH_ERROR_AUTOMATION_NOT_CONFIGURED, JUNO_AUTH_ERROR_NOT_CONFIGURED,
JUNO_AUTH_ERROR_OPENID_DISABLED,
};
use crate::state::asserts::{assert_set_authentication_config, assert_set_automation_config};
use crate::state::heap::{get_automation, get_config};
use crate::state::heap::{insert_automation, insert_config};
use crate::state::types::automation::{AutomationConfig, OpenIdAutomationProviders};
use crate::state::types::config::{AuthenticationConfig, OpenIdAuthProviders};
use crate::state::types::interface::{SetAuthenticationConfig, SetAutomationConfig};
use crate::state::{get_salt, insert_salt};
use crate::strategies::AuthHeapStrategy;
use junobuild_shared::ic::api::print;
use junobuild_shared::random::raw_rand;
pub fn set_authentication_config(
auth_heap: &impl AuthHeapStrategy,
proposed_config: &SetAuthenticationConfig,
) -> Result<AuthenticationConfig, String> {
let current_config = get_config(auth_heap);
assert_set_authentication_config(proposed_config, ¤t_config)?;
let config = AuthenticationConfig::prepare(¤t_config, proposed_config);
insert_config(auth_heap, &config);
Ok(config)
}
pub fn set_automation_config(
auth_heap: &impl AuthHeapStrategy,
proposed_config: &SetAutomationConfig,
) -> Result<AutomationConfig, String> {
let current_config = get_automation(auth_heap);
assert_set_automation_config(proposed_config, ¤t_config)?;
let config = AutomationConfig::prepare(¤t_config, proposed_config);
insert_automation(auth_heap, &config);
Ok(config)
}
pub async fn init_salt(auth_heap: &impl AuthHeapStrategy) -> Result<(), String> {
let existing_salt = get_salt(auth_heap);
if existing_salt.is_some() {
#[allow(clippy::disallowed_methods)]
print("Authentication salt exists. Skipping initialization.");
return Ok(());
}
let salt = raw_rand()
.await
.map_err(|e| format!("Failed to obtain authentication seed: {:?}", e))?;
insert_salt(auth_heap, &salt);
#[allow(clippy::disallowed_methods)]
print("Authentication salt initialized.");
Ok(())
}
pub fn get_auth_providers(
auth_heap: &impl AuthHeapStrategy,
) -> Result<OpenIdAuthProviders, String> {
let config = get_config(auth_heap).ok_or(JUNO_AUTH_ERROR_NOT_CONFIGURED.to_string())?;
let openid = config
.openid
.ok_or(JUNO_AUTH_ERROR_OPENID_DISABLED.to_string())?;
Ok(openid.providers.clone())
}
pub fn get_automation_providers(
auth_heap: &impl AuthHeapStrategy,
) -> Result<OpenIdAutomationProviders, String> {
let config =
get_automation(auth_heap).ok_or(JUNO_AUTH_ERROR_AUTOMATION_NOT_CONFIGURED.to_string())?;
let openid = config
.openid
.ok_or(JUNO_AUTH_ERROR_OPENID_DISABLED.to_string())?;
Ok(openid.providers.clone())
}