elemental-core 0.3.0

Core library for Elemental, providing common utilities and abstractions used across the project.
Documentation
use crate::auth::accounts::AccountId;
pub use crate::auth::accounts::yggdrasil::YGGDRASIL_AUTHORIZER_ID;
use crate::auth::accounts::yggdrasil::{
    YggdrasilAccount, YggdrasilProfile, preferred_language, user_id,
};
use crate::auth::authorizers::Authorizer;
use crate::auth::error::{Error, Result};
use crate::auth::providers::yggdrasil::{YggdrasilSiteId, nidhogg_client};
use crate::http::SwappableClient;
use nidhogg::{client::Nidhogg, request::authenticate::Authenticate};

pub struct YggdrasilAuthorizer {
    pub base_url: Option<String>,
    pub username: String,
    pub password: String,
    pub client_token: Option<String>,
    http_client: Option<SwappableClient>,
}

impl YggdrasilAuthorizer {
    pub fn new(
        base_url: impl Into<String>,
        username: impl Into<String>,
        password: impl Into<String>,
    ) -> Self {
        Self {
            base_url: Some(base_url.into()),
            username: username.into(),
            password: password.into(),
            client_token: None,
            http_client: None,
        }
    }

    pub fn offline(username: impl Into<String>) -> Self {
        Self {
            base_url: None,
            username: username.into(),
            password: String::new(),
            client_token: None,
            http_client: None,
        }
    }

    pub fn with_client_token(mut self, client_token: impl Into<String>) -> Self {
        self.client_token = Some(client_token.into());
        self
    }

    /// Configures the [`SwappableClient`] used for Yggdrasil authentication requests.
    pub fn with_http_client(mut self, http_client: SwappableClient) -> Self {
        self.http_client = Some(http_client);
        self
    }

    fn client(&self) -> Result<Nidhogg> {
        let base_url = self
            .base_url
            .as_deref()
            .ok_or(Error::YggdrasilBaseUrlMissing)?;
        nidhogg_client(base_url, self.http_client.as_ref())
    }

    pub async fn authenticate(&self) -> Result<YggdrasilAccount> {
        let Some(base_url) = self.base_url.as_deref() else {
            return Ok(YggdrasilAccount::offline(self.username.clone()));
        };
        let canonical_site = YggdrasilSiteId::new(base_url);
        let base_url = canonical_site
            .as_ref()
            .map(YggdrasilSiteId::as_str)
            .unwrap_or_else(|| base_url.trim().trim_end_matches('/'));
        let response = self
            .client()?
            .authenticate(&Authenticate::new(
                self.username.clone(),
                self.password.clone(),
                self.client_token.clone(),
                true,
            ))
            .await
            .map_err(|source| Error::Yggdrasil { source })?;
        let selected_profile = response
            .selected_profile
            .as_ref()
            .or_else(|| {
                response
                    .available_profiles
                    .as_ref()
                    .and_then(|profiles| profiles.first())
            })
            .ok_or(Error::YggdrasilProfileMissing)?;

        Ok(YggdrasilAccount {
            base_url: Some(base_url.to_owned()),
            account_id: account_id(base_url, &selected_profile.id),
            user_id: user_id(response.user.as_ref()),
            preferred_language: preferred_language(response.user.as_ref()),
            access_token: response.access_token,
            client_token: response.client_token,
            selected_profile: YggdrasilProfile::from(selected_profile),
        })
    }
}

fn account_id(base_url: &str, profile_id: &str) -> AccountId {
    AccountId::derive(YGGDRASIL_AUTHORIZER_ID, &format!("{base_url}:{profile_id}"))
}

impl Authorizer for YggdrasilAuthorizer {
    type Account = YggdrasilAccount;

    async fn authorize(&self) -> Result<Self::Account> {
        self.authenticate().await
    }

    fn id() -> &'static str {
        YGGDRASIL_AUTHORIZER_ID
    }

    fn name() -> &'static str {
        "Yggdrasil"
    }
}