[fractal/fractal-next] Unlock Secret Service collection, create if absent



commit 067931b7c707980f4332dce3d3b12091a4a3f9a4
Author: Enterprisey <59171-enterprisey users noreply gitlab gnome org>
Date:   Fri Jul 30 19:55:42 2021 -0700

    Unlock Secret Service collection, create if absent

 src/secret.rs | 30 ++++++++++++++++++++++++++----
 1 file changed, 26 insertions(+), 4 deletions(-)
---
diff --git a/src/secret.rs b/src/secret.rs
index 5e64b24a..68d08214 100644
--- a/src/secret.rs
+++ b/src/secret.rs
@@ -1,4 +1,5 @@
 use matrix_sdk::ruma::identifiers::{DeviceIdBox, UserId};
+use once_cell::sync::Lazy;
 use secret_service::EncryptionType;
 use secret_service::SecretService;
 use std::collections::HashMap;
@@ -15,10 +16,12 @@ pub struct StoredSession {
     pub device_id: DeviceIdBox,
 }
 
+static SECRET_SERVICE: Lazy<Result<SecretService<'static>, secret_service::Error>> =
+    Lazy::new(|| SecretService::new(EncryptionType::Dh));
+
 /// Retrieves all sessions stored to the `SecretService`
 pub fn restore_sessions() -> Result<Vec<StoredSession>, secret_service::Error> {
-    let ss = SecretService::new(EncryptionType::Dh)?;
-    let collection = ss.get_default_collection()?;
+    let collection = get_default_collection_unlocked()?;
 
     // Sessions that contain or produce errors are ignored.
     // TODO: Return error for corrupt sessions
@@ -78,8 +81,7 @@ pub fn restore_sessions() -> Result<Vec<StoredSession>, secret_service::Error> {
 /// Writes a session to the `SecretService`, overwriting any previously stored session with the
 /// same `homeserver`, `username` and `device-id`.
 pub fn store_session(session: StoredSession) -> Result<(), secret_service::Error> {
-    let ss = SecretService::new(EncryptionType::Dh)?;
-    let collection = ss.get_default_collection()?;
+    let collection = get_default_collection_unlocked()?;
 
     // Store the information for the login
     let attributes: HashMap<&str, &str> = [
@@ -120,3 +122,23 @@ pub fn store_session(session: StoredSession) -> Result<(), secret_service::Error
 
     Ok(())
 }
+
+fn get_default_collection_unlocked<'a>(
+) -> Result<secret_service::Collection<'a>, secret_service::Error> {
+    if SECRET_SERVICE.is_ok() {
+        let ss = SECRET_SERVICE.as_ref().unwrap();
+        let collection = match ss.get_default_collection() {
+            Ok(col) => col,
+            Err(secret_service::Error::NoResult) => ss.create_collection("default", "default")?,
+            Err(x) => return Err(x),
+        };
+
+        collection.unlock()?;
+
+        Ok(collection)
+    } else {
+        Err(secret_service::Error::Crypto(
+            "Error encountered when initiating secret service connection.".to_string(),
+        ))
+    }
+}


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]