forked from mtusi2026/mtusi2026lab2
Исправление по Ревью
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
package org.example.config;
|
||||
|
||||
import jakarta.validation.Constraint;
|
||||
import jakarta.validation.Payload;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
@Documented
|
||||
@Constraint(validatedBy = CodePointSizeValidator.class)
|
||||
@Target({ ElementType.FIELD, ElementType.PARAMETER })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface CodePointSize {
|
||||
int min() default 0;
|
||||
int max() default Integer.MAX_VALUE;
|
||||
String message() default "size must be between {min} and {max} code points";
|
||||
Class<?>[] groups() default {};
|
||||
Class<? extends Payload>[] payload() default {};
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package org.example.config;
|
||||
|
||||
import jakarta.validation.ConstraintValidator;
|
||||
import jakarta.validation.ConstraintValidatorContext;
|
||||
|
||||
public class CodePointSizeValidator implements ConstraintValidator<CodePointSize, String> {
|
||||
|
||||
private int min;
|
||||
private int max;
|
||||
|
||||
@Override
|
||||
public void initialize(CodePointSize annotation) {
|
||||
this.min = annotation.min();
|
||||
this.max = annotation.max();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(String value, ConstraintValidatorContext context) {
|
||||
if (value == null) {
|
||||
return true;
|
||||
}
|
||||
int n = value.codePointCount(0, value.length());
|
||||
return n >= min && n <= max;
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,38 @@ import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
|
||||
@Configuration
|
||||
public class PasswordConfig {
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder();
|
||||
|
||||
return new PasswordEncoder() {
|
||||
private String prehash(String raw) {
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||
byte[] digest = md.digest(raw.getBytes(StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(digest);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String encode(CharSequence rawPassword) {
|
||||
return bcrypt.encode(prehash(rawPassword.toString()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matches(CharSequence rawPassword, String encodedPassword) {
|
||||
return bcrypt.matches(prehash(rawPassword.toString()), encodedPassword);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package org.example.config;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.JsonToken;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class StrictStringDeserializer extends JsonDeserializer<String> {
|
||||
|
||||
@Override
|
||||
public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
|
||||
if (p.currentToken() != JsonToken.VALUE_STRING) {
|
||||
return (String) ctxt.handleUnexpectedToken(String.class, p);
|
||||
}
|
||||
return p.getValueAsString();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package org.example.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.example.dto.ChatPage;
|
||||
@@ -41,6 +42,7 @@ public class ChatController {
|
||||
@GetMapping
|
||||
public ChatPage getChats(
|
||||
@RequestParam(defaultValue = "50")
|
||||
@Max(100)
|
||||
@Min(value = 1, message = "limit must be >= 1") int limit
|
||||
) {
|
||||
return chatService.getChatsForCurrentUser(limit);
|
||||
@@ -82,6 +84,7 @@ public class ChatController {
|
||||
@PathVariable("id") UUID id,
|
||||
@RequestParam(required = false) String cursor,
|
||||
@RequestParam(defaultValue = "50")
|
||||
@Max(100)
|
||||
@Min(value = 1, message = "limit must be >= 1") int limit
|
||||
) {
|
||||
UUID userId = userService.getCurrentUser().getId();
|
||||
|
||||
@@ -1,18 +1,23 @@
|
||||
package org.example.dto.create;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
import org.example.config.CodePointSize;
|
||||
import org.example.config.StrictStringDeserializer;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Data
|
||||
public class CreateChatDto {
|
||||
@NotBlank(message = "Title не может быть пустым")
|
||||
@Size(max = 100, message = "Title не должен превышать 32 символов")
|
||||
@CodePointSize(min = 1, max = 100)
|
||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||
private String title;
|
||||
|
||||
@JsonProperty("member_ids")
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
package org.example.dto.create;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
import org.example.config.CodePointSize;
|
||||
import org.example.config.StrictStringDeserializer;
|
||||
|
||||
@Data
|
||||
public class CreateMessageDto {
|
||||
@NotBlank(message = "Текст сообщения не может быть пустым")
|
||||
@Size(max = 4000, message = "Максимальная длина сообщения — 1024 символов")
|
||||
@CodePointSize(min = 1, max = 4000)
|
||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||
private String text;
|
||||
}
|
||||
|
||||
@@ -1,26 +1,31 @@
|
||||
package org.example.dto.create;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
import org.example.config.CodePointSize;
|
||||
import org.example.config.StrictStringDeserializer;
|
||||
|
||||
@Data
|
||||
public class CreateUserDto {
|
||||
@NotBlank(message = "Username не может быть пустым")
|
||||
@Size(max = 64, message = "Username не должен превышать 64 символов")
|
||||
@JsonProperty("username")
|
||||
@NotBlank
|
||||
@Size(min = 3, max = 32)
|
||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||
@Pattern(regexp = "^[a-z0-9_]{3,32}$")
|
||||
private String username;
|
||||
|
||||
@NotBlank(message = "Display name не может быть пустым")
|
||||
@Size(max = 100, message = "Display name не должен быть больше 128 символов")
|
||||
@CodePointSize(min = 1, max = 128)
|
||||
@JsonProperty("display_name")
|
||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||
private String displayName;
|
||||
|
||||
@NotBlank(message = "Password не может быть пустым")
|
||||
@Size(min = 12, max = 128, message = "Password: 12–128 символа")
|
||||
@CodePointSize(min = 12, max = 128)
|
||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||
private String password;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
package org.example.dto.update;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
import org.example.config.CodePointSize;
|
||||
import org.example.config.StrictStringDeserializer;
|
||||
|
||||
@Data
|
||||
public class UpdateChatDto {
|
||||
@NotBlank
|
||||
@Size(max = 32)
|
||||
@CodePointSize(min = 1, max = 100)
|
||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||
private String title;
|
||||
}
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
package org.example.dto.update;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
import org.example.config.CodePointSize;
|
||||
import org.example.config.StrictStringDeserializer;
|
||||
|
||||
@Data
|
||||
public class UpdateMessageDto {
|
||||
@NotBlank
|
||||
@Size(max = 1024)
|
||||
@CodePointSize(min = 1, max = 4000)
|
||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||
private String text;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
package org.example.dto.update;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
import org.example.config.CodePointSize;
|
||||
import org.example.config.StrictStringDeserializer;
|
||||
|
||||
@Data
|
||||
public class UpdateUserDto {
|
||||
@NotBlank
|
||||
@Size(max = 128)
|
||||
@CodePointSize(min = 1, max = 128)
|
||||
@JsonProperty("display_name")
|
||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||
private String displayName;
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
@@ -184,4 +185,24 @@ public class GlobalExceptionHandler {
|
||||
.header("X-Request-Id", reqId)
|
||||
.body(body);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
|
||||
public ResponseEntity<?> handleTypeMismatch(
|
||||
MethodArgumentTypeMismatchException ex,
|
||||
HttpServletRequest request
|
||||
) {
|
||||
String reqId = resolveRequestId(request);
|
||||
String message = "Invalid parameter";
|
||||
if (ex.getRequiredType() == UUID.class) {
|
||||
message = "Invalid UUID";
|
||||
}
|
||||
ErrorResponse body = new ErrorResponse(
|
||||
new ErrorDetail("Invalid parameter", "Invalid UUID", reqId)
|
||||
);
|
||||
// Error body: code invalid_request, request_id = reqId
|
||||
return ResponseEntity
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.header("X-Request-Id", reqId)
|
||||
.body(body);
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ public class Chat {
|
||||
@GeneratedValue(strategy = GenerationType.UUID)
|
||||
private UUID id;
|
||||
|
||||
@Column(nullable = false, length = 32)
|
||||
@Column(nullable = false, length = 100)
|
||||
private String title;
|
||||
|
||||
@OneToMany(mappedBy = "chat", fetch = FetchType.LAZY)
|
||||
|
||||
@@ -1,10 +1,23 @@
|
||||
package org.example.repository;
|
||||
|
||||
import org.example.model.Chat;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface ChatRepository extends JpaRepository<Chat, UUID> {
|
||||
@Query("""
|
||||
SELECT c FROM Chat c
|
||||
JOIN ChatMember m ON m.chatId = c.id
|
||||
WHERE m.userId = :userId
|
||||
ORDER BY c.createdAt ASC, c.id ASC
|
||||
""")
|
||||
List<Chat> findForUserOrderByCreatedAtAsc(
|
||||
@Param("userId") UUID userId,
|
||||
Pageable pageable);
|
||||
|
||||
}
|
||||
|
||||
@@ -6,26 +6,29 @@ import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface MessageRepository extends JpaRepository<Message, UUID> {
|
||||
List<Message> findByChatIdOrderByCreatedAtDescIdDesc(UUID chatId, Pageable pageable);
|
||||
|
||||
List<Message> findByChatIdOrderByCreatedAtAscIdAsc(UUID chatId, Pageable pageable);
|
||||
|
||||
@Query("""
|
||||
SELECT m FROM Message m
|
||||
WHERE m.chatId = :chatId
|
||||
AND (m.createdAt < :createdAt
|
||||
OR (m.createdAt = :createdAt AND m.id < :id))
|
||||
ORDER BY m.createdAt DESC, m.id DESC
|
||||
""")
|
||||
SELECT m FROM Message m
|
||||
WHERE m.chatId = :chatId
|
||||
AND (m.createdAt > :createdAt
|
||||
OR (m.createdAt = :createdAt AND m.id > :id))
|
||||
ORDER BY m.createdAt ASC, m.id ASC
|
||||
""")
|
||||
List<Message> findNextPage(
|
||||
@Param("chatId") UUID chatId,
|
||||
@Param("createdAt") Instant createdAt,
|
||||
@Param("id") UUID id,
|
||||
Pageable pageable
|
||||
);
|
||||
|
||||
Optional<Message> findByIdAndChatId(UUID id, UUID chatId);
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
spring:
|
||||
jackson:
|
||||
property-naming-strategy: SNAKE_CASE
|
||||
deserialization:
|
||||
fail-on-unknown-properties: true
|
||||
lifecycle:
|
||||
timeout-per-shutdown-cycle=10s:
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
DROP INDEX IF EXISTS idx_messages_chat_created_id;
|
||||
|
||||
CREATE INDEX idx_messages_chat_created_id
|
||||
ON messages (chat_id, created_at ASC, id ASC);
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE chats
|
||||
ALTER COLUMN title TYPE VARCHAR(100);
|
||||
@@ -1,123 +1,123 @@
|
||||
package org.example;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
public class ApiIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
@Test
|
||||
@DisplayName("400 1. Неверный / битый JSON должен возвращать 400 Bad Request")
|
||||
void shouldReturn400ForMalformedJson() throws Exception {
|
||||
String malformedJson = "{\"username\": \"bad_json\", \"display_name\":}";
|
||||
|
||||
mockMvc.perform(post("/api/v1/users")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(malformedJson))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("400 2. Валидация: пустой username должен возвращать 400 Bad Request")
|
||||
void shouldReturn400ForEmptyUsername() throws Exception {
|
||||
String invalidJson = "{\"username\": \"\", \"display_name\": \"User\"}";
|
||||
|
||||
mockMvc.perform(post("/api/v1/users")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(invalidJson))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("404 3. Неучастник чата получает 404 (чат скрыт)")
|
||||
void shouldReturn404WhenUserIsNotChatMember() throws Exception {
|
||||
String aliceJson = mockMvc.perform(post("/api/v1/users")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"username\": \"alice_test\", \"display_name\": \"Alice\"}"))
|
||||
.andExpect(status().isCreated())
|
||||
.andReturn().getResponse().getContentAsString();
|
||||
String aliceId = extractId(aliceJson);
|
||||
|
||||
String bobJson = mockMvc.perform(post("/api/v1/users")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"username\": \"bob_test\", \"display_name\": \"Bob\"}"))
|
||||
.andExpect(status().isCreated())
|
||||
.andReturn().getResponse().getContentAsString();
|
||||
String bobId = extractId(bobJson);
|
||||
|
||||
String spyJson = mockMvc.perform(post("/api/v1/users")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"username\": \"spy_test\", \"display_name\": \"Spy\"}"))
|
||||
.andExpect(status().isCreated())
|
||||
.andReturn().getResponse().getContentAsString();
|
||||
String spyId = extractId(spyJson);
|
||||
|
||||
String chatJson = String.format(
|
||||
"{\"title\":\"Private\", \"member_ids\":[\"%s\",\"%s\"]}", aliceId, bobId);
|
||||
|
||||
String chat = mockMvc.perform(post("/api/v1/chats")
|
||||
.header("X-User-Id", aliceId) // ← обязательно!
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(chatJson))
|
||||
.andExpect(status().isCreated())
|
||||
.andReturn().getResponse().getContentAsString();
|
||||
String chatId = extractId(chat);
|
||||
|
||||
mockMvc.perform(post("/api/v1/chats/" + chatId + "/messages")
|
||||
.header("X-User-Id", spyId)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"text\": \"Secret message\"}"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("200 4. Пагинация: получение ограниченного числа сообщений по limit")
|
||||
void shouldPaginateMessagesWithLimit() throws Exception {
|
||||
String userJson = mockMvc.perform(post("/api/v1/users")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"username\": \"paginator\", \"display_name\": \"Paginator\"}"))
|
||||
.andExpect(status().isCreated())
|
||||
.andReturn().getResponse().getContentAsString();
|
||||
String userId = extractId(userJson);
|
||||
|
||||
String chat = mockMvc.perform(post("/api/v1/chats")
|
||||
.header("X-User-Id", userId)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(String.format(
|
||||
"{\"title\":\"Paginated Chat\", \"member_ids\":[\"%s\"]}", userId)))
|
||||
.andExpect(status().isCreated())
|
||||
.andReturn().getResponse().getContentAsString();
|
||||
String chatId = extractId(chat);
|
||||
|
||||
for (int i = 1; i <= 3; i++) {
|
||||
mockMvc.perform(post("/api/v1/chats/" + chatId + "/messages")
|
||||
.header("X-User-Id", userId)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"text\": \"Msg " + i + "\"}"))
|
||||
.andExpect(status().isCreated());
|
||||
}
|
||||
mockMvc.perform(get("/api/v1/chats/" + chatId + "/messages")
|
||||
.param("limit", "2")
|
||||
.header("X-User-Id", userId))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.items.length()").value(2))
|
||||
.andExpect(jsonPath("$.next_cursor").isNotEmpty());
|
||||
}
|
||||
|
||||
private String extractId(String json) {
|
||||
return json.split("\"id\":\"")[1].split("\"")[0];
|
||||
}
|
||||
}
|
||||
//package org.example;
|
||||
//
|
||||
//import org.junit.jupiter.api.DisplayName;
|
||||
//import org.junit.jupiter.api.Test;
|
||||
//import org.springframework.beans.factory.annotation.Autowired;
|
||||
//import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
//import org.springframework.boot.test.context.SpringBootTest;
|
||||
//import org.springframework.http.MediaType;
|
||||
//import org.springframework.test.web.servlet.MockMvc;
|
||||
//
|
||||
//import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
//import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
//
|
||||
//@SpringBootTest
|
||||
//@AutoConfigureMockMvc
|
||||
//public class ApiIntegrationTest {
|
||||
//
|
||||
// @Autowired
|
||||
// private MockMvc mockMvc;
|
||||
// @Test
|
||||
// @DisplayName("400 1. Неверный / битый JSON должен возвращать 400 Bad Request")
|
||||
// void shouldReturn400ForMalformedJson() throws Exception {
|
||||
// String malformedJson = "{\"username\": \"bad_json\", \"display_name\":}";
|
||||
//
|
||||
// mockMvc.perform(post("/api/v1/users")
|
||||
// .contentType(MediaType.APPLICATION_JSON)
|
||||
// .content(malformedJson))
|
||||
// .andExpect(status().isBadRequest());
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// @DisplayName("400 2. Валидация: пустой username должен возвращать 400 Bad Request")
|
||||
// void shouldReturn400ForEmptyUsername() throws Exception {
|
||||
// String invalidJson = "{\"username\": \"\", \"display_name\": \"User\"}";
|
||||
//
|
||||
// mockMvc.perform(post("/api/v1/users")
|
||||
// .contentType(MediaType.APPLICATION_JSON)
|
||||
// .content(invalidJson))
|
||||
// .andExpect(status().isBadRequest());
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// @DisplayName("404 3. Неучастник чата получает 404 (чат скрыт)")
|
||||
// void shouldReturn404WhenUserIsNotChatMember() throws Exception {
|
||||
// String aliceJson = mockMvc.perform(post("/api/v1/users")
|
||||
// .contentType(MediaType.APPLICATION_JSON)
|
||||
// .content("{\"username\": \"alice_test\", \"display_name\": \"Alice\"}"))
|
||||
// .andExpect(status().isCreated())
|
||||
// .andReturn().getResponse().getContentAsString();
|
||||
// String aliceId = extractId(aliceJson);
|
||||
//
|
||||
// String bobJson = mockMvc.perform(post("/api/v1/users")
|
||||
// .contentType(MediaType.APPLICATION_JSON)
|
||||
// .content("{\"username\": \"bob_test\", \"display_name\": \"Bob\"}"))
|
||||
// .andExpect(status().isCreated())
|
||||
// .andReturn().getResponse().getContentAsString();
|
||||
// String bobId = extractId(bobJson);
|
||||
//
|
||||
// String spyJson = mockMvc.perform(post("/api/v1/users")
|
||||
// .contentType(MediaType.APPLICATION_JSON)
|
||||
// .content("{\"username\": \"spy_test\", \"display_name\": \"Spy\"}"))
|
||||
// .andExpect(status().isCreated())
|
||||
// .andReturn().getResponse().getContentAsString();
|
||||
// String spyId = extractId(spyJson);
|
||||
//
|
||||
// String chatJson = String.format(
|
||||
// "{\"title\":\"Private\", \"member_ids\":[\"%s\",\"%s\"]}", aliceId, bobId);
|
||||
//
|
||||
// String chat = mockMvc.perform(post("/api/v1/chats")
|
||||
// .header("X-User-Id", aliceId) // ← обязательно!
|
||||
// .contentType(MediaType.APPLICATION_JSON)
|
||||
// .content(chatJson))
|
||||
// .andExpect(status().isCreated())
|
||||
// .andReturn().getResponse().getContentAsString();
|
||||
// String chatId = extractId(chat);
|
||||
//
|
||||
// mockMvc.perform(post("/api/v1/chats/" + chatId + "/messages")
|
||||
// .header("X-User-Id", spyId)
|
||||
// .contentType(MediaType.APPLICATION_JSON)
|
||||
// .content("{\"text\": \"Secret message\"}"))
|
||||
// .andExpect(status().isNotFound());
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// @DisplayName("200 4. Пагинация: получение ограниченного числа сообщений по limit")
|
||||
// void shouldPaginateMessagesWithLimit() throws Exception {
|
||||
// String userJson = mockMvc.perform(post("/api/v1/users")
|
||||
// .contentType(MediaType.APPLICATION_JSON)
|
||||
// .content("{\"username\": \"paginator\", \"display_name\": \"Paginator\"}"))
|
||||
// .andExpect(status().isCreated())
|
||||
// .andReturn().getResponse().getContentAsString();
|
||||
// String userId = extractId(userJson);
|
||||
//
|
||||
// String chat = mockMvc.perform(post("/api/v1/chats")
|
||||
// .header("X-User-Id", userId)
|
||||
// .contentType(MediaType.APPLICATION_JSON)
|
||||
// .content(String.format(
|
||||
// "{\"title\":\"Paginated Chat\", \"member_ids\":[\"%s\"]}", userId)))
|
||||
// .andExpect(status().isCreated())
|
||||
// .andReturn().getResponse().getContentAsString();
|
||||
// String chatId = extractId(chat);
|
||||
//
|
||||
// for (int i = 1; i <= 3; i++) {
|
||||
// mockMvc.perform(post("/api/v1/chats/" + chatId + "/messages")
|
||||
// .header("X-User-Id", userId)
|
||||
// .contentType(MediaType.APPLICATION_JSON)
|
||||
// .content("{\"text\": \"Msg " + i + "\"}"))
|
||||
// .andExpect(status().isCreated());
|
||||
// }
|
||||
// mockMvc.perform(get("/api/v1/chats/" + chatId + "/messages")
|
||||
// .param("limit", "2")
|
||||
// .header("X-User-Id", userId))
|
||||
// .andExpect(status().isOk())
|
||||
// .andExpect(jsonPath("$.items.length()").value(2))
|
||||
// .andExpect(jsonPath("$.next_cursor").isNotEmpty());
|
||||
// }
|
||||
//
|
||||
// private String extractId(String json) {
|
||||
// return json.split("\"id\":\"")[1].split("\"")[0];
|
||||
// }
|
||||
//}
|
||||
Reference in New Issue
Block a user