admin_config/
security_config.rs1use serde::{Deserialize, Serialize};
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
32pub struct SecurityConfig {
33 pub aes_key: String,
35 pub aes_iv: String,
37 pub api_key_encrypt_key: String,
39 pub password_salt: String,
41 pub enable_cors: bool,
43 pub allowed_origins: String,
45 pub enable_csrf: bool,
47}
48
49impl Default for SecurityConfig {
50 fn default() -> Self {
51 Self {
52 aes_key: Self::generate_hex(32),
53 aes_iv: Self::generate_hex(16),
54 api_key_encrypt_key: Self::generate_hex(32),
55 password_salt: Self::generate_hex(16),
56 enable_cors: true,
57 allowed_origins: String::new(),
58 enable_csrf: false,
59 }
60 }
61}
62
63impl SecurityConfig {
64 pub fn allowed_origins_list(&self) -> Vec<String> {
68 self.allowed_origins
69 .split(',')
70 .map(|s| s.trim().to_string())
71 .filter(|s| !s.is_empty())
72 .collect()
73 }
74
75 pub fn generate_hex(byte_len: usize) -> String {
77 (0..byte_len).map(|_| format!("{:02x}", rand::random::<u8>())).collect()
78 }
79
80 pub fn validate(&self) -> Result<(), String> {
84 if self.aes_key.len() != 64 {
85 return Err(format!(
86 "aes_key 必须是 64 位十六进制字符串(32 字节),当前长度: {}",
87 self.aes_key.len()
88 ));
89 }
90
91 if self.aes_iv.len() != 32 {
92 return Err(format!(
93 "aes_iv 必须是 32 位十六进制字符串(16 字节),当前长度: {}",
94 self.aes_iv.len()
95 ));
96 }
97
98 if self.api_key_encrypt_key.len() != 64 {
99 return Err(format!(
100 "api_key_encrypt_key 必须是 64 位十六进制字符串(32 字节),当前长度: {}",
101 self.api_key_encrypt_key.len()
102 ));
103 }
104
105 if !self.aes_key.chars().all(|c| c.is_ascii_hexdigit()) {
106 return Err("aes_key 必须只包含十六进制字符 (0-9, a-f, A-F)".to_string());
107 }
108
109 if !self.aes_iv.chars().all(|c| c.is_ascii_hexdigit()) {
110 return Err("aes_iv 必须只包含十六进制字符 (0-9, a-f, A-F)".to_string());
111 }
112
113 if !self.api_key_encrypt_key.chars().all(|c| c.is_ascii_hexdigit()) {
114 return Err("api_key_encrypt_key 必须只包含十六进制字符 (0-9, a-f, A-F)".to_string());
115 }
116
117 Ok(())
118 }
119}