sa_token_core/context/mod.rs
1// Author: 金书记
2//
3//! 上下文模块 - 用于在请求处理过程中传递 token 信息
4//!
5//! 注意:在实际应用中,建议通过框架的请求扩展(如 Axum 的 Extension)
6//! 来传递上下文,而不是使用 thread_local。这里提供的是一个简单的实现。
7
8use std::sync::Arc;
9use std::cell::RefCell;
10use crate::token::{TokenInfo, TokenValue};
11
12thread_local! {
13 static CONTEXT: RefCell<Option<SaTokenContext>> = RefCell::new(None);
14}
15
16/// sa-token 上下文 | sa-token Context
17///
18/// 用于在请求处理过程中传递 Token 相关信息
19/// Used to pass token-related information during request processing
20///
21/// # 字段说明 | Field Description
22/// - `token`: 当前请求的 token | Current request's token
23/// - `token_info`: Token 详细信息 | Token detailed information
24/// - `login_id`: 登录用户 ID | Logged-in user ID
25#[derive(Debug, Clone)]
26pub struct SaTokenContext {
27 /// 当前请求的 token | Current request's token
28 pub token: Option<TokenValue>,
29
30 /// 当前请求的 token 信息 | Current request's token info
31 pub token_info: Option<Arc<TokenInfo>>,
32
33 /// 登录 ID | Login ID
34 pub login_id: Option<String>,
35}
36
37impl SaTokenContext {
38 pub fn new() -> Self {
39 Self {
40 token: None,
41 token_info: None,
42 login_id: None,
43 }
44 }
45
46 /// 设置当前上下文 | Set Current Context
47 ///
48 /// # 参数 | Parameters
49 /// - `ctx`: 要设置的上下文 | Context to set
50 pub fn set_current(ctx: SaTokenContext) {
51 CONTEXT.with(|c| {
52 *c.borrow_mut() = Some(ctx);
53 });
54 }
55
56 /// 获取当前上下文 | Get Current Context
57 ///
58 /// # 返回 | Returns
59 /// 当前线程的上下文,如果不存在则返回 None
60 /// Current thread's context, or None if not exists
61 pub fn get_current() -> Option<SaTokenContext> {
62 CONTEXT.with(|c| {
63 c.borrow().clone()
64 })
65 }
66
67 /// 清除当前上下文 | Clear Current Context
68 ///
69 /// 清除当前线程的上下文信息
70 /// Clear current thread's context information
71 pub fn clear() {
72 CONTEXT.with(|c| {
73 *c.borrow_mut() = None;
74 });
75 }
76}
77
78impl Default for SaTokenContext {
79 fn default() -> Self {
80 Self::new()
81 }
82}