sa_token_plugin_rocket/
lib.rs

1// Author: 金书记
2//
3//! # sa-token-plugin-rocket
4//! 
5//! Rocket框架集成插件 - 一站式认证授权解决方案
6//! 
7//! ## 快速开始
8//! 
9//! 只需要导入这一个包,即可使用所有功能:
10//! 
11//! ```toml
12//! [dependencies]
13//! sa-token-plugin-rocket = "0.1.3"  # 默认使用内存存储
14//! # 或者使用 Redis 存储
15//! sa-token-plugin-rocket = { version = "0.1.3", features = ["redis"] }
16//! ```
17//! 
18//! ## 使用示例
19//! 
20//! ```rust,ignore
21//! use rocket::{State, get};
22//! use sa_token_plugin_rocket::*;  // 一次性导入所有功能
23//! 
24//! #[get("/user/info")]
25//! async fn user_info(token: SaTokenGuard) -> String {
26//!     format!("User ID: {}", token.login_id())
27//! }
28//! 
29//! #[rocket::main]
30//! async fn main() {
31//!     // 1. 初始化(使用内存存储,已重新导出)
32//!     let state = SaTokenState::builder()
33//!         .storage(Arc::new(MemoryStorage::new()))
34//!         .timeout(7200)
35//!         .build();
36//!     
37//!     // 2. 创建 Rocket 实例
38//!     rocket::build()
39//!         .attach(SaTokenFairing::new(state.manager.clone()))
40//!         .manage(state)
41//!         .mount("/", routes![user_info])
42//!         .launch()
43//!         .await
44//!         .unwrap();
45//! }
46//! ```
47
48pub mod middleware;
49pub mod extractor;
50pub mod adapter;
51
52// ============================================================================
53// Rocket 框架集成(本插件特有)
54// ============================================================================
55pub use middleware::SaTokenFairing;
56pub use extractor::{SaTokenGuard, OptionalSaTokenGuard, LoginIdGuard};
57pub use adapter::{RocketRequestAdapter, RocketResponseAdapter};
58
59// ============================================================================
60// 重新导出核心功能(sa-token-core)
61// ============================================================================
62pub use sa_token_core::{
63    // 核心管理器
64    SaTokenManager, StpUtil,
65    
66    // 配置
67    SaTokenConfig,
68    config::TokenStyle,
69    
70    // Token 相关
71    TokenValue, TokenInfo,
72    
73    // 会话管理
74    SaSession,
75    
76    // 权限
77    PermissionChecker,
78    
79    // 错误处理
80    SaTokenError,
81    
82    // 事件系统
83    SaTokenEvent, SaTokenListener, SaTokenEventBus, LoggingListener,
84    
85    // JWT 支持
86    JwtManager, JwtClaims, JwtAlgorithm,
87    
88    // OAuth2 支持
89    OAuth2Manager, OAuth2Client, AuthorizationCode, AccessToken, OAuth2TokenInfo,
90    
91    // 安全特性
92    NonceManager, RefreshTokenManager,
93    
94    // WebSocket 认证
95    WsAuthManager, WsAuthInfo, WsTokenExtractor, DefaultWsTokenExtractor,
96    
97    // 在线用户管理
98    OnlineManager, OnlineUser, PushMessage, MessageType, MessagePusher, InMemoryPusher,
99    
100    // 分布式会话
101    DistributedSessionManager, DistributedSession, DistributedSessionStorage, 
102    ServiceCredential, InMemoryDistributedStorage,
103};
104
105// ============================================================================
106// 重新导出适配器接口(sa-token-adapter)
107// ============================================================================
108pub use sa_token_adapter::{
109    storage::SaStorage,
110    framework::FrameworkAdapter,
111};
112
113// ============================================================================
114// 重新导出宏(sa-token-macro)
115// ============================================================================
116pub use sa_token_macro::{
117    sa_check_login,
118    sa_check_permission,
119    sa_check_role,
120    sa_check_permissions_and,
121    sa_check_permissions_or,
122    sa_check_roles_and,
123    sa_check_roles_or,
124    sa_ignore,
125};
126
127// ============================================================================
128// 重新导出存储实现(根据 feature 条件编译)
129// ============================================================================
130
131/// 内存存储(默认启用)
132#[cfg(feature = "memory")]
133pub use sa_token_storage_memory::MemoryStorage;
134
135/// Redis 存储
136#[cfg(feature = "redis")]
137pub use sa_token_storage_redis::RedisStorage;
138
139/// 数据库存储
140#[cfg(feature = "database")]
141pub use sa_token_storage_database::DatabaseStorage;
142
143use std::sync::Arc;
144
145/// Rocket 应用状态
146#[derive(Clone)]
147pub struct SaTokenState {
148    pub manager: Arc<SaTokenManager>,
149}
150
151impl SaTokenState {
152    /// 创建状态构建器
153    pub fn builder() -> SaTokenStateBuilder {
154        SaTokenStateBuilder::new()
155    }
156}
157
158/// 状态构建器
159#[derive(Default)]
160pub struct SaTokenStateBuilder {
161    config_builder: sa_token_core::config::SaTokenConfigBuilder,
162}
163
164impl SaTokenStateBuilder {
165    pub fn new() -> Self {
166        Self::default()
167    }
168    
169    pub fn storage(mut self, storage: Arc<dyn SaStorage>) -> Self {
170        self.config_builder = self.config_builder.storage(storage);
171        self
172    }
173    
174    pub fn token_name(mut self, name: impl Into<String>) -> Self {
175        self.config_builder = self.config_builder.token_name(name);
176        self
177    }
178    
179    pub fn timeout(mut self, timeout: i64) -> Self {
180        self.config_builder = self.config_builder.timeout(timeout);
181        self
182    }
183    
184    pub fn active_timeout(mut self, timeout: i64) -> Self {
185        self.config_builder = self.config_builder.active_timeout(timeout);
186        self
187    }
188    
189    /// 设置是否开启自动续签
190    pub fn auto_renew(mut self, enabled: bool) -> Self {
191        self.config_builder = self.config_builder.auto_renew(enabled);
192        self
193    }
194    
195    pub fn is_concurrent(mut self, concurrent: bool) -> Self {
196        self.config_builder = self.config_builder.is_concurrent(concurrent);
197        self
198    }
199    
200    pub fn is_share(mut self, share: bool) -> Self {
201        self.config_builder = self.config_builder.is_share(share);
202        self
203    }
204    
205    /// 设置 Token 风格
206    pub fn token_style(mut self, style: sa_token_core::config::TokenStyle) -> Self {
207        self.config_builder = self.config_builder.token_style(style);
208        self
209    }
210    
211    pub fn token_prefix(mut self, prefix: impl Into<String>) -> Self {
212        self.config_builder = self.config_builder.token_prefix(prefix);
213        self
214    }
215    
216    pub fn jwt_secret_key(mut self, key: impl Into<String>) -> Self {
217        self.config_builder = self.config_builder.jwt_secret_key(key);
218        self
219    }
220    
221    pub fn build(self) -> SaTokenState {
222        let manager = self.config_builder.build();
223        
224        // 自动初始化全局 StpUtil
225        sa_token_core::StpUtil::init_manager(manager.clone());
226        
227        SaTokenState {
228            manager: Arc::new(manager),
229        }
230    }
231}