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 上下文
17#[derive(Debug, Clone)]
18pub struct SaTokenContext {
19    /// 当前请求的 token
20    pub token: Option<TokenValue>,
21    
22    /// 当前请求的 token 信息
23    pub token_info: Option<Arc<TokenInfo>>,
24    
25    /// 登录 ID
26    pub login_id: Option<String>,
27}
28
29impl SaTokenContext {
30    pub fn new() -> Self {
31        Self {
32            token: None,
33            token_info: None,
34            login_id: None,
35        }
36    }
37    
38    /// 设置当前上下文
39    pub fn set_current(ctx: SaTokenContext) {
40        CONTEXT.with(|c| {
41            *c.borrow_mut() = Some(ctx);
42        });
43    }
44    
45    /// 获取当前上下文
46    pub fn get_current() -> Option<SaTokenContext> {
47        CONTEXT.with(|c| {
48            c.borrow().clone()
49        })
50    }
51    
52    /// 清除当前上下文
53    pub fn clear() {
54        CONTEXT.with(|c| {
55            *c.borrow_mut() = None;
56        });
57    }
58}
59
60impl Default for SaTokenContext {
61    fn default() -> Self {
62        Self::new()
63    }
64}