modality_trace_recorder_plugin/
auth.rs

1use derive_more::{Deref, Into};
2use thiserror::Error;
3use tracing::debug;
4
5#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Deref, Into)]
6pub struct AuthTokenBytes(Vec<u8>);
7
8#[derive(Copy, Clone, Debug, Error)]
9pub enum AuthTokenError {
10    #[error("An auth token is required. Provide one at the command line or via the MODALITY_AUTH_TOKEN environment variable.")]
11    AuthRequired,
12
13    #[error("Encountered an error decoding the auth token. {0}")]
14    Hex(#[from] hex::FromHexError),
15}
16
17impl AuthTokenBytes {
18    pub fn resolve(maybe_provided_hex: Option<&str>) -> Result<Self, AuthTokenError> {
19        let hex = if let Some(provided_hex) = maybe_provided_hex {
20            provided_hex.to_string()
21        } else {
22            dirs::config_dir()
23                .and_then(|config| {
24                    let file_path = config.join("modality_cli").join(".user_auth_token");
25                    debug!("Resolving auth token from default Modality auth token file");
26                    std::fs::read_to_string(file_path).ok()
27                })
28                .ok_or(AuthTokenError::AuthRequired)?
29        };
30
31        Ok(Self(hex::decode(hex.trim())?))
32    }
33}