summaryrefslogtreecommitdiffstats
path: root/src/client/access_token.rs
diff options
context:
space:
mode:
authorsigoden <sigoden@gmail.com>2024-05-06 09:08:49 +0800
committerGitHub <noreply@github.com>2024-05-06 09:08:49 +0800
commit7c6f75a139128e77f6c0e16ee176192dfef75599 (patch)
tree4bddb77185d420eee329ebac3f5a3e34de5cf512 /src/client/access_token.rs
parent9b283024b47f57ad7bbf032fa015eab42f8162a9 (diff)
downloadaichat-7c6f75a139128e77f6c0e16ee176192dfef75599.tar.gz
refactor: unified access token management (#486)
Diffstat (limited to 'src/client/access_token.rs')
-rw-r--r--src/client/access_token.rs34
1 files changed, 34 insertions, 0 deletions
diff --git a/src/client/access_token.rs b/src/client/access_token.rs
new file mode 100644
index 0000000..07640d5
--- /dev/null
+++ b/src/client/access_token.rs
@@ -0,0 +1,34 @@
+use anyhow::{anyhow, Result};
+use chrono::Utc;
+use indexmap::IndexMap;
+use lazy_static::lazy_static;
+use parking_lot::RwLock;
+
+lazy_static! {
+ static ref ACCESS_TOKENS: RwLock<IndexMap<String, (String, i64)>> =
+ RwLock::new(IndexMap::new());
+}
+
+pub fn get_access_token(client_name: &str) -> Result<String> {
+ ACCESS_TOKENS
+ .read()
+ .get(client_name)
+ .map(|(token, _)| token.clone())
+ .ok_or_else(|| anyhow!("Invalid access token"))
+}
+
+pub fn is_valid_access_token(client_name: &str) -> bool {
+ let access_tokens = ACCESS_TOKENS.read();
+ let (token, expires_at) = match access_tokens.get(client_name) {
+ Some(v) => v,
+ None => return false,
+ };
+ !token.is_empty() && Utc::now().timestamp() < *expires_at
+}
+
+pub fn set_access_token(client_name: &str, token: String, expires_at: i64) {
+ let mut access_tokens = ACCESS_TOKENS.write();
+ let entry = access_tokens.entry(client_name.to_string()).or_default();
+ entry.0 = token;
+ entry.1 = expires_at;
+}