@@ -10,13 +10,58 @@ use crate::error::{AppError, AppErrorType};
1010use crate :: middleware:: auth;
1111use 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/// 接收用户注册信息,验证数据有效性,然后创建新用户
1656pub 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