Skip to main content

trailcache_core/auth/
credentials.rs

1use anyhow::{Context, Result};
2use keyring::Entry;
3
4const SERVICE_NAME: &str = "trailcache";
5
6pub struct CredentialStore;
7
8impl CredentialStore {
9    /// Store username and password in the OS keychain
10    pub fn store(username: &str, password: &str) -> Result<()> {
11        let entry = Entry::new(SERVICE_NAME, username)
12            .context("Failed to create keyring entry")?;
13        entry
14            .set_password(password)
15            .context("Failed to store password in keychain")?;
16        Ok(())
17    }
18
19    /// Retrieve password for a username from the OS keychain
20    pub fn get_password(username: &str) -> Result<String> {
21        let entry = Entry::new(SERVICE_NAME, username)
22            .context("Failed to create keyring entry")?;
23        entry
24            .get_password()
25            .context("Failed to retrieve password from keychain")
26    }
27
28    /// Delete stored credentials for a username
29    #[allow(dead_code)]
30    pub fn delete(username: &str) -> Result<()> {
31        let entry = Entry::new(SERVICE_NAME, username)
32            .context("Failed to create keyring entry")?;
33        entry
34            .delete_credential()
35            .context("Failed to delete credential from keychain")?;
36        Ok(())
37    }
38
39    /// Check if credentials exist for a username
40    pub fn has_credentials(username: &str) -> bool {
41        if let Ok(entry) = Entry::new(SERVICE_NAME, username) {
42            entry.get_password().is_ok()
43        } else {
44            false
45        }
46    }
47}