sa_token_plugin_axum/
lib.rs

1// Author: 金书记
2//
3//! # sa-token-plugin-axum
4//! 
5//! Axum框架集成插件 - 一站式认证授权解决方案
6//! 
7//! ## 快速开始
8//! 
9//! 只需要导入这一个包,即可使用所有功能:
10//! 
11//! ```toml
12//! [dependencies]
13//! sa-token-plugin-axum = "0.1.3"  # 默认使用内存存储
14//! # 或者使用 Redis 存储
15//! sa-token-plugin-axum = { version = "0.1.3", features = ["redis"] }
16//! ```
17//! 
18//! ## 使用示例
19//! 
20//! ```rust,ignore
21//! use axum::{Router, routing::get};
22//! use sa_token_plugin_axum::*;  // 一次性导入所有功能
23//! 
24//! #[tokio::main]
25//! async fn main() {
26//!     // 1. 初始化(使用内存存储,已重新导出)
27//!     let state = SaTokenState::builder()
28//!         .storage(Arc::new(MemoryStorage::new()))
29//!         .timeout(7200)
30//!         .build();
31//!     
32//!     // 2. 创建路由
33//!     let app = Router::new()
34//!         .route("/api/user", get(user_info))
35//!         .layer(SaTokenLayer::new(state.clone()))
36//!         .with_state(state);
37//!     
38//!     // 3. 使用宏检查权限
39//!     #[sa_check_login]
40//!     async fn user_info() -> String {
41//!         "User info".to_string()
42//!     }
43//! }
44//! ```
45
46pub mod layer;
47pub mod extractor;
48pub mod middleware;
49pub mod adapter;
50
51// ============================================================================
52// Axum 框架集成(本插件特有)
53// ============================================================================
54pub use layer::SaTokenLayer;
55pub use extractor::{SaTokenExtractor, OptionalSaTokenExtractor, LoginIdExtractor};
56pub use middleware::{SaTokenMiddleware, SaCheckLoginLayer, SaCheckLoginMiddleware, SaCheckPermissionLayer, SaCheckPermissionMiddleware};
57
58pub use sa_token_core::{self, prelude::*};
59pub use sa_token_adapter::{self, storage::SaStorage, framework::FrameworkAdapter};
60pub use sa_token_macro::*;
61
62// ============================================================================
63// 重新导出存储实现(根据 feature 条件编译)
64// ============================================================================
65
66/// 内存存储(默认启用)
67#[cfg(feature = "memory")]
68pub use sa_token_storage_memory::MemoryStorage;
69
70/// Redis 存储
71#[cfg(feature = "redis")]
72pub use sa_token_storage_redis::RedisStorage;
73
74/// 数据库存储
75#[cfg(feature = "database")]
76pub use sa_token_storage_database::DatabaseStorage;
77
78use std::sync::Arc;
79
80/// Axum应用状态
81#[derive(Clone)]
82pub struct SaTokenState {
83    pub manager: Arc<SaTokenManager>,
84}
85
86impl SaTokenState {
87    /// 从存储和配置创建状态
88    pub fn new(storage: Arc<dyn SaStorage>, config: SaTokenConfig) -> Self {
89        Self {
90            manager: Arc::new(SaTokenManager::new(storage, config)),
91        }
92    }
93    
94    /// 从 SaTokenManager 创建状态
95    pub fn from_manager(manager: SaTokenManager) -> Self {
96        Self {
97            manager: Arc::new(manager),
98        }
99    }
100    
101    /// 使用构建器模式创建状态
102    /// 
103    /// # 示例
104    /// ```rust,ignore
105    /// use std::sync::Arc;
106    /// use sa_token_plugin_axum::SaTokenState;
107    /// use sa_token_storage_memory::MemoryStorage;
108    /// use sa_token_core::SaTokenConfig;
109    /// 
110    /// let state = SaTokenState::builder()
111    ///     .storage(Arc::new(MemoryStorage::new()))
112    ///     .timeout(7200)
113    ///     .build();
114    /// ```
115    pub fn builder() -> SaTokenStateBuilder {
116        SaTokenStateBuilder::default()
117    }
118}
119
120/// SaTokenState 构建器
121#[derive(Default)]
122pub struct SaTokenStateBuilder {
123    config_builder: sa_token_core::config::SaTokenConfigBuilder,
124}
125
126impl SaTokenStateBuilder {
127    pub fn token_name(mut self, name: impl Into<String>) -> Self {
128        self.config_builder = self.config_builder.token_name(name);
129        self
130    }
131    
132    pub fn timeout(mut self, timeout: i64) -> Self {
133        self.config_builder = self.config_builder.timeout(timeout);
134        self
135    }
136    
137    pub fn active_timeout(mut self, timeout: i64) -> Self {
138        self.config_builder = self.config_builder.active_timeout(timeout);
139        self
140    }
141    
142    /// 设置是否开启自动续签
143    pub fn auto_renew(mut self, enabled: bool) -> Self {
144        self.config_builder = self.config_builder.auto_renew(enabled);
145        self
146    }
147    
148    pub fn is_concurrent(mut self, concurrent: bool) -> Self {
149        self.config_builder = self.config_builder.is_concurrent(concurrent);
150        self
151    }
152    
153    pub fn is_share(mut self, share: bool) -> Self {
154        self.config_builder = self.config_builder.is_share(share);
155        self
156    }
157    
158    pub fn token_style(mut self, style: sa_token_core::config::TokenStyle) -> Self {
159        self.config_builder = self.config_builder.token_style(style);
160        self
161    }
162    
163    pub fn token_prefix(mut self, prefix: impl Into<String>) -> Self {
164        self.config_builder = self.config_builder.token_prefix(prefix);
165        self
166    }
167    
168    pub fn jwt_secret_key(mut self, key: impl Into<String>) -> Self {
169        self.config_builder = self.config_builder.jwt_secret_key(key);
170        self
171    }
172    
173    pub fn storage(mut self, storage: Arc<dyn SaStorage>) -> Self {
174        self.config_builder = self.config_builder.storage(storage);
175        self
176    }
177    
178    pub fn build(self) -> SaTokenState {
179        // config_builder.build() 已经自动初始化了 StpUtil
180        // config_builder.build() already auto-initializes StpUtil
181        let manager = self.config_builder.build();
182        // 直接创建 SaTokenState,不再调用 from_manager 避免重复初始化
183        // Create SaTokenState directly, don't call from_manager to avoid duplicate initialization
184        SaTokenState {
185            manager: Arc::new(manager),
186        }
187    }
188}