forked from mtusi2026/mtusi2026lab2
Исправление по Ревью
This commit is contained in:
@@ -107,25 +107,40 @@ public class AuthService {
|
||||
}
|
||||
|
||||
|
||||
public Optional<User> resolveUserByBearer(String rawToken) {
|
||||
String hash = TokenHasher.sha256(rawToken);
|
||||
private final ConcurrentHashMap<String, Object> inflight = new ConcurrentHashMap<>();
|
||||
|
||||
Optional<UUID> cached = cacheService.get(hash);
|
||||
if (cached.isPresent()) {
|
||||
return userRepository.findById(cached.get());
|
||||
@Transactional(readOnly = true)
|
||||
public Optional<User> resolveUserByBearer(String rawToken) {
|
||||
if (rawToken == null || rawToken.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
Object lock = locks.computeIfAbsent(hash, h -> new Object());
|
||||
final String hash = TokenHasher.sha256(rawToken);
|
||||
|
||||
Optional<UUID> cachedUserId = cacheService.get(hash);
|
||||
if (cachedUserId.isPresent()) {
|
||||
return userRepository.findById(cachedUserId.get());
|
||||
}
|
||||
|
||||
Object lock = inflight.computeIfAbsent(hash, h -> new Object());
|
||||
try {
|
||||
synchronized (lock) {
|
||||
cached = cacheService.get(hash);
|
||||
if (cached.isPresent()) {
|
||||
return userRepository.findById(cached.get());
|
||||
cachedUserId = cacheService.get(hash);
|
||||
if (cachedUserId.isPresent()) {
|
||||
return userRepository.findById(cachedUserId.get());
|
||||
}
|
||||
return resolveUserByBearer(hash);
|
||||
|
||||
Instant now = Instant.now();
|
||||
Optional<Session> session = sessionRepository.findByToken(hash);
|
||||
if (session.isEmpty() || !session.get().isActive(now)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Session s = session.get();
|
||||
cacheService.put(hash, s.getUserId(), s.getExpiresAt());
|
||||
return userRepository.findById(s.getUserId());
|
||||
}
|
||||
} finally {
|
||||
locks.remove(hash, lock);
|
||||
inflight.remove(hash, lock);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import org.example.model.ChatMember;
|
||||
import org.example.model.User;
|
||||
import org.example.repository.ChatMemberRepository;
|
||||
import org.example.repository.ChatRepository;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@@ -31,18 +32,21 @@ public class ChatService {
|
||||
User currentUser = userService.getCurrentUser();
|
||||
UUID currentId = currentUser.getId();
|
||||
|
||||
List<UUID> memberIds = dto.getMemberIds().stream()
|
||||
.distinct()
|
||||
.toList();
|
||||
|
||||
List<UUID> memberIds = dto.getMemberIds();
|
||||
if (memberIds == null || memberIds.isEmpty()) {
|
||||
throw new IllegalArgumentException("member_ids must not be empty");
|
||||
}
|
||||
long distinctCount = memberIds.stream().distinct().count();
|
||||
if (distinctCount != memberIds.size()) {
|
||||
throw new IllegalArgumentException("duplicate member_ids");
|
||||
}
|
||||
if (!memberIds.contains(currentId)) {
|
||||
throw new IllegalArgumentException(
|
||||
"Создатель чата должен входить в список участников (member_ids)");
|
||||
"creator must be in member_ids");
|
||||
}
|
||||
|
||||
for (UUID memberId : memberIds) {
|
||||
if (!userService.exists(memberId)) {
|
||||
throw new NotFoundException("Пользователь с ID " + memberId + " не найден");
|
||||
throw new IllegalArgumentException("unknown member_id");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,17 +81,25 @@ public class ChatService {
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public ChatPage getChatsForCurrentUser(int limit) {
|
||||
UUID userId = userService.getCurrentUser().getId();
|
||||
List<ChatResponse> items = new ArrayList<>();
|
||||
|
||||
for (ChatMember membership : chatMemberRepository.findByUserId(userId)) {
|
||||
if (items.size() >= limit) {
|
||||
break;
|
||||
}
|
||||
chatRepository.findById(membership.getChatId())
|
||||
.ifPresent(chat -> items.add(toResponse(chat.getId())));
|
||||
if (limit < 1 || limit > 100) {
|
||||
throw new IllegalArgumentException("limit must be 1..100");
|
||||
}
|
||||
return new ChatPage(items, null);
|
||||
UUID userId = userService.getCurrentUser().getId();
|
||||
List<Chat> raw = chatRepository.findForUserOrderByCreatedAtAsc(
|
||||
userId,
|
||||
PageRequest.of(0, limit + 1)
|
||||
);
|
||||
boolean hasMore = raw.size() > limit;
|
||||
List<Chat> page = hasMore ? raw.subList(0, limit) : raw;
|
||||
List<ChatResponse> items = page.stream()
|
||||
.map(c -> toResponse(c.getId()))
|
||||
.toList();
|
||||
String nextCursor = null;
|
||||
if (hasMore && !items.isEmpty()) {
|
||||
nextCursor = items.get(items.size() - 1).getId().toString();
|
||||
}
|
||||
|
||||
return new ChatPage(items, nextCursor);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
|
||||
@@ -44,8 +44,8 @@ public class MessageService {
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public MessagePage getMessage(UUID chatId, UUID userId, String cursor, int limit) {
|
||||
if (limit < 1) {
|
||||
throw new IllegalArgumentException("Лимит должен быть больше 0");
|
||||
if (limit < 1 || limit > 100) {
|
||||
throw new IllegalArgumentException("limit must be between 1 and 100");
|
||||
}
|
||||
|
||||
chatService.requireMember(chatId);
|
||||
@@ -57,7 +57,7 @@ public class MessageService {
|
||||
List<Message> items;
|
||||
|
||||
if (cursor == null || cursor.isBlank()) {
|
||||
items = messageRepository.findByChatIdOrderByCreatedAtDescIdDesc(chatId, pageable);
|
||||
items = messageRepository.findByChatIdOrderByCreatedAtAscIdAsc(chatId, pageable);
|
||||
} else {
|
||||
UUID cursorId;
|
||||
try {
|
||||
@@ -67,11 +67,7 @@ public class MessageService {
|
||||
}
|
||||
|
||||
Message cursorMsg = messageRepository.findByIdAndChatId(cursorId, chatId)
|
||||
.orElse(null);
|
||||
|
||||
if (cursorMsg == null) {
|
||||
throw new IllegalArgumentException("Invalid cursor");
|
||||
}
|
||||
.orElseThrow(() -> new IllegalArgumentException("Invalid cursor"));
|
||||
|
||||
items = messageRepository.findNextPage(
|
||||
chatId,
|
||||
@@ -83,7 +79,18 @@ public class MessageService {
|
||||
|
||||
String nextCursor = null;
|
||||
if (items.size() == limit && !items.isEmpty()) {
|
||||
nextCursor = items.get(items.size() - 1).getId().toString();
|
||||
Message last = items.get(items.size() - 1);
|
||||
boolean hasMore = !messageRepository
|
||||
.findNextPage(
|
||||
chatId,
|
||||
last.getCreatedAt(),
|
||||
last.getId(),
|
||||
PageRequest.of(0, 1)
|
||||
)
|
||||
.isEmpty();
|
||||
if (hasMore) {
|
||||
nextCursor = last.getId().toString();
|
||||
}
|
||||
}
|
||||
|
||||
return new MessagePage(items, nextCursor);
|
||||
|
||||
@@ -4,6 +4,7 @@ import lombok.RequiredArgsConstructor;
|
||||
import org.example.config.UserContext;
|
||||
import org.example.dto.create.CreateUserDto;
|
||||
import org.example.dto.update.UpdateUserDto;
|
||||
import org.example.exception.ForbiddenException;
|
||||
import org.example.exception.NotFoundException;
|
||||
import org.example.exception.UnauthorizedException;
|
||||
import org.example.exception.UserAlreadyExistsException;
|
||||
@@ -50,32 +51,51 @@ public class UserService {
|
||||
return user;
|
||||
}
|
||||
|
||||
private User requireCurrentUser() {
|
||||
User user = UserContext.getCurrentUser();
|
||||
if (user == null) {
|
||||
throw new UnauthorizedException("Unauthorized");
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public User getUserById(UUID id) {
|
||||
return userRepository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException("Пользователь с id: " + id + " не найден."));
|
||||
requireCurrentUser();
|
||||
return userRepository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException("Пользователь не найден"));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public User updateUser(UUID id, UpdateUserDto updateObject){
|
||||
User existing = getUserById(id);
|
||||
existing.setDisplayName(updateObject.getDisplayName());
|
||||
return userRepository.save(existing);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public User updateUser(String id, UpdateUserDto updateObject) {
|
||||
return updateUser(parseUuid(id), updateObject);
|
||||
public User updateUser(UUID id, UpdateUserDto dto) {
|
||||
User me = requireCurrentUser();
|
||||
if (!me.getId().equals(id)) {
|
||||
throw new ForbiddenException("Forbidden");
|
||||
}
|
||||
User user = userRepository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException("Пользователь не найден"));
|
||||
user.setDisplayName(dto.getDisplayName());
|
||||
return userRepository.save(user);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteUser(UUID id) {
|
||||
User me = requireCurrentUser();
|
||||
if (!me.getId().equals(id)) {
|
||||
throw new ForbiddenException("Forbidden");
|
||||
}
|
||||
if (!userRepository.existsById(id)) {
|
||||
throw new NotFoundException("Пользователь с id: " + id + " не найден");
|
||||
throw new NotFoundException("Пользователь не найден");
|
||||
}
|
||||
userRepository.deleteById(id);
|
||||
}
|
||||
|
||||
|
||||
@Transactional
|
||||
public User updateUser(String id, UpdateUserDto updateObject) {
|
||||
return updateUser(parseUuid(id), updateObject);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteUser(String id) {
|
||||
deleteUser(parseUuid(id));
|
||||
|
||||
Reference in New Issue
Block a user