Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SDK] Functions for saving and loading Credentials to/from disk #84

Merged
merged 3 commits into from
Jul 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/sdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,5 @@ futures-channel = "0.3"
anymap = "0.12"
im = "15.1"
base64 = "0.21"
home = "0.5"
lazy_static = "1.4"
47 changes: 46 additions & 1 deletion crates/sdk/src/identity.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use crate::callbacks::CallbackId;
use crate::global_connection::with_credential_store;
use anyhow::{anyhow, Result};
use anyhow::{anyhow, Context, Result};
use spacetimedb_lib::de::Deserialize;
use spacetimedb_lib::ser::Serialize;
use spacetimedb_sats::bsatn;
// TODO: impl ser/de for `Identity`, `Token`, `Credentials` so that clients can stash them
// to disk and use them to re-connect.

Expand Down Expand Up @@ -162,3 +163,47 @@ pub fn token() -> Result<Token> {
pub fn credentials() -> Result<Credentials> {
with_credential_store(|cred_store| cred_store.credentials().ok_or(anyhow!("Credentials not yet received")))
}

const CREDS_FILE: &str = "credentials";

/// Load a saved `Credentials` from a file within `~/dirname`, if one exists.
///
/// `dirname` is treated as a directory in the user's home directory.
/// If it contains a file named `credentials`,
/// that file is treated as a BSATN-encoded `Credentials`, deserialized and returned.
///
/// Returns `Ok(None)` if the directory or the credentials file does not exist.
/// Returns `Err` when IO or deserialization fails.
pub fn load_credentials(dirname: &str) -> Result<Option<Credentials>> {
let mut path = home::home_dir().with_context(|| "Determining user home directory to compute credentials path")?;
path.push(dirname);
path.push(CREDS_FILE);

match std::fs::read(&path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e).with_context(|| "Reading BSATN-encoded credentials from file")?,
Ok(file_contents) => bsatn::from_slice::<Credentials>(&file_contents)
.with_context(|| "Deserializing credentials")
.map(Some),
}
}

/// Stores a `Credentials` to a file within `~/dirname`, to be later loaded with [`load_credentials`].
///
/// `dirname` is treated as a directory in the user's home directory.
/// The directory is created if it does not already exists.
/// A file within it named `credentials` is created or replaced,
/// containing `creds` encoded as BSATN.
///
/// Returns `Err` when IO or serialization fails.
pub fn save_credentials(dirname: &str, creds: &Credentials) -> Result<()> {
let creds_bytes = bsatn::to_vec(creds).with_context(|| "Serializing credentials")?;

let mut path = home::home_dir().with_context(|| "Determining user home directory to compute credentials path")?;
path.push(dirname);

std::fs::create_dir_all(&path).with_context(|| "Creating credentials directory")?;

path.push(CREDS_FILE);
std::fs::write(&path, creds_bytes).with_context(|| "Writing credentials to file")
}