mal/auth/
cache.rs

1use super::OAuth;
2use crate::config::oauth_config::AuthConfig;
3use std::{
4    fs::OpenOptions,
5    io::{Read, Write},
6};
7
8pub fn cache_auth(auth: &OAuth) {
9    let auth_path = AuthConfig::get_paths().unwrap().auth_cache_path;
10
11    let mut auth_file = OpenOptions::new()
12        .write(true)
13        .create(true)
14        .truncate(false)
15        .open(auth_path)
16        .unwrap();
17
18    let cached_auth = serde_json::to_string(auth).unwrap();
19
20    write!(auth_file, "{}", cached_auth).unwrap();
21}
22
23pub fn load_cached_auth() -> Option<OAuth> {
24    let auth_path = AuthConfig::get_paths().unwrap().auth_cache_path;
25    let mut auth_file = OpenOptions::new()
26        .read(true)
27        .write(true)
28        .create(true)
29        .truncate(false)
30        .open(auth_path)
31        .unwrap();
32
33    let mut cached_string = String::new();
34
35    auth_file.read_to_string(&mut cached_string).unwrap();
36
37    let cached_auth: OAuth = match serde_json::from_str(&cached_string) {
38        Ok(s) => s,
39        Err(_) => return None,
40    };
41
42    Some(cached_auth)
43}
44
45pub fn delete_cached_auth() {
46    let auth_path = AuthConfig::get_paths().unwrap().config_file_path;
47    let _ = std::fs::remove_file(auth_path);
48}