修改了注册的字段和数据传递逻辑

This commit is contained in:
高子兴 2024-07-01 20:38:08 +08:00
parent 3fdded3c9c
commit 9c46495d40
3 changed files with 14 additions and 12 deletions

View File

@ -28,14 +28,16 @@ class AuthenticationController {
@PostMapping("/register")
public ResponseEntity<RegisterResponse> register(@RequestBody RegisterRequest request) {
try {
boolean isRegistered = userService.registerUser(request.getUsername(), request.getPassword(), request.getContactInfo());
boolean isRegistered = userService.registerUser(request);
if (isRegistered) {
return new ResponseEntity<>(new RegisterResponse("注册成功"), HttpStatus.OK);
} else {
return new ResponseEntity<>(new RegisterResponse("注册失败:用户已存在"), HttpStatus.BAD_REQUEST);
}
} catch (Exception e) {
} catch (IllegalArgumentException e) {
return new ResponseEntity<>(new RegisterResponse("注册失败:输入格式有误"), HttpStatus.BAD_REQUEST);
} catch (Exception e) {
return new ResponseEntity<>(new RegisterResponse("注册失败:服务器错误"), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

View File

@ -8,5 +8,6 @@ import lombok.Setter;
public class RegisterRequest {
private String username;
private String password;
private String contactInfo;
private String phoneNumber;
private String verificationCode;
}

View File

@ -2,6 +2,7 @@ package org.cmh.backend.authentication.service;
import org.cmh.backend.authentication.dto.ChangePasswordRequest;
import org.cmh.backend.authentication.dto.ManageUserProfileRequest;
import org.cmh.backend.authentication.dto.RegisterRequest;
import org.cmh.backend.authentication.model.UserHS;
import org.cmh.backend.authentication.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
@ -23,14 +24,17 @@ public class UserService {
return userRepository.findByUsername(username);
}
public boolean registerUser(String username, String password, String contactInfo) {
public boolean registerUser(RegisterRequest request) {
String username = request.getUsername();
String password = request.getPassword();
String phoneNumber = request.getPhoneNumber();
// 验证用户名是否已存在
if (userRepository.findByUsername(username) != null) {
return false; // 用户已存在
}
// 验证输入格式
if (!isValidUsername(username) || !isValidPassword(password) || !isValidContactInfo(contactInfo)) {
if (!isValidUsername(username) || !isValidPassword(password) || !isValidContactInfo(phoneNumber)) {
throw new IllegalArgumentException();
}
@ -41,15 +45,10 @@ public class UserService {
UserHS newUser = new UserHS();
newUser.setUsername(username);
newUser.setPassword(encodedPassword);
newUser.setPhoneNumber(contactInfo); // 假设contactInfo是电话号码
newUser.setPhoneNumber(phoneNumber);
newUser.setCreatedAt(LocalDateTime.now());
try {
userRepository.save(newUser);
} catch (Exception e) {
// 处理保存用户时可能出现的异常
return false;
}
return true;
}