sa_token_plugin_tide/
extractor.rs1use tide::{Request, Response, StatusCode};
2use sa_token_core::{token::TokenValue, error::messages};
3use serde_json::json;
4
5#[derive(Debug)]
7pub struct AuthError;
8
9impl AuthError {
10 pub fn new() -> Self {
12 Self
13 }
14
15 pub fn message(&self) -> &'static str {
17 messages::AUTH_ERROR
18 }
19
20 pub fn to_json(&self) -> String {
22 json!({
23 "code": 401,
24 "message": self.message()
25 }).to_string()
26 }
27
28 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
37pub struct SaTokenExtractor(pub TokenValue);
40
41impl SaTokenExtractor {
42 pub fn token(&self) -> &TokenValue {
44 &self.0
45 }
46
47 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
56pub struct OptionalSaTokenExtractor(pub Option<TokenValue>);
59
60impl OptionalSaTokenExtractor {
61 pub fn token(&self) -> Option<&TokenValue> {
63 self.0.as_ref()
64 }
65
66 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
73pub struct LoginIdExtractor(pub String);
76
77impl LoginIdExtractor {
78 pub fn login_id(&self) -> &str {
80 &self.0
81 }
82
83 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}