aboutsummaryrefslogtreecommitdiff
path: root/azalea-auth/src/cache.rs
blob: 3ff9333054f1be5ee0c287c9df6ca02855c01912 (plain)
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
//! Cache auth information

use std::{
    fmt::Debug,
    io,
    path::Path,
    time::{SystemTime, UNIX_EPOCH},
};

use serde::{Deserialize, Serialize, de::DeserializeOwned};
use thiserror::Error;
use tokio::{
    fs::{self, File},
    io::{AsyncReadExt, AsyncWriteExt},
};
use tracing::{debug, trace};

#[derive(Debug, Error)]
pub enum CacheError {
    #[error("Failed to read cache file: {0}")]
    Read(io::Error),
    #[error("Failed to write cache file: {0}")]
    Write(io::Error),
    #[error("Failed to create cache file directory: {0}")]
    MkDir(io::Error),
    #[error("Failed to parse cache file: {0}")]
    Parse(serde_json::Error),
}

pub trait CacheEntry: Serialize + DeserializeOwned + Debug {
    type Key<'a>: for<'b> PartialEq<Self::Key<'b>>
    where
        Self: 'a;
    fn key<'a>(&'a self) -> Self::Key<'a>;
}

#[derive(Debug, Deserialize, Serialize)]
pub struct CachedAccount {
    #[serde(alias = "email")]
    pub cache_key: String,
    /// Microsoft auth
    pub msa: ExpiringValue<crate::auth::AccessTokenResponse>,
    /// Xbox Live auth
    pub xbl: ExpiringValue<crate::auth::XboxLiveAuth>,
    /// Minecraft auth
    pub mca: ExpiringValue<crate::auth::MinecraftAuthResponse>,
    /// The user's Minecraft profile (i.e. username, UUID, skin)
    pub profile: crate::auth::ProfileResponse,
}

impl CacheEntry for CachedAccount {
    type Key<'a> = &'a str;
    fn key<'a>(&'a self) -> Self::Key<'a> {
        &self.cache_key
    }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct ExpiringValue<T> {
    /// Seconds since the UNIX epoch
    pub expires_at: u64,
    pub data: T,
}

impl<T> ExpiringValue<T> {
    pub fn is_expired(&self) -> bool {
        self.expires_at
            < SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs()
    }

    /// Return the data if it's not expired, otherwise return `None`
    pub fn get(&self) -> Option<&T> {
        if self.is_expired() {
            None
        } else {
            Some(&self.data)
        }
    }
}

impl<T: Clone> Clone for ExpiringValue<T> {
    fn clone(&self) -> Self {
        Self {
            expires_at: self.expires_at,
            data: self.data.clone(),
        }
    }
}

async fn get_entire_cache<T: CacheEntry>(cache_file: &Path) -> Result<Vec<T>, CacheError> {
    let mut cache: Vec<T> = Vec::new();
    if cache_file.exists() {
        let mut cache_file = File::open(cache_file).await.map_err(CacheError::Read)?;
        // read the file into a string
        let mut contents = String::new();
        cache_file
            .read_to_string(&mut contents)
            .await
            .map_err(CacheError::Read)?;
        cache = serde_json::from_str(&contents).map_err(CacheError::Parse)?;
    }
    Ok(cache)
}
async fn set_entire_cache<T: CacheEntry>(
    cache_file: &Path,
    cache: Vec<T>,
) -> Result<(), CacheError> {
    trace!("saving cache: {:?}", cache);

    if !cache_file.exists() {
        let cache_file_parent = cache_file
            .parent()
            .expect("Cache file is root directory and also doesn't exist.");
        debug!(
            "Making cache file parent directory at {}",
            cache_file_parent.to_string_lossy()
        );
        fs::create_dir_all(cache_file_parent)
            .await
            .map_err(CacheError::MkDir)?;
    }
    let mut cache_file = File::create(cache_file).await.map_err(CacheError::Write)?;
    let cache = serde_json::to_string_pretty(&cache).map_err(CacheError::Parse)?;
    cache_file
        .write_all(cache.as_bytes())
        .await
        .map_err(CacheError::Write)?;

    Ok(())
}

/// Gets cached data for the given cache key.
///
/// As a convention, the cache key is usually the email of the account.
pub async fn get_account_in_cache(cache_file: &Path, cache_key: &str) -> Option<CachedAccount> {
    get_account_in_cache_g(cache_file, cache_key).await
}

pub async fn get_account_in_cache_g<T: CacheEntry>(
    cache_file: &Path,
    cache_key: T::Key<'_>,
) -> Option<T> {
    let cache = get_entire_cache::<T>(cache_file).await.unwrap_or_default();
    cache.into_iter().find(|account| account.key() == cache_key)
}

pub async fn set_account_in_cache(
    cache_file: &Path,
    cache_key: &str,
    account: CachedAccount,
) -> Result<(), CacheError> {
    set_account_in_cache_g(cache_file, cache_key, account).await
}

pub async fn set_account_in_cache_g<T: CacheEntry>(
    cache_file: &Path,
    cache_key: T::Key<'_>,
    account: T,
) -> Result<(), CacheError> {
    let mut cache = get_entire_cache::<T>(cache_file).await.unwrap_or_default();
    cache.retain(|account| account.key() != cache_key);
    cache.push(account);
    set_entire_cache(cache_file, cache).await
}