Newer
Older
/* Copyright 2021 Dominik George <dominik.george@teckids.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use lazy_static::lazy_static;
use std::convert::From;
use std::time::SystemTime;
use oauth2::basic::BasicTokenResponse;
const TOKEN_DEFAULT_EXPIRES: u64 = 24 * 60 * 60;
struct UserToken {
access_token: String,
expires_at: u64,
refresh_token: Option<String>,
}
impl UserToken {
fn is_expired(&self) -> bool {
match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(d) => d.as_secs() >= self.expires_at,
Err(_) => true
}
}
}
impl From<BasicTokenResponse> for UserToken {
fn from(response: BasicTokenResponse) -> Self {
UserToken {
access_token: response.access_token.secret().to_string(),
expires_at: match response.expires_in {
Some(duration) => duration,
None => TOKEN_DEFAULT_EXPIRES
} + SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).ok().unwrap().as_secs(),
refresh_token: match response.refresh_token {
Some(t) => Some(t.secret().to_string()),
None => None
}
}
}
struct Cache {
user_tokens: HashMap<String, UserToken>
}
impl Cache {
Cache {
user_tokens: HashMap::new()
}
}
pub fn load_user_token(&self, owner: String) -> Option<&UserToken> {
return self.user_tokens.get(&owner);
}
pub fn save_user_token(&self, owner: String, token: UserToken) {
self.user_tokens.insert(owner, token);
for (owner, token) in self.user_tokens {
if token.is_expired() {
self.user_tokens.remove(&owner);
}
}
}
}
lazy_static! {