|
| 1 | +package kattsyn.dev.rentplace.services.impl; |
| 2 | + |
| 3 | +import jakarta.security.auth.message.AuthException; |
| 4 | +import kattsyn.dev.rentplace.entities.User; |
| 5 | +import kattsyn.dev.rentplace.exceptions.NotFoundException; |
| 6 | +import kattsyn.dev.rentplace.repositories.UserRepository; |
| 7 | +import kattsyn.dev.rentplace.services.SecurityService; |
| 8 | +import lombok.RequiredArgsConstructor; |
| 9 | +import org.springframework.security.core.Authentication; |
| 10 | +import org.springframework.security.core.context.SecurityContextHolder; |
| 11 | +import org.springframework.stereotype.Service; |
| 12 | + |
| 13 | +@Service |
| 14 | +@RequiredArgsConstructor |
| 15 | +public class SecurityServiceImpl implements SecurityService { |
| 16 | + |
| 17 | + private final UserRepository userRepository; |
| 18 | + |
| 19 | + @Override |
| 20 | + public String getCurrentUserEmail() throws AuthException { |
| 21 | + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); |
| 22 | + if (auth == null || !auth.isAuthenticated() || "anonymousUser".equals(auth.getName())) { |
| 23 | + throw new AuthException("Пользователь не авторизован"); |
| 24 | + } |
| 25 | + Object principal = auth.getPrincipal(); |
| 26 | + return (principal instanceof User) ? ((User) principal).getEmail() : principal.toString(); |
| 27 | + } |
| 28 | + |
| 29 | + @Override |
| 30 | + public User getCurrentUser() throws AuthException { |
| 31 | + String email = getCurrentUserEmail(); |
| 32 | + return userRepository.findByEmail(email) |
| 33 | + .orElseThrow(() -> new NotFoundException(String.format("User with email %s not found", email))); |
| 34 | + } |
| 35 | + |
| 36 | + @Override |
| 37 | + public Long getCurrentUserId() throws AuthException { |
| 38 | + return getCurrentUser().getUserId(); |
| 39 | + } |
| 40 | +} |
0 commit comments