quick_flash/
credentials_manager.rs

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
use crate::credentials::Credentials;
use anyhow::{self, Context};
use chrono::Utc;
use std::{
    hash::{DefaultHasher, Hash, Hasher},
    path::PathBuf,
};

pub struct CredentialsManager {
    base_path: PathBuf,
}

impl CredentialsManager {
    pub fn new(base_path: PathBuf) -> Self {
        CredentialsManager { base_path }
    }

    pub fn get_all(&self) -> anyhow::Result<Vec<Credentials>> {
        if !self.base_path.exists() {
            return Ok(vec![]);
        }

        self.base_path
            .read_dir()
            .context("Failed to read from credentials directory")?
            .map(|entry| {
                let path = entry?.path();
                Credentials::read_from_path(&path)
            })
            .collect()
    }

    pub fn remove(&self, user_storage_name: &str) -> anyhow::Result<()> {
        self.base_path
            .read_dir()
            .context("Failed to read from credentials directory")?
            .find(|entry| {
                let path = entry.as_ref().map_or_else(|_| PathBuf::new(), |e| e.path());
                Credentials::read_from_path(&path)
                    .ok()
                    .map_or(false, |c| c.user_storage_name == user_storage_name)
            })
            .context("Credentials not found")?
            .and_then(|path| std::fs::remove_file(path.path()))
            .context("Failed to remove credentials file")?;
        Ok(())
    }

    pub fn add(&self, creds: Credentials) -> anyhow::Result<()> {
        if !self.base_path.exists() {
            std::fs::create_dir_all(&self.base_path)
                .context("Failed to create credentials directory")?;
        }

        if creds.user_storage_name.is_empty() {
            anyhow::bail!("User storage name cannot be empty");
        }

        /* check if credentials with the same name do not exist already */
        self.get_all().and_then(|existing_creds| {
            if existing_creds
                .iter()
                .any(|c| c.user_storage_name == creds.user_storage_name)
            {
                anyhow::bail!("Credentials with the same name already exist");
            }

            let mut hasher = DefaultHasher::new();
            creds.hash(&mut hasher);

            let name = format!(
                "{}_{:0x}.toml",
                Utc::now().format("%Y-%m-%d_%H-%M-%S"),
                hasher.finish()
            );
            let path = self.base_path.join(name);
            creds.write_to_path(&path)
        })
    }
}

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

    #[test]
    fn test_credentials_manager() {
        let temp_dir = tempdir().unwrap();
        let creds_dir = temp_dir.path().join("creds");
        let creds_manager = CredentialsManager::new(creds_dir.clone());
        assert_eq!(creds_manager.get_all().unwrap().len(), 0);

        assert_eq!(
            creds_manager.remove("test").err().unwrap().to_string(),
            "Failed to read from credentials directory"
        );

        let creds = Credentials::new_r2(
            "test".to_string(),
            "storage_name".to_string(),
            "account_id".to_string(),
            "access_key".to_string(),
            "secret_key".to_string(),
        );

        creds_manager.add(creds.clone()).unwrap();
        let all_creds = creds_manager.get_all().unwrap();
        assert_eq!(all_creds.len(), 1);
        assert_eq!(all_creds[0], creds);

        let creds2 = Credentials::new_r2(
            "test2".to_string(),
            "storage_name".to_string(),
            "account_id".to_string(),
            "access_key".to_string(),
            "secret_key".to_string(),
        );

        creds_manager.add(creds2.clone()).unwrap();
        let all_creds = creds_manager.get_all().unwrap();
        assert_eq!(all_creds.len(), 2);
        assert!(all_creds.contains(&creds));
        assert!(all_creds.contains(&creds2));

        creds_manager.remove("test").unwrap();
        let all_creds = creds_manager.get_all().unwrap();
        assert_eq!(all_creds.len(), 1);
        assert_eq!(all_creds[0].user_storage_name, "test2");

        creds_manager.remove("test2").unwrap();
        let all_creds = creds_manager.get_all().unwrap();
        assert_eq!(all_creds.len(), 0);

        assert_eq!(
            creds_manager.remove("test").err().unwrap().to_string(),
            "Credentials not found"
        );
        assert_eq!(
            creds_manager.remove("test2").err().unwrap().to_string(),
            "Credentials not found"
        );
        assert_eq!(creds_manager.get_all().unwrap().len(), 0);
    }
}