This commit is contained in:
2026-10-06 14:32:54 +03:00
parent 65003b6119
commit b95197a6fc
75 changed files with 4403 additions and 28 deletions
@@ -0,0 +1,81 @@
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.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<User> requireUsers(Set<UUID> ids) {
Set<User> users = userRepository.findAllByIdForShare(ids);
if (users.size() != ids.size()) {
throw new NotFoundException("Users not found: " + findMissing(ids, users));
}
return users;
}
private Set<UUID> findMissing(Set<UUID> requested, Set<User> found) {
Set<UUID> foundIds = found.stream()
.map(User::getId)
.collect(Collectors.toSet());
Set<UUID> 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);
}
}