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;
47pub mod layer;
48
49// ============================================================================
50// Actix-web 框架集成(本插件特有)
51// ============================================================================
52pub use middleware::SaCheckLoginMiddleware;
53pub use layer::SaTokenLayer;
54
55// 为保持向后兼容,SaTokenMiddleware 从 layer 模块重新导出
56pub use middleware::SaTokenMiddleware;
57pub use extractor::{SaTokenExtractor, OptionalSaTokenExtractor, LoginIdExtractor};
58pub use adapter::{ActixRequestAdapter, ActixResponseAdapter};
59
60// ============================================================================
61// 重新导出核心功能(sa-token-core)
62// ============================================================================
63pub use sa_token_core::{self, 
64    // 核心管理器
65    SaTokenManager, StpUtil,
66    
67    // 配置
68    SaTokenConfig,
69    config::TokenStyle,
70    
71    // Token 相关
72    TokenValue, TokenInfo,
73    
74    // 会话管理
75    SaSession,
76    
77    // 权限
78    PermissionChecker,
79    
80    // 错误处理
81    SaTokenError,
82    
83    // 事件系统
84    SaTokenEvent, SaTokenListener, SaTokenEventBus, LoggingListener,
85    
86    // JWT 支持
87    JwtManager, JwtClaims, JwtAlgorithm,
88    
89    // OAuth2 支持
90    OAuth2Manager, OAuth2Client, AuthorizationCode, AccessToken, OAuth2TokenInfo,
91    
92    // 安全特性
93    NonceManager, RefreshTokenManager,
94    
95    // WebSocket 认证
96    WsAuthManager, WsAuthInfo, WsTokenExtractor, DefaultWsTokenExtractor,
97    
98    // 在线用户管理
99    OnlineManager, OnlineUser, PushMessage, MessageType, MessagePusher, InMemoryPusher,
100    
101    // 分布式会话
102    DistributedSessionManager, DistributedSession, DistributedSessionStorage, 
103    ServiceCredential, InMemoryDistributedStorage,
104    
105    // 模块
106    token, error
107};
108
109// ============================================================================
110// 重新导出适配器接口(sa-token-adapter)
111// ============================================================================
112pub use sa_token_adapter::{self,
113    storage::SaStorage,
114    framework::FrameworkAdapter,
115};
116
117// ============================================================================
118// 重新导出宏(sa-token-macro)
119// ============================================================================
120pub use sa_token_macro::{
121    sa_check_login,
122    sa_check_permission,
123    sa_check_role,
124    sa_check_permissions_and,
125    sa_check_permissions_or,
126    sa_check_roles_and,
127    sa_check_roles_or,
128    sa_ignore,
129};
130
131// ============================================================================
132// 重新导出存储实现(根据 feature 条件编译)
133// ============================================================================
134
135/// 内存存储(默认启用)
136#[cfg(feature = "memory")]
137pub use sa_token_storage_memory::MemoryStorage;
138
139/// Redis 存储
140#[cfg(feature = "redis")]
141pub use sa_token_storage_redis::RedisStorage;
142
143/// 数据库存储
144#[cfg(feature = "database")]
145pub use sa_token_storage_database::DatabaseStorage;
146
147use std::sync::Arc;
148use actix_web::web::Data;
149
150/// Actix-web应用数据
151pub type SaTokenData = Data<SaTokenState>;
152
153/// 应用状态
154#[derive(Clone)]
155pub struct SaTokenState {
156    pub manager: Arc<SaTokenManager>,
157}
158
159impl SaTokenState {
160    /// 创建状态构建器
161    pub fn builder() -> SaTokenStateBuilder {
162        SaTokenStateBuilder::new()
163    }
164}
165
166/// 状态构建器
167#[derive(Default)]
168pub struct SaTokenStateBuilder {
169    config_builder: sa_token_core::config::SaTokenConfigBuilder,
170}
171
172impl SaTokenStateBuilder {
173    pub fn new() -> Self {
174        Self::default()
175    }
176    
177    pub fn storage(mut self, storage: Arc<dyn SaStorage>) -> Self {
178        self.config_builder = self.config_builder.storage(storage);
179        self
180    }
181    
182    pub fn token_name(mut self, name: impl Into<String>) -> Self {
183        self.config_builder = self.config_builder.token_name(name);
184        self
185    }
186    
187    pub fn timeout(mut self, timeout: i64) -> Self {
188        self.config_builder = self.config_builder.timeout(timeout);
189        self
190    }
191    
192    pub fn active_timeout(mut self, timeout: i64) -> Self {
193        self.config_builder = self.config_builder.active_timeout(timeout);
194        self
195    }
196    
197    /// 设置是否开启自动续签
198    pub fn auto_renew(mut self, enabled: bool) -> Self {
199        self.config_builder = self.config_builder.auto_renew(enabled);
200        self
201    }
202    
203    pub fn is_concurrent(mut self, concurrent: bool) -> Self {
204        self.config_builder = self.config_builder.is_concurrent(concurrent);
205        self
206    }
207    
208    pub fn is_share(mut self, share: bool) -> Self {
209        self.config_builder = self.config_builder.is_share(share);
210        self
211    }
212    
213    /// 设置 Token 风格
214    pub fn token_style(mut self, style: sa_token_core::config::TokenStyle) -> Self {
215        self.config_builder = self.config_builder.token_style(style);
216        self
217    }
218    
219    pub fn token_prefix(mut self, prefix: impl Into<String>) -> Self {
220        self.config_builder = self.config_builder.token_prefix(prefix);
221        self
222    }
223    
224    pub fn jwt_secret_key(mut self, key: impl Into<String>) -> Self {
225        self.config_builder = self.config_builder.jwt_secret_key(key);
226        self
227    }
228    
229    pub fn build(self) -> Data<SaTokenState> {
230        let manager = self.config_builder.build();
231        
232        // 自动初始化全局 StpUtil
233        sa_token_core::StpUtil::init_manager(manager.clone());
234        
235        Data::new(SaTokenState {
236            manager: Arc::new(manager),
237        })
238    }
239}
240