feat: implemented access token restoring

This commit is contained in:
antifallobst 2023-09-23 12:31:09 +02:00
parent 5f70219eac
commit 70d39c35ab
Signed by: antifallobst
GPG Key ID: 2B4F402172791BAF
2 changed files with 42 additions and 9 deletions

View File

@ -1,4 +1,4 @@
use anyhow::{Error, Ok, Result};
use anyhow::{Error, Result};
use directories::ProjectDirs;
use reqwest::{Client, StatusCode};
use serde::{Deserialize, Serialize};
@ -136,9 +136,29 @@ impl Api {
}))
}
pub async fn from_file() -> Result<Option<Self>> {
let project_dirs = match ProjectDirs::from("net", "NerdCult", "ncadmin") {
Some(pd) => Ok(pd),
None => Err(Error::msg("Failed to get data dir")),
}?;
let path = project_dirs.data_dir().join("data.json");
if !path.exists() {
return Ok(None);
}
let s = std::fs::read_to_string(&path)?;
let deserialized: Self = serde_json::from_str(&s)?;
match Api::from_token(&deserialized.base_url, deserialized.token).await? {
Ok(a) => Ok(Some(a)),
Err(_) => Ok(None),
}
}
pub fn save(&self) -> Result<()> {
let serialized = serde_json::to_string(&self)?;
let project_dirs = match ProjectDirs::from("lol", "NerdCult", "ncadmin") {
let project_dirs = match ProjectDirs::from("net", "NerdCult", "ncadmin") {
Some(pd) => Ok(pd),
None => Err(Error::msg("Failed to get data dir")),
}?;

View File

@ -17,21 +17,34 @@ struct Args {
/// An access token for the API
#[arg(short, long)]
token: Option<String>,
/// Skips the check for saved API access data
#[arg(short, long)]
no_saved_access: bool,
}
#[tokio::main]
async fn main() -> Result<()> {
let args = Args::parse();
let stdout = ui::prepare()?;
let base_url = args.base_url.unwrap();
let api = if let Some(token) = args.token {
Api::from_token(&base_url, token).await??
let stdout = ui::prepare()?;
let api = match if let Some(token) = args.token {
match Api::from_token(&base_url, token).await? {
Ok(a) => Some(a),
Err(_) => None,
}
} else if !args.no_saved_access {
Api::from_file().await?
} else {
let mut login = ui::login::UI::new(stdout, base_url)?;
let api = login.run().await?;
api
None
} {
Some(a) => a,
None => {
let mut login = ui::login::UI::new(stdout, base_url)?;
login.run().await?
}
};
println!("{:#?}", api);