From 01fd545429d75c6ca5ea0015d9519ab68b1cb574 Mon Sep 17 00:00:00 2001 From: Ammar Arif Date: Fri, 14 Jun 2024 17:34:04 -0400 Subject: [PATCH] add comment --- src/session.rs | 40 +++++++++++++++++++++++++++++++--------- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/src/session.rs b/src/session.rs index 8a70c24..49e2b2f 100644 --- a/src/session.rs +++ b/src/session.rs @@ -40,16 +40,33 @@ pub struct SessionCredentials { pub authorization: Vec, } -/// Retrieves the session for the given chain id. -pub fn get(chain_id: FieldElement) -> anyhow::Result { +/// Retrieves the session for the given chain id of the currently authenticated user. +/// Returns `None` if no session can be found for the chain id. +/// +/// # Errors +/// +/// This function will return an error if there is no authenticated user. +/// +pub fn get(chain_id: FieldElement) -> anyhow::Result> { let credentials = Credentials::load()?; let username = credentials.account.expect("id must exist").id; - let contents = fs::read_to_string(get_file_path(&username, chain_id))?; - Ok(serde_json::from_str(&contents)?) + let path = get_file_path(&username, chain_id); + + if path.exists() { + let contents = fs::read_to_string(path)?; + Ok(Some(serde_json::from_str(&contents)?)) + } else { + Ok(None) + } } -/// Stores the session on-disk. -pub fn store(chain_id: FieldElement, session: &SessionDetails) -> anyhow::Result<()> { +/// Stores the session on-disk. Returns the path to the file where the `session` has been written to. +/// +/// # Errors +/// +/// This function will return an error if there is no authenticated user. +/// +pub fn store(chain_id: FieldElement, session: &SessionDetails) -> anyhow::Result { // TODO: maybe can store the authenticated user in a global variable so that // we don't have to call load again if we already did it before. let credentials = Credentials::load()?; @@ -59,18 +76,23 @@ pub fn store(chain_id: FieldElement, session: &SessionDetails) -> anyhow::Result // Create the parent directories if they don't yet exist. if let Some(parent) = path.parent() { if !parent.exists() { - trace!(path = %parent.display(), "Creating parent directories."); fs::create_dir_all(&path)?; } } let contents = serde_json::to_string_pretty(session)?; fs::write(&path, contents)?; - trace!(path = %path.display(), "Session token stored successfully."); - Ok(()) + Ok(path) } +/// Creates a new session token. This will open a browser to the Cartridge Controller keychain page +/// to prompt user to create a new session for the given policies and network. +/// +/// # Errors +/// +/// This function will return an error if there is no authenticated user. +/// #[tracing::instrument(level = "trace", skip(rpc_url), fields(policies = policies.len()))] pub async fn create(rpc_url: U, policies: &[Policy]) -> anyhow::Result where