Refine login error handling and adjust Google signup flow

This commit is contained in:
Tim
2025-07-15 11:06:33 +08:00
parent f65df582f6
commit abb6c98df7
6 changed files with 87 additions and 43 deletions

View File

@@ -72,12 +72,24 @@ public class AuthController {
if (captchaEnabled && loginCaptchaEnabled && !captchaService.verify(req.getCaptcha())) {
return ResponseEntity.badRequest().body(Map.of("error", "Invalid captcha"));
}
Optional<User> user = userService.authenticate(req.getUsername(), req.getPassword());
if (user.isPresent()) {
return ResponseEntity.ok(Map.of("token", jwtService.generateToken(user.get().getUsername())));
} else {
return ResponseEntity.badRequest().body(Map.of("error", "Invalid credentials or user not verified"));
Optional<User> userOpt = userService.findByUsername(req.getUsername());
if (userOpt.isEmpty() || !userService.matchesPassword(userOpt.get(), req.getPassword())) {
return ResponseEntity.badRequest().body(Map.of(
"error", "Invalid credentials",
"reason_code", "INVALID_CREDENTIALS"));
}
User user = userOpt.get();
if (!user.isVerified()) {
return ResponseEntity.badRequest().body(Map.of(
"error", "User not verified",
"reason_code", "NOT_VERIFIED"));
}
if (!user.isApproved()) {
return ResponseEntity.badRequest().body(Map.of(
"error", "Register reason not approved",
"reason_code", "NOT_APPROVED"));
}
return ResponseEntity.ok(Map.of("token", jwtService.generateToken(user.getUsername())));
}
@PostMapping("/google")

View File

@@ -94,6 +94,10 @@ public class UserService {
.filter(user -> passwordEncoder.matches(password, user.getPassword()));
}
public boolean matchesPassword(User user, String rawPassword) {
return passwordEncoder.matches(rawPassword, user.getPassword());
}
public Optional<User> findByUsername(String username) {
return userRepository.findByUsername(username);
}