elemental-core 0.3.0

Core library for Elemental, providing common utilities and abstractions used across the project.
Documentation
use serde::{Deserialize, Serialize};

use crate::auth::accounts::{Account, AccountId};
use crate::auth::credential::{Credential, CredentialKind};
use crate::auth::protocol::microsoft::{ExchangedMinecraftSession, unix_now};

const REFRESH_SKEW_SECONDS: u64 = 300;

pub const MICROSOFT_AUTHORIZER_ID: &str = "microsoft";

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MicrosoftAccount {
    pub account_id: AccountId,
    pub username: String,
    pub uuid: String,
    pub access_token: String,
    pub refresh_token: String,
    pub client_id: String,
    pub xuid: Option<String>,
    pub expires_at: u64,
}

impl MicrosoftAccount {
    pub(crate) fn from_session(client_id: &str, session: ExchangedMinecraftSession) -> Self {
        Self {
            account_id: AccountId::derive(MICROSOFT_AUTHORIZER_ID, &session.uuid),
            username: session.username,
            uuid: session.uuid,
            access_token: session.access_token,
            refresh_token: session.refresh_token,
            client_id: client_id.to_owned(),
            xuid: session.xuid,
            expires_at: session.expires_at,
        }
    }
}

impl Account for MicrosoftAccount {
    fn account_id(&self) -> AccountId {
        self.account_id
    }

    fn authorizer_id(&self) -> &'static str {
        MICROSOFT_AUTHORIZER_ID
    }

    fn display_name(&self) -> &str {
        &self.username
    }

    fn needs_refresh(&self) -> bool {
        unix_now().saturating_add(REFRESH_SKEW_SECONDS) >= self.expires_at
    }

    fn credential(&self) -> Credential {
        Credential {
            username: self.username.clone(),
            uuid: self.uuid.clone(),
            access_token: self.access_token.clone(),
            kind: CredentialKind::Msa,
            xuid: self.xuid.clone(),
            client_id: Some(self.client_id.clone()),
            #[cfg(feature = "yggdrasil-auth")]
            auth_server: None,
        }
    }
}