r_token/memory.rs
1use crate::RTokenError;
2use crate::models::RTokenInfo;
3use chrono::Utc;
4use std::{
5 collections::HashMap,
6 sync::{Arc, Mutex},
7};
8
9/// Issues, stores, and revokes authentication tokens.
10///
11/// This type is designed to be stored in actix-web application state
12/// (e.g. `web::Data<RTokenManager>`). Internally it uses an `Arc<Mutex<...>>`,
13/// so `Clone` creates another handle to the same shared store.
14///
15/// Tokens are generated as UUID v4 strings. Each token is associated with:
16/// - a user id (`String`)
17/// - an expiration timestamp (Unix epoch milliseconds)
18///
19/// ## 繁體中文
20///
21/// 負責簽發、儲存與註銷 token 的管理器。
22///
23/// 一般會放在 actix-web 的 application state 中(例如 `web::Data<RTokenManager>`)。
24/// 內部以 `Arc<Mutex<...>>` 共享狀態,因此 `Clone` 只是在同一份映射表上增加一個引用。
25///
26/// token 以 UUID v4 字串產生,並會綁定:
27/// - 使用者 id(`String`)
28/// - 到期時間(Unix epoch 毫秒)
29#[derive(Clone, Default)]
30pub struct RTokenManager {
31 /// In-memory token store.
32 ///
33 /// ## 繁體中文
34 ///
35 /// 記憶體中的 token 儲存表。
36 // store: Arc<Mutex<HashMap<String, String>>>,
37 store: Arc<Mutex<HashMap<String, RTokenInfo>>>,
38}
39
40impl RTokenManager {
41 /// Creates an empty manager.
42 ///
43 /// ## 繁體中文
44 ///
45 /// 建立一個空的管理器。
46 pub fn new() -> Self {
47 Self {
48 store: Arc::new(Mutex::new(HashMap::new())),
49 }
50 }
51
52 /// Issues a new token for the given user id.
53 ///
54 /// `expire_time` is treated as TTL in seconds. The token will be considered invalid
55 /// once the stored expiration timestamp is earlier than the current time.
56 ///
57 /// Returns [`RTokenError::MutexPoisoned`] if the internal mutex is poisoned.
58 ///
59 /// ## 繁體中文
60 ///
61 /// 為指定使用者 id 簽發新 token。
62 ///
63 /// `expire_time` 會被視為 TTL(秒)。當儲存的到期時間早於目前時間時,token 會被視為無效。
64 ///
65 /// 若內部 mutex 發生 poisoned,會回傳 [`RTokenError::MutexPoisoned`]。
66 // pub fn login(&self, id: &str, expire_time: u64,role:impl Into<Vec<String>>) -> Result<String, RTokenError> {
67 pub fn login(&self, id: &str, expire_time: u64) -> Result<String, RTokenError> {
68 let token = uuid::Uuid::new_v4().to_string();
69 // Acquire the write lock and insert the token-user mapping into the store
70 // 获取写锁并将 Token-用户映射关系插入到存储中
71 // #[allow(clippy::unwrap_used)]
72 // self.store.lock().unwrap().insert(token.clone(), id.to_string());
73 let now = Utc::now();
74 let ttl = chrono::Duration::seconds(expire_time as i64);
75 let deadline = now + ttl;
76 let expire_time = deadline.timestamp_millis() as u64;
77 let info = RTokenInfo {
78 user_id: id.to_string(),
79 expire_at: expire_time,
80 roles: Vec::new(),
81 };
82 self.store
83 .lock()
84 .map_err(|_| RTokenError::MutexPoisoned)?
85 .insert(token.clone(), info);
86 Ok(token)
87 }
88
89 #[cfg(feature = "rbac")]
90 pub fn login_with_roles(
91 &self,
92 id: &str,
93 expire_time: u64,
94 role: impl Into<Vec<String>>,
95 ) -> Result<String, RTokenError> {
96 let token = uuid::Uuid::new_v4().to_string();
97 let now = Utc::now();
98 let ttl = chrono::Duration::seconds(expire_time as i64);
99 let deadline = now + ttl;
100 let expire_time = deadline.timestamp_millis() as u64;
101 let info = RTokenInfo {
102 user_id: id.to_string(),
103 expire_at: expire_time,
104 roles: role.into(),
105 };
106 self.store
107 .lock()
108 .map_err(|_| RTokenError::MutexPoisoned)?
109 .insert(token.clone(), info);
110 Ok(token)
111 }
112
113 // pub fn set_role(&self, token: &str, role: impl Into<Vec<String>>) -> Result<(), RTokenError> {
114 #[cfg(feature = "rbac")]
115 pub fn set_roles(&self, token: &str, roles: impl Into<Vec<String>>) -> Result<(), RTokenError> {
116 let mut store = self.store.lock().map_err(|_| RTokenError::MutexPoisoned)?;
117 if let Some(info) = store.get_mut(token) {
118 info.roles = roles.into();
119 }
120 Ok(())
121 }
122
123 #[cfg(feature = "rbac")]
124 pub fn get_roles(&self, token: &str) -> Result<Option<Vec<String>>, RTokenError> {
125 let store = self.store.lock().map_err(|_| RTokenError::MutexPoisoned)?;
126 Ok(store.get(token).map(|info| info.roles.clone()))
127 }
128
129 /// Revokes a token by removing it from the in-memory store.
130 ///
131 /// This operation is idempotent: removing a non-existing token is treated as success.
132 /// Returns [`RTokenError::MutexPoisoned`] if the internal mutex is poisoned.
133 ///
134 /// ## 繁體中文
135 ///
136 /// 從記憶體儲存表中移除 token,以達到註銷效果。
137 ///
138 /// 此操作具冪等性:移除不存在的 token 也視為成功。
139 /// 若內部 mutex 發生 poisoned,會回傳 [`RTokenError::MutexPoisoned`]。
140 pub fn logout(&self, token: &str) -> Result<(), RTokenError> {
141 // self.store.lock().unwrap().remove(token);
142 self.store
143 .lock()
144 .map_err(|_| RTokenError::MutexPoisoned)?
145 .remove(token);
146 Ok(())
147 }
148
149 /// Validates a token and returns the associated user id if present.
150 ///
151 /// Behavior:
152 /// - Returns `Ok(Some(user_id))` when the token exists and is not expired.
153 /// - Returns `Ok(None)` when the token does not exist or is expired.
154 /// - Expired tokens are removed from the in-memory store during validation.
155 ///
156 /// ## 繁體中文
157 ///
158 /// 驗證 token,若有效則回傳對應的使用者 id。
159 ///
160 /// 行為:
161 /// - token 存在且未過期:回傳 `Ok(Some(user_id))`
162 /// - token 不存在或已過期:回傳 `Ok(None)`
163 /// - 若 token 已過期,會在驗證時從記憶體儲存表中移除
164 pub fn validate(&self, token: &str) -> Result<Option<String>, RTokenError> {
165 #[cfg(feature = "rbac")]
166 {
167 Ok(self
168 .validate_with_roles(token)?
169 .map(|(user_id, _roles)| user_id))
170 }
171
172 #[cfg(not(feature = "rbac"))]
173 {
174 let mut store = self.store.lock().map_err(|_| RTokenError::MutexPoisoned)?;
175 let Some(info) = store.get(token) else {
176 return Ok(None);
177 };
178
179 if info.expire_at < Utc::now().timestamp_millis() as u64 {
180 store.remove(token);
181 return Ok(None);
182 }
183
184 Ok(Some(info.user_id.clone()))
185 }
186 }
187
188 #[cfg(feature = "rbac")]
189 /// Validates a token and returns both user id and roles (RBAC enabled).
190 ///
191 /// This has the same expiration behavior as [`RTokenManager::validate`].
192 ///
193 /// ## 繁體中文
194 ///
195 /// 驗證 token,並在 RBAC 啟用時同時回傳使用者 id 與角色列表。
196 ///
197 /// 到期行為與 [`RTokenManager::validate`] 相同。
198 pub fn validate_with_roles(
199 &self,
200 token: &str,
201 ) -> Result<Option<(String, Vec<String>)>, RTokenError> {
202 let mut store = self.store.lock().map_err(|_| RTokenError::MutexPoisoned)?;
203 let Some(info) = store.get(token) else {
204 return Ok(None);
205 };
206
207 if info.expire_at < Utc::now().timestamp_millis() as u64 {
208 store.remove(token);
209 return Ok(None);
210 }
211
212 Ok(Some((info.user_id.clone(), info.roles.clone())))
213 }
214}
215
216/// An authenticated request context extracted from actix-web.
217///
218/// If extraction succeeds, `id` is the user id previously passed to
219/// [`RTokenManager::login`], and `token` is the original token from the request.
220///
221/// The token is read from `Authorization` header. Both of the following formats
222/// are accepted:
223/// - `Authorization: <token>`
224/// - `Authorization: Bearer <token>`
225///
226/// ## 繁體中文
227///
228/// 由 actix-web 自動抽取的已驗證使用者上下文。
229///
230/// Extractor 成功時:
231/// - `id` 會是先前傳給 [`RTokenManager::login`] 的使用者 id
232/// - `token` 會是請求中帶來的 token 原文
233///
234/// token 會從 `Authorization` header 讀取,支援以下格式:
235/// - `Authorization: <token>`
236/// - `Authorization: Bearer <token>`
237#[cfg(feature = "actix")]
238#[derive(Debug)]
239pub struct RUser {
240 /// The user id associated with the token.
241 ///
242 /// ## 繁體中文
243 ///
244 /// 與 token 綁定的使用者 id。
245 pub id: String,
246
247 /// The raw token string from the request.
248 ///
249 /// ## 繁體中文
250 ///
251 /// 來自請求的 token 字串原文。
252 pub token: String,
253 #[cfg(feature = "rbac")]
254 pub roles: Vec<String>,
255}
256
257#[cfg(feature = "rbac")]
258impl RUser {
259 pub fn has_role(&self, role: &str) -> bool {
260 self.roles.iter().any(|r| r == role)
261 }
262}
263
264/// Extracts [`RUser`] from an actix-web request.
265///
266/// Failure modes:
267/// - 500: manager is missing from `app_data`, or mutex is poisoned
268/// - 401: token is missing, invalid, or expired
269///
270/// ## 繁體中文
271///
272/// 從 actix-web 請求中抽取 [`RUser`]。
273///
274/// 失敗情況:
275/// - 500:`app_data` 中找不到管理器,或 mutex poisoned
276/// - 401:token 缺失、無效、或已過期
277#[cfg(feature = "actix")]
278impl actix_web::FromRequest for RUser {
279 type Error = actix_web::Error;
280 type Future = std::future::Ready<Result<Self, Self::Error>>;
281
282 fn from_request(
283 req: &actix_web::HttpRequest,
284 _payload: &mut actix_web::dev::Payload,
285 ) -> Self::Future {
286 use actix_web::web;
287
288 // 獲取管理器
289 let manager = match req.app_data::<web::Data<RTokenManager>>() {
290 Some(m) => m,
291 None => {
292 return std::future::ready(Err(actix_web::error::ErrorInternalServerError(
293 "Token manager not found",
294 )));
295 }
296 };
297 let token = match crate::extract_token_from_request(req) {
298 Some(token) => token,
299 None => {
300 return std::future::ready(Err(actix_web::error::ErrorUnauthorized(
301 "Unauthorized",
302 )));
303 }
304 };
305
306 #[cfg(feature = "rbac")]
307 {
308 let user_info = match manager.validate_with_roles(&token) {
309 Ok(user_info) => user_info,
310 Err(_) => {
311 return std::future::ready(Err(actix_web::error::ErrorInternalServerError(
312 "Mutex poisoned",
313 )));
314 }
315 };
316
317 if let Some((user_id, roles)) = user_info {
318 return std::future::ready(Ok(RUser {
319 id: user_id,
320 token,
321 roles,
322 }));
323 }
324
325 std::future::ready(Err(actix_web::error::ErrorUnauthorized("Invalid token")))
326 }
327
328 #[cfg(not(feature = "rbac"))]
329 {
330 let user_id = match manager.validate(&token) {
331 Ok(user_id) => user_id,
332 Err(_) => {
333 return std::future::ready(Err(actix_web::error::ErrorInternalServerError(
334 "Mutex poisoned",
335 )));
336 }
337 };
338
339 if let Some(user_id) = user_id {
340 return std::future::ready(Ok(RUser { id: user_id, token }));
341 }
342
343 std::future::ready(Err(actix_web::error::ErrorUnauthorized("Invalid token")))
344 }
345 }
346}