1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
use keyring::Entry;

use crate::{here, Error, ErrorLocation, Location};

/// Access the Keyring of the platform
#[must_use]
pub struct Keyring {
    entry: Entry,
}

impl Keyring {
    /// Create a Keyring
    pub fn new<T, E>(app_name: T, username: E) -> Self
    where
        T: AsRef<str>,
        E: AsRef<str>,
    {
        let service = format!("novel-{}", app_name.as_ref());
        let entry = Entry::new(&service, username.as_ref());

        Self { entry }
    }

    /// Get password
    pub fn get_password(&self) -> Result<String, Error> {
        Ok(self.entry.get_password()?)
    }

    /// Set password
    pub fn set_password<T>(&self, password: T) -> Result<(), Error>
    where
        T: AsRef<str>,
    {
        Ok(self
            .entry
            .set_password(password.as_ref())
            .location(here!())?)
    }

    /// Delete password
    pub fn delete_password(&self) -> Result<(), Error> {
        Ok(self.entry.delete_password()?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use pretty_assertions::assert_eq;

    #[test]
    #[cfg_attr(feature = "ci", ignore)]
    fn keyring() -> Result<(), Error> {
        let password = "test-username";
        let keyring = Keyring::new("test", password);

        keyring.set_password(password)?;
        assert_eq!(keyring.get_password()?, password);

        keyring.delete_password()?;

        Ok(())
    }
}