Skip to main content

rust_ucenter/
lib.rs

1// use deadpool_redis::{Config, Pool, Runtime}; 
2use redis::{Commands, Client, Connection};
3use serde::de::DeserializeOwned;
4use serde::{Deserialize, Serialize};
5use thiserror::Error;
6
7// 定义用户信息结构体
8#[derive(Serialize, Deserialize, PartialEq, Clone, Debug)]
9pub struct TokenUserInfo {
10    pub created: u64,
11    pub devId: String,
12    pub distId: i32,
13    pub distributorType: i32,
14    pub email: String,
15    pub frozenAll: i32,
16    pub frozenAsset: i32,
17    pub frozenCfd: i32,
18    pub frozenOtc: i32,
19    pub frozenSpot: i32,
20    pub invite: String,
21    pub ip: u64,
22    pub isMarketMaker: Option<i32>,
23    pub mobile: String,
24    pub parentId: i64,
25    pub parentInvite: String,
26    pub partnerId: i64,
27    pub salesId: i32,
28    pub status: i32,
29    pub userId: i64,
30    pub username: Option<String>,
31    pub lastIp: Option<String>,
32}
33
34#[derive(Debug, Clone)]
35pub struct AuthConfig {
36    pub redis_url: String,
37    pub header_key: String,
38}
39
40impl Default for AuthConfig {
41    fn default() -> Self {
42        Self {
43            redis_url: "redis://127.0.0.1/".into(),
44            header_key: "X-Authorization".into(),
45        }
46    }
47}
48
49#[derive(Debug, Error)]
50pub enum AuthError {
51    #[error("Missing auth header")]
52    MissingHeader,
53    #[error("Redis connection error: {0}")]
54    ConnectionError(String),
55    #[error("Redis command error: {0}")]
56    CommandError(String),
57    #[error("Deserialization error: {0}")]
58    DeserializationError(String),
59}
60
61#[derive(Clone)]
62pub struct AuthClient {
63    // pub pool: Pool,
64    pub client: Client,
65    pub config: AuthConfig,
66}
67
68impl AuthClient {
69    pub fn new(config: AuthConfig) -> Result<Self, AuthError> {
70        let client = Client::open(config.redis_url.clone())
71            .map_err(|e| AuthError::ConnectionError(e.to_string()))?;
72        Ok(Self { client, config })
73    }
74
75    fn get_conn(&self) -> Result<Connection, AuthError> {
76        self.client.get_connection()
77            .map_err(|e| AuthError::ConnectionError(e.to_string()))
78    }
79
80    pub fn get_user_data<T: DeserializeOwned>(
81        &self,
82        token: &str,
83    ) -> Result<T, AuthError> {
84        let mut conn = self.get_conn()?;
85
86        // 第一层查询:根据token获取user_id
87        let redis_key1 = format!("kubiex:session:id:{}", token);
88        let user_id: Option<String> = conn.get(&redis_key1)
89            .map_err(|e| AuthError::CommandError(e.to_string()))?;
90
91        let data = if let Some(user_id) = user_id {
92            // 第二层查询:根据user_id获取用户信息
93            let redis_key2 = format!("kubiex:session:user_id:{}", user_id);
94            conn.get(&redis_key2)
95                .map_err(|e| AuthError::CommandError(e.to_string()))?
96        } else {
97            // 如果找不到user_id返回空字符串(保持原逻辑)
98            String::new()
99        };
100
101        serde_json::from_str(&data)
102            .map_err(|e| AuthError::DeserializationError(e.to_string()))
103    }
104    // pub async fn new(config: AuthConfig) -> Result<Self, AuthError> {
105    //     let cfg = Config::from_url(config.redis_url.clone());
106    //     let pool = cfg.create_pool(Some(Runtime::Tokio1))
107    //         .map_err(|e| AuthError::ConnectionError(e.to_string()))?;
108        
109    //     Ok(Self { pool, config })
110    // }
111
112    // pub async fn get_user_data<T: DeserializeOwned + Send + Sync>(
113    //     &self,
114    //     token: &str,
115    // ) -> Result<T, AuthError> {
116
117    //     let mut data = String::new();
118
119    //     let mut redis_key= format!("kubiex:session:id:{}", token);
120
121    //     let mut conn = self.pool.get().await
122    //         .map_err(|e| AuthError::ConnectionError(e.to_string()))?;
123
124    //     let user_id_data: Option<String> = conn.get(redis_key).await
125    //         .map_err(|e| AuthError::CommandError(e.to_string()))?;
126        
127
128    //     if let Some(user_id) = user_id_data {
129    //         // 只处理 Some 的情况
130    //         println!("-------Received user_id: {}", user_id);
131
132    //         redis_key=format!("kubiex:session:user_id:{}", user_id);
133    //         let user_info_option: Option<String> = conn.get(redis_key).await
134    //             .map_err(|e| AuthError::CommandError(e.to_string()))?;
135    //         println!("Authorization redis_key 2 result: {:?}", user_info_option);
136    //         if let Some(user_info) = user_info_option {
137    //             data = user_info;
138    //             println!("Authorization redis_key 2 result: {:?}", &data);
139    //         };
140    //     } 
141    //     serde_json::from_str(&data)
142    //         .map_err(|e| AuthError::DeserializationError(e.to_string()))
143    // }
144
145
146
147
148}
149
150
151
152
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157    
158
159    #[tokio::test]
160    async fn test_full_flow() {
161        let config = AuthConfig {
162            redis_url: "redis://locklevel-redis-dev1-india.8wuaih.ng.0001.apse1.cache.amazonaws.com:6379/0".into(),
163            header_key: "X-Authorization".into(),
164        };
165
166        let client =  AuthClient::new(config).unwrap();
167        let result: Result<TokenUserInfo, _> = client.get_user_data("f4a7afb9e538aa9e7f61646864e20466d5671680266603db6b70141821cf9067");
168        if let Ok(user_info) = result {
169            println!("Got user info: {:?}", user_info);
170        }
171        // let client = AuthClient::new(config).await.unwrap();
172
173        // 测试获取数据
174        // let result: TokenUserInfo = client.get_user_data("f4a7afb9e538aa9e7f61646864e20466d5671680266603db6b70141821cf9067").await.unwrap();
175        
176    }
177}