sa_token_plugin_tide/
extractor.rs

1use tide::{Request, Response, StatusCode};
2use sa_token_core::{token::TokenValue, error::messages};
3use serde_json::json;
4
5/// 中文: 认证错误 | English: Authentication error
6#[derive(Debug)]
7pub struct AuthError;
8
9impl AuthError {
10    /// 中文: 创建新的认证错误 | English: Create new authentication error
11    pub fn new() -> Self {
12        Self
13    }
14    
15    /// 中文: 获取错误消息 | English: Get error message
16    pub fn message(&self) -> &'static str {
17        messages::AUTH_ERROR
18    }
19    
20    /// 中文: 转换为 JSON 字符串 | English: Convert to JSON string
21    pub fn to_json(&self) -> String {
22        json!({
23            "code": 401,
24            "message": self.message()
25        }).to_string()
26    }
27    
28    /// 中文: 转换为 Response | English: Convert to Response
29    pub fn to_response(&self) -> Response {
30        let mut res = Response::new(StatusCode::Unauthorized);
31        res.set_body(self.to_json());
32        res.set_content_type("application/json");
33        res
34    }
35}
36
37/// 中文: 必填 Token 提取器,读取扩展中的 TokenValue
38/// English: Required token extractor reading TokenValue from request extensions
39pub struct SaTokenExtractor(pub TokenValue);
40
41impl SaTokenExtractor {
42    /// 中文: 获取 Token 值 | English: Get token value
43    pub fn token(&self) -> &TokenValue {
44        &self.0
45    }
46    
47    /// 中文: 中间件将 Token 写入扩展,这里提取 | English: Middleware writes TokenValue into extensions
48    pub fn from_request<State: Clone + Send + Sync + 'static>(req: &Request<State>) -> Result<Self, AuthError> {
49        req.ext::<TokenValue>()
50            .cloned()
51            .map(SaTokenExtractor)
52            .ok_or_else(AuthError::new)
53    }
54}
55
56/// 中文: 可选 Token 提取器,用于无需强制鉴权的接口
57/// English: Optional token extractor for routes without mandatory auth
58pub struct OptionalSaTokenExtractor(pub Option<TokenValue>);
59
60impl OptionalSaTokenExtractor {
61    /// 中文: 获取 Option<TokenValue> | English: Get Option<TokenValue>
62    pub fn token(&self) -> Option<&TokenValue> {
63        self.0.as_ref()
64    }
65    
66    /// 中文: 直接返回 Option<TokenValue> | English: Returns Option<TokenValue> directly
67    pub fn from_request<State: Clone + Send + Sync + 'static>(req: &Request<State>) -> Self {
68        let token = req.ext::<TokenValue>().cloned();
69        OptionalSaTokenExtractor(token)
70    }
71}
72
73/// 中文: 登录 ID 提取器,从扩展中获取 login_id
74/// English: Login ID extractor retrieving login_id from extensions
75pub struct LoginIdExtractor(pub String);
76
77impl LoginIdExtractor {
78    /// 中文: 获取登录 ID | English: Get login ID
79    pub fn login_id(&self) -> &str {
80        &self.0
81    }
82    
83    /// 中文: 若登录成功,中间件会注入 login_id | English: Middleware injects login_id when user authenticated
84    pub fn from_request<State: Clone + Send + Sync + 'static>(req: &Request<State>) -> Result<Self, AuthError> {
85        req.ext::<String>()
86            .cloned()
87            .map(LoginIdExtractor)
88            .ok_or_else(AuthError::new)
89    }
90}