sa_token_plugin_rocket/
lib.rs

1// Author: 金书记
2//
3//! # sa-token-plugin-rocket
4//! 
5//! Rocket框架集成插件
6
7pub mod middleware;
8pub mod extractor;
9pub mod adapter;
10
11pub use middleware::SaTokenFairing;
12pub use extractor::{SaTokenGuard, OptionalSaTokenGuard, LoginIdGuard};
13pub use adapter::{RocketRequestAdapter, RocketResponseAdapter};
14
15use std::sync::Arc;
16use sa_token_core::SaTokenManager;
17use sa_token_adapter::storage::SaStorage;
18
19/// Rocket 应用状态
20#[derive(Clone)]
21pub struct SaTokenState {
22    pub manager: Arc<SaTokenManager>,
23}
24
25impl SaTokenState {
26    /// 创建状态构建器
27    pub fn builder() -> SaTokenStateBuilder {
28        SaTokenStateBuilder::new()
29    }
30}
31
32/// 状态构建器
33#[derive(Default)]
34pub struct SaTokenStateBuilder {
35    config_builder: sa_token_core::config::SaTokenConfigBuilder,
36}
37
38impl SaTokenStateBuilder {
39    pub fn new() -> Self {
40        Self::default()
41    }
42    
43    pub fn storage(mut self, storage: Arc<dyn SaStorage>) -> Self {
44        self.config_builder = self.config_builder.storage(storage);
45        self
46    }
47    
48    pub fn token_name(mut self, name: impl Into<String>) -> Self {
49        self.config_builder = self.config_builder.token_name(name);
50        self
51    }
52    
53    pub fn timeout(mut self, timeout: i64) -> Self {
54        self.config_builder = self.config_builder.timeout(timeout);
55        self
56    }
57    
58    pub fn active_timeout(mut self, timeout: i64) -> Self {
59        self.config_builder = self.config_builder.active_timeout(timeout);
60        self
61    }
62    
63    /// 设置是否开启自动续签
64    pub fn auto_renew(mut self, enabled: bool) -> Self {
65        self.config_builder = self.config_builder.auto_renew(enabled);
66        self
67    }
68    
69    pub fn is_concurrent(mut self, concurrent: bool) -> Self {
70        self.config_builder = self.config_builder.is_concurrent(concurrent);
71        self
72    }
73    
74    pub fn is_share(mut self, share: bool) -> Self {
75        self.config_builder = self.config_builder.is_share(share);
76        self
77    }
78    
79    /// 设置 Token 风格
80    pub fn token_style(mut self, style: sa_token_core::config::TokenStyle) -> Self {
81        self.config_builder = self.config_builder.token_style(style);
82        self
83    }
84    
85    pub fn token_prefix(mut self, prefix: impl Into<String>) -> Self {
86        self.config_builder = self.config_builder.token_prefix(prefix);
87        self
88    }
89    
90    pub fn jwt_secret_key(mut self, key: impl Into<String>) -> Self {
91        self.config_builder = self.config_builder.jwt_secret_key(key);
92        self
93    }
94    
95    pub fn build(self) -> SaTokenState {
96        let manager = self.config_builder.build();
97        
98        // 自动初始化全局 StpUtil
99        sa_token_core::StpUtil::init_manager(manager.clone());
100        
101        SaTokenState {
102            manager: Arc::new(manager),
103        }
104    }
105}