Skip to content

Commit

Permalink
add comment
Browse files Browse the repository at this point in the history
  • Loading branch information
kariy committed Jun 14, 2024
1 parent c3155ac commit 01fd545
Showing 1 changed file with 31 additions and 9 deletions.
40 changes: 31 additions & 9 deletions src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,33 @@ pub struct SessionCredentials {
pub authorization: Vec<FieldElement>,
}

/// Retrieves the session for the given chain id.
pub fn get(chain_id: FieldElement) -> anyhow::Result<SessionDetails> {
/// 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<Option<SessionDetails>> {
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<PathBuf> {
// 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()?;
Expand All @@ -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<U>(rpc_url: U, policies: &[Policy]) -> anyhow::Result<SessionDetails>
where
Expand Down

0 comments on commit 01fd545

Please sign in to comment.