REFACTOR code to use Optional entity

This commit is contained in:
2025-08-12 15:39:06 +02:00
parent 19a78df4c6
commit 6433294ced
7 changed files with 121 additions and 74 deletions

View File

@@ -41,17 +41,16 @@ public class UserService {
this.jwtService = jwtService;
}
public User getUserById(Long userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new NotAuthenticated("User not found"));
public Optional<User> getUserById(Long userId) {
return userRepository.findById(userId);
}
public User getLoggedInUser() {
public Optional<User> getLoggedInUser() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.isAuthenticated() && auth.getPrincipal() instanceof User) {
return (User) auth.getPrincipal();
if (auth != null && auth.isAuthenticated() && auth.getPrincipal() instanceof User user) {
return Optional.of(user);
}
return null;
return Optional.empty();
}
public String login(String idToken) {