quick_flash/
credentials.rs

1use crate::utils;
2use anyhow::{self, Context};
3use chrono::Utc;
4use serde::{Deserialize, Serialize};
5use std::fs;
6use std::path::Path;
7
8#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Hash)]
9pub enum StorageType {
10    R2,
11}
12
13#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Hash)]
14pub struct Credentials {
15    pub user_storage_name: String,
16    pub storage_type: StorageType,
17    pub storage_name: String,
18    pub storage_account_id: String,
19    pub storage_access_key: String,
20    pub storage_secret_key: String,
21    pub timestamp: i64,
22}
23
24impl Credentials {
25    pub fn new_r2(
26        user_storage_name: String,
27        storage_name: String,
28        storage_account_id: String,
29        storage_access_key: String,
30        storage_secret_key: String,
31    ) -> Self {
32        Self {
33            user_storage_name,
34            storage_type: StorageType::R2,
35            storage_name,
36            storage_account_id,
37            storage_access_key,
38            storage_secret_key,
39            timestamp: Utc::now().timestamp(),
40        }
41    }
42
43    pub fn read_from_path(path: &Path) -> anyhow::Result<Self> {
44        let contents = fs::read_to_string(path).context(format!(
45            "Failed to read credentials file {}",
46            path.display()
47        ))?;
48        let credentials: Credentials = toml::from_str(&contents).context(format!(
49            "Failed to parse credentials file {}",
50            path.display()
51        ))?;
52        Ok(credentials)
53    }
54
55    pub fn write_to_path(&self, path: &Path) -> anyhow::Result<()> {
56        let contents = toml::to_string(self)?;
57        fs::write(path, contents)?;
58        Ok(())
59    }
60}
61
62pub fn get_credentials_from_command_line() -> anyhow::Result<Credentials> {
63    eprintln!("Input credentials for the R2 bucket below:");
64
65    eprint!("Bucket Name: ");
66    let storage_name = utils::read_line()?;
67    eprint!("Bucket Account ID: ");
68    let storage_account_id = utils::read_line()?;
69    eprint!("Bucket Access Key: ");
70    let storage_access_key = utils::read_line()?;
71    eprint!("Bucket Secret Key: ");
72    let storage_secret_key = utils::read_line()?;
73    eprint!(
74        "Optionally, name the storage for future reference [{}]: ",
75        &storage_name
76    );
77    let user_storage_name = utils::read_line().unwrap_or(storage_name.clone());
78
79    let creds = Credentials::new_r2(
80        user_storage_name,
81        storage_name,
82        storage_account_id,
83        storage_access_key,
84        storage_secret_key,
85    );
86    /* eprintln!("Saving credentials to {}...", path.display());
87    write_credentials(&path, &creds)?; */
88    Ok(creds)
89}