Skip to content

Commit

Permalink
Format codebase
Browse files Browse the repository at this point in the history
Signed-off-by: David Graeff <davgraeff@gmail.com>
  • Loading branch information
davidgraeff committed Jan 22, 2024
1 parent ca0156f commit a6a1d63
Show file tree
Hide file tree
Showing 16 changed files with 161 additions and 186 deletions.
34 changes: 12 additions & 22 deletions examples/create_read_write_document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,7 @@ async fn write_document(session: &mut ServiceSession, doc_id: &str) -> errors::R
a_timestamp: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Nanos, true),
};

documents::write(
session,
"tests",
Some(doc_id),
&obj,
documents::WriteOptions::default()
).await
documents::write(session, "tests", Some(doc_id), &obj, documents::WriteOptions::default()).await
}

async fn write_partial_document(session: &mut ServiceSession, doc_id: &str) -> errors::Result<WriteResult> {
Expand All @@ -55,7 +49,8 @@ async fn write_partial_document(session: &mut ServiceSession, doc_id: &str) -> e
Some(doc_id),
&obj,
documents::WriteOptions { merge: true },
).await
)
.await
}

fn check_write(result: WriteResult, doc_id: &str) {
Expand Down Expand Up @@ -105,10 +100,8 @@ async fn user_account_session(cred: Credentials) -> errors::Result<()> {
assert_eq!(user_session.project_id(), cred.project_id);

println!("user::Session::by_access_token");
let user_session = sessions::user::Session::by_access_token(
&cred,
&user_session.access_token_unchecked().await
).await?;
let user_session =
sessions::user::Session::by_access_token(&cred, &user_session.access_token_unchecked().await).await?;

assert_eq!(user_session.user_id, utils::TEST_USER_ID);

Expand All @@ -128,7 +121,8 @@ async fn user_account_session(cred: Credentials) -> errors::Result<()> {
Some(doc_id),
&obj,
documents::WriteOptions::default(),
).await?,
)
.await?,
doc_id,
);

Expand All @@ -146,7 +140,8 @@ async fn user_account_session(cred: Credentials) -> errors::Result<()> {
"abc".into(),
dto::FieldOperator::EQUAL,
"a_string",
).await?
)
.await?
.collect();
assert_eq!(results.len(), 1);
let doc: DemoDTO = documents::read_by_name(&user_session, &results.get(0).unwrap().name).await?;
Expand Down Expand Up @@ -192,11 +187,9 @@ async fn user_account_session(cred: Credentials) -> errors::Result<()> {
println!("user::Session documents::query for f64");
let f: f64 = 13.37;

let count = documents::query(&user_session, "tests", f.into(), dto::FieldOperator::EQUAL, "a_float")
.await?;
let count = documents::query(&user_session, "tests", f.into(), dto::FieldOperator::EQUAL, "a_float").await?;

let count = count
.count();
let count = count.count();
assert_eq!(count, 0);

Ok(())
Expand All @@ -211,10 +204,7 @@ async fn main() -> errors::Result<()> {
let cred = Credentials::from_file(credential_file.to_str().unwrap()).await?;

// Only download the public keys once, and cache them.
let jwkset = utils::from_cache_file(
credential_file.with_file_name("cached_jwks.jwks").as_path(),
&cred
).await?;
let jwkset = utils::from_cache_file(credential_file.with_file_name("cached_jwks.jwks").as_path(), &cred).await?;
cred.add_jwks_public_keys(&jwkset).await;
cred.verify().await?;

Expand Down
10 changes: 4 additions & 6 deletions examples/firebase_user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,11 @@ const TEST_USER_ID: &str = include_str!("test_user_id.txt");

#[tokio::main]
async fn main() -> errors::Result<()> {
let cred = Credentials::from_file("firebase-service-account.json").await.expect("Read credentials file");
let cred = Credentials::from_file("firebase-service-account.json")
.await
.expect("Read credentials file");

let user_session = UserSession::by_user_id(
&cred,
TEST_USER_ID,
false
).await?;
let user_session = UserSession::by_user_id(&cred, TEST_USER_ID, false).await?;

println!("users::user_info");
let user_info_container = users::user_info(&user_session).await?;
Expand Down
5 changes: 3 additions & 2 deletions examples/own_auth.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use firestore_db_and_auth::{documents, errors, Credentials, FirebaseAuthBearer};
use firestore_db_and_auth::errors::FirebaseError::APIError;
use firestore_db_and_auth::{documents, errors, Credentials, FirebaseAuthBearer};

/// Define your own structure that will implement the FirebaseAuthBearer trait
struct MyOwnSession {
Expand Down Expand Up @@ -51,7 +51,8 @@ async fn run() -> errors::Result<()> {
Some("test_doc"),
&t,
documents::WriteOptions::default(),
).await?;
)
.await?;
Ok(())
}

Expand Down
10 changes: 2 additions & 8 deletions examples/session_cookie.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,13 @@ async fn main() -> Result<(), FirebaseError> {
let cred = Credentials::from_file(credential_file.to_str().unwrap()).await?;

// Only download the public keys once, and cache them.
let jwkset = utils::from_cache_file(
credential_file.with_file_name("cached_jwks.jwks").as_path(), &cred
).await?;
let jwkset = utils::from_cache_file(credential_file.with_file_name("cached_jwks.jwks").as_path(), &cred).await?;
cred.add_jwks_public_keys(&jwkset).await;
cred.verify().await?;

let user_session = utils::user_session_with_cached_refresh_token(&cred).await?;

let cookie = session_cookie::create(
&cred,
user_session.access_token().await,
Duration::seconds(3600)
).await?;
let cookie = session_cookie::create(&cred, user_session.access_token().await, Duration::seconds(3600)).await?;
println!("Created session cookie: {}", cookie);

Ok(())
Expand Down
6 changes: 1 addition & 5 deletions examples/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,7 @@ pub async fn user_session_with_cached_refresh_token(cred: &Credentials) -> error
// Generate a new refresh token if necessary
println!("Generate new user auth token");
let user_session: sessions::user::Session = if refresh_token.is_empty() {
let session = sessions::user::Session::by_user_id(
&cred,
TEST_USER_ID,
true
).await?;
let session = sessions::user::Session::by_user_id(&cred, TEST_USER_ID, true).await?;
std::fs::write("refresh-token-for-tests.txt", &session.refresh_token.as_ref().unwrap())?;
session
} else {
Expand Down
31 changes: 16 additions & 15 deletions src/credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@
//! This module contains the [`crate::credentials::Credentials`] type, used by [`crate::sessions`] to create and maintain
//! authentication tokens for accessing the Firebase REST API.
use chrono::{Duration, DateTime, offset};
use chrono::{offset, DateTime, Duration};
use serde::{Deserialize, Serialize};
use serde_json;
use std::collections::BTreeMap;
use std::fs::File;
use std::sync::{Arc};
use std::fmt;
use std::fs::File;
use std::sync::Arc;

use super::jwt::{create_jwt_encoded, download_google_jwks, verify_access_token, JWKSet, JWT_AUDIENCE_IDENTITY};
use crate::{errors::FirebaseError, jwt::TokenValidationResult};
use std::io::BufReader;
use base64::Engine;
use base64::prelude::BASE64_STANDARD;
use base64::Engine;
use std::io::BufReader;
use tokio::sync::RwLock;

type Error = super::errors::FirebaseError;
Expand All @@ -30,10 +30,10 @@ pub(crate) struct Keys {
impl fmt::Debug for Keys {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Keys")
.field("pub_key_expires_at", &self.pub_key_expires_at)
.field("pub_key", &self.pub_key.keys().collect::<Vec<&String>>())
.field("secret", &self.secret.is_some())
.finish()
.field("pub_key_expires_at", &self.pub_key_expires_at)
.field("pub_key", &self.pub_key.keys().collect::<Vec<&String>>())
.field("secret", &self.secret.is_some())
.finish()
}
}

Expand Down Expand Up @@ -80,7 +80,8 @@ pub fn pem_to_der(pem_file_contents: &str) -> Result<Vec<u8>, Error> {
}

let base64_body = pem_file_contents.unwrap().replace("\n", "");
Ok(BASE64_STANDARD.decode(&base64_body)
Ok(BASE64_STANDARD
.decode(&base64_body)
.map_err(|_| FirebaseError::Generic("Invalid private key in credentials file. Expected Base64 data."))?)
}

Expand Down Expand Up @@ -177,7 +178,6 @@ impl Credentials {
Ok(self)
}


/// Verifies that creating access tokens is possible with the given credentials and public keys.
/// Returns an empty result type on success.
pub async fn verify(&self) -> Result<(), Error> {
Expand All @@ -188,7 +188,8 @@ impl Credentials {
Some(self.client_id.clone()),
None,
JWT_AUDIENCE_IDENTITY,
).await?;
)
.await?;
verify_access_token(&self, &access_token).await?;
Ok(())
}
Expand All @@ -202,9 +203,9 @@ impl Credentials {
pub async fn decode_secret(&self, kid: &str) -> Result<Option<Arc<biscuit::jws::Secret>>, Error> {
let should_refresh = {
let keys = self.keys.read().await;
keys.pub_key_expires_at.map(|expires_at| {
expires_at - offset::Utc::now() < Duration::minutes(10)
}).unwrap_or(false)
keys.pub_key_expires_at
.map(|expires_at| expires_at - offset::Utc::now() < Duration::minutes(10))
.unwrap_or(false)
};

if should_refresh {
Expand Down
Loading

0 comments on commit a6a1d63

Please sign in to comment.