sa_token_plugin_actix_web/
lib.rs

1// Author: 金书记
2//
3//! # sa-token-plugin-actix-web
4//! 
5//! Actix-web框架集成插件 - 一站式认证授权解决方案
6//! 
7//! ## 快速开始
8//! 
9//! 只需要导入这一个包,即可使用所有功能:
10//! 
11//! ```toml
12//! [dependencies]
13//! sa-token-plugin-actix-web = "0.1.3"  # 默认使用内存存储
14//! # 或者使用 Redis 存储
15//! sa-token-plugin-actix-web = { version = "0.1.3", features = ["redis"] }
16//! ```
17//! 
18//! ## 使用示例
19//! 
20//! ```rust,ignore
21//! use sa_token_plugin_actix_web::*;
22//! 
23//! // 1. 初始化(使用内存存储)
24//! let state = SaTokenState::builder()
25//!     .storage(Arc::new(MemoryStorage::new()))  // 已重新导出
26//!     .timeout(7200)
27//!     .build();
28//! 
29//! // 2. 登录
30//! let token = state.manager().login("user123").await?;
31//! 
32//! // 3. 使用宏检查权限
33//! #[sa_check_login]
34//! async fn user_info() -> impl Responder {
35//!     "User info"
36//! }
37//! 
38//! #[sa_check_permission("admin")]
39//! async fn admin_panel() -> impl Responder {
40//!     "Admin panel"
41//! }
42//! ```
43
44pub mod middleware;
45pub mod extractor;
46pub mod adapter;
47
48// ============================================================================
49// Actix-web 框架集成(本插件特有)
50// ============================================================================
51pub use middleware::{SaTokenMiddleware, SaCheckLoginMiddleware};
52pub use extractor::{SaTokenExtractor, OptionalSaTokenExtractor, LoginIdExtractor};
53pub use adapter::{ActixRequestAdapter, ActixResponseAdapter};
54
55// ============================================================================
56// 重新导出核心功能(sa-token-core)
57// ============================================================================
58pub use sa_token_core::{
59    // 核心管理器
60    SaTokenManager, StpUtil,
61    
62    // 配置
63    SaTokenConfig,
64    config::TokenStyle,
65    
66    // Token 相关
67    TokenValue, TokenInfo,
68    
69    // 会话管理
70    SaSession,
71    
72    // 权限
73    PermissionChecker,
74    
75    // 错误处理
76    SaTokenError,
77    
78    // 事件系统
79    SaTokenEvent, SaTokenListener, SaTokenEventBus, LoggingListener,
80    
81    // JWT 支持
82    JwtManager, JwtClaims, JwtAlgorithm,
83    
84    // OAuth2 支持
85    OAuth2Manager, OAuth2Client, AuthorizationCode, AccessToken, OAuth2TokenInfo,
86    
87    // 安全特性
88    NonceManager, RefreshTokenManager,
89    
90    // WebSocket 认证
91    WsAuthManager, WsAuthInfo, WsTokenExtractor, DefaultWsTokenExtractor,
92    
93    // 在线用户管理
94    OnlineManager, OnlineUser, PushMessage, MessageType, MessagePusher, InMemoryPusher,
95    
96    // 分布式会话
97    DistributedSessionManager, DistributedSession, DistributedSessionStorage, 
98    ServiceCredential, InMemoryDistributedStorage,
99};
100
101// ============================================================================
102// 重新导出适配器接口(sa-token-adapter)
103// ============================================================================
104pub use sa_token_adapter::{
105    storage::SaStorage,
106    framework::FrameworkAdapter,
107};
108
109// ============================================================================
110// 重新导出宏(sa-token-macro)
111// ============================================================================
112pub use sa_token_macro::{
113    sa_check_login,
114    sa_check_permission,
115    sa_check_role,
116    sa_check_permissions_and,
117    sa_check_permissions_or,
118    sa_check_roles_and,
119    sa_check_roles_or,
120    sa_ignore,
121};
122
123// ============================================================================
124// 重新导出存储实现(根据 feature 条件编译)
125// ============================================================================
126
127/// 内存存储(默认启用)
128#[cfg(feature = "memory")]
129pub use sa_token_storage_memory::MemoryStorage;
130
131/// Redis 存储
132#[cfg(feature = "redis")]
133pub use sa_token_storage_redis::RedisStorage;
134
135/// 数据库存储
136#[cfg(feature = "database")]
137pub use sa_token_storage_database::DatabaseStorage;
138
139use std::sync::Arc;
140use actix_web::web::Data;
141
142/// Actix-web应用数据
143pub type SaTokenData = Data<SaTokenState>;
144
145/// 应用状态
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) -> Data<SaTokenState> {
222        let manager = self.config_builder.build();
223        
224        // 自动初始化全局 StpUtil
225        sa_token_core::StpUtil::init_manager(manager.clone());
226        
227        Data::new(SaTokenState {
228            manager: Arc::new(manager),
229        })
230    }
231}
232