admin_config/session_config.rs
1//! Session 配置模块
2//!
3//! 提供会话管理相关的配置
4
5use serde::{Deserialize, Serialize};
6
7/// Session 配置
8///
9/// 用于配置服务器端会话和 Cookie 行为
10///
11/// # 字段说明
12///
13/// - `secret_key`: Session 加密密钥,默认自动生成 32 字节随机密钥
14/// - `max_age`: Session 过期时间(秒),默认 86400 秒(24 小时)
15/// - `http_only`: Cookie 是否仅允许 HTTP 访问,禁止 JavaScript 读取,默认 true
16/// - `secure`: Cookie 是否仅在 HTTPS 下传输,默认 false
17/// - `cookie_path`: Cookie 有效路径,默认 "/"
18/// - `cookie_domain`: Cookie 有效域名,默认 None(当前域名)
19///
20/// # 示例
21///
22/// ```rust
23/// use admin_config::SessionConfig;
24///
25/// let config = SessionConfig::default();
26/// assert_eq!(config.max_age, 86400);
27/// assert!(config.http_only);
28/// assert_eq!(config.cookie_path, "/");
29/// ```
30#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct SessionConfig {
32 /// Session 密钥
33 pub secret_key: String,
34 /// 过期时间(秒)
35 pub max_age: u64,
36 /// 是否仅 HTTP 访问
37 pub http_only: bool,
38 /// 是否仅 HTTPS 访问
39 pub secure: bool,
40 /// Cookie 路径
41 pub cookie_path: String,
42 /// Cookie 域名
43 pub cookie_domain: Option<String>,
44}
45
46impl Default for SessionConfig {
47 fn default() -> Self {
48 Self {
49 secret_key: Self::generate_secret_key(),
50 max_age: 86400,
51 http_only: true,
52 secure: false,
53 cookie_path: "/".to_string(),
54 cookie_domain: None,
55 }
56 }
57}
58
59impl SessionConfig {
60 /// 生成32字节(64位十六进制)的会话密钥
61 fn generate_secret_key() -> String {
62 (0..32).map(|_| format!("{:02x}", rand::random::<u8>())).collect()
63 }
64}