Skip to content

Commit 493b333

Browse files
committed
feat: 增强用户注册和认证功能,添加输入验证;优化文章标签管理逻辑,支持批量添加和更新标签
1 parent b371bc8 commit 493b333

12 files changed

Lines changed: 324 additions & 230 deletions

File tree

backend/src/api/postapi.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -102,10 +102,7 @@ pub async fn delete_post(
102102
State(state): State<crate::state::AppState>,
103103
Path(id): Path<Uuid>,
104104
) -> Result<Json<serde_json::Value>, AppError> {
105-
// 先删除文章的所有标签关联
106-
post::Post::remove_all_labels(state.pool.as_ref(), id).await?;
107-
108-
// 删除文章
105+
// 直接删除文章(标签关联通过数据库 CASCADE 自动删除)
109106
let deleted = post::Post::delete(state.pool.as_ref(), id).await?;
110107

111108
if deleted {

backend/src/api/userapi.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,58 @@ use crate::error::{AppError, AppErrorType};
1010
use crate::middleware::auth;
1111
use crate::model::models::user::{CreateUserRequest, LoginRequest, UpdateUserRequest, User};
1212

13+
/// 验证用户名格式
14+
fn validate_username(username: &str) -> Result<(), AppError> {
15+
if username.len() < 3 {
16+
return Err(AppError::new_message("用户名至少需要3个字符", AppErrorType::Internal));
17+
}
18+
if username.len() > 50 {
19+
return Err(AppError::new_message("用户名不能超过50个字符", AppErrorType::Internal));
20+
}
21+
if !username.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '-') {
22+
return Err(AppError::new_message(
23+
"用户名只能包含字母、数字、下划线和连字符",
24+
AppErrorType::Internal,
25+
));
26+
}
27+
Ok(())
28+
}
29+
30+
/// 验证邮箱格式
31+
fn validate_email(email: &str) -> Result<(), AppError> {
32+
if email.len() > 100 {
33+
return Err(AppError::new_message("邮箱不能超过100个字符", AppErrorType::Internal));
34+
}
35+
// 简单的邮箱格式验证
36+
if !email.contains('@') || !email.contains('.') {
37+
return Err(AppError::new_message("邮箱格式不正确", AppErrorType::Internal));
38+
}
39+
Ok(())
40+
}
41+
42+
/// 验证密码强度
43+
fn validate_password(password: &str) -> Result<(), AppError> {
44+
if password.len() < 6 {
45+
return Err(AppError::new_message("密码至少需要6个字符", AppErrorType::Internal));
46+
}
47+
if password.len() > 100 {
48+
return Err(AppError::new_message("密码不能超过100个字符", AppErrorType::Internal));
49+
}
50+
Ok(())
51+
}
52+
1353
/// 用户注册API
1454
///
1555
/// 接收用户注册信息,验证数据有效性,然后创建新用户
1656
pub async fn register_user(
1757
State(state): State<crate::state::AppState>,
1858
Json(req): Json<CreateUserRequest>,
1959
) -> Result<Json<User>, AppError> {
60+
// 验证输入
61+
validate_username(&req.username)?;
62+
validate_email(&req.email)?;
63+
validate_password(&req.password)?;
64+
2065
// 验证用户名是否已存在
2166
if let Ok(Some(_)) = User::find_by_username(&state.pool, &req.username).await {
2267
return Err(AppError::new_message(

0 commit comments

Comments
 (0)