mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-02-23 22:50:51 +08:00
feat: add email verification
This commit is contained in:
@@ -8,6 +8,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.Random;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -17,17 +18,33 @@ public class UserService {
|
||||
|
||||
public User register(String username, String email, String password) {
|
||||
if (userRepository.findByUsername(username).isPresent() || userRepository.findByEmail(email).isPresent()) {
|
||||
throw new RuntimeException("User already exists");
|
||||
throw new IllegalStateException("User already exists");
|
||||
}
|
||||
User user = new User();
|
||||
user.setUsername(username);
|
||||
user.setEmail(email);
|
||||
user.setPassword(passwordEncoder.encode(password));
|
||||
user.setVerified(false);
|
||||
String code = String.format("%06d", new Random().nextInt(1000000));
|
||||
user.setVerificationCode(code);
|
||||
return userRepository.save(user);
|
||||
}
|
||||
|
||||
public boolean verifyCode(String username, String code) {
|
||||
Optional<User> userOpt = userRepository.findByUsername(username);
|
||||
if (userOpt.isPresent() && code.equals(userOpt.get().getVerificationCode())) {
|
||||
User user = userOpt.get();
|
||||
user.setVerified(true);
|
||||
user.setVerificationCode(null);
|
||||
userRepository.save(user);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public Optional<User> authenticate(String username, String password) {
|
||||
return userRepository.findByUsername(username)
|
||||
.filter(User::isVerified)
|
||||
.filter(user -> passwordEncoder.matches(password, user.getPassword()));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user