admin_config/
auth_config.rs

1//! 认证配置模块
2//!
3//! 提供 JWT Token 相关的配置管理
4
5use serde::{Deserialize, Serialize};
6
7/// 认证配置
8///
9/// 用于配置 JWT Token 的密钥和过期时间
10///
11/// # 字段说明
12///
13/// - `token_secret`: JWT 签名密钥,默认自动生成 32 字节随机密钥
14/// - `token_expiry_hours`: Access Token 过期时间(小时),默认 24 小时
15/// - `refresh_token_expiry_days`: Refresh Token 过期时间(天),默认 7 天
16///
17/// # 示例
18///
19/// ```rust
20/// use admin_config::AuthConfig;
21///
22/// let config = AuthConfig::default();
23/// assert_eq!(config.token_expiry_hours, 24);
24/// assert_eq!(config.refresh_token_expiry_days, 7);
25/// ```
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct AuthConfig {
28    /// JWT 密钥
29    pub token_secret: String,
30    /// Token 过期时间(小时)
31    pub token_expiry_hours: u64,
32    /// Refresh Token 过期时间(天)
33    pub refresh_token_expiry_days: u64,
34}
35
36impl Default for AuthConfig {
37    fn default() -> Self {
38        Self {
39            token_secret: Self::generate_token_secret(),
40            token_expiry_hours: 24,
41            refresh_token_expiry_days: 7,
42        }
43    }
44}
45
46impl AuthConfig {
47    /// 获取 Token 过期时间(秒)
48    pub fn token_expiry_seconds(&self) -> u64 {
49        self.token_expiry_hours * 3600
50    }
51
52    /// 获取 Refresh Token 过期时间(秒)
53    pub fn refresh_token_expiry_seconds(&self) -> u64 {
54        self.refresh_token_expiry_days * 86400
55    }
56
57    /// 生成32字节(64位十六进制)的JWT密钥
58    fn generate_token_secret() -> String {
59        (0..32).map(|_| format!("{:02x}", rand::random::<u8>())).collect()
60    }
61}