package ru.mtusi.messenger.service; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ru.mtusi.messenger.dto.UserDTO; import ru.mtusi.messenger.exception.ConflictException; import ru.mtusi.messenger.exception.NotFoundException; import ru.mtusi.messenger.exception.UnauthorizedException; import ru.mtusi.messenger.mapper.UserMapper; import ru.mtusi.messenger.model.User; import ru.mtusi.messenger.repository.UserRepository; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; @Service @RequiredArgsConstructor @Slf4j public class UserService { private final PasswordEncoder passwordEncoder; private final UserMapper userMapper; private final UserRepository userRepository; @Transactional public Set requireUsers(Collection ids) { Set uniqueIds = new HashSet<>(ids); Set users = userRepository.findAllByIdForShare(uniqueIds); if (users.size() != uniqueIds.size()) { throw new NotFoundException("Users not found: " + findMissing(uniqueIds, users)); } return users; } private Set findMissing(Set requested, Set found) { Set foundIds = found.stream() .map(User::getId) .collect(Collectors.toSet()); Set missing = new HashSet<>(requested); missing.removeAll(foundIds); return missing; } @Transactional(readOnly = true) public UserDTO authenticate(String username, String password) { User user = userRepository.findByUsername(username).orElseThrow(() -> new UnauthorizedException("Bad credentials")); if (!passwordEncoder.matches(password, user.getPasswordHash())) { throw new UnauthorizedException("Bad credentials"); } return userMapper.toUserDto(user); } @Transactional public UserDTO registerUser(UserDTO userDTO) { User user = userMapper.toUser(userDTO); user.setPasswordHash(passwordEncoder.encode(userDTO.getPassword())); try { return userMapper.toUserDto(userRepository.saveAndFlush(user)); } catch (DataIntegrityViolationException exception) { throw new ConflictException("Username already exists"); } } @Transactional(readOnly = true) public UserDTO currentUser(UUID userId) { return userMapper.toUserDto(userRepository.findById(userId).orElseThrow(() -> new NotFoundException("User not found") )); } @Transactional public User getReferenceUserById(UUID senderId) { return userRepository.getReferenceById(senderId); } }