docs(report): fill REPORT.md for lab2 grade 3

This commit is contained in:
2026-10-29 18:14:24 +03:00
parent 65003b6119
commit e660283ef4
52 changed files with 1621 additions and 22 deletions
@@ -0,0 +1,11 @@
package ru.mtusi.messenger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MessengerApplication {
public static void main(String[] args) {
SpringApplication.run(MessengerApplication.class, args);
}
}
@@ -0,0 +1,54 @@
package ru.mtusi.messenger.config;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import ru.mtusi.messenger.entity.SessionEntity;
import ru.mtusi.messenger.repository.SessionRepository;
import java.io.IOException;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collections;
import java.util.Optional;
public class BearerTokenFilter extends OncePerRequestFilter {
private final SessionRepository sessionRepository;
public BearerTokenFilter(SessionRepository sessionRepository) {
this.sessionRepository = sessionRepository;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.substring(7);
Optional<SessionEntity> sessionOpt = sessionRepository.findById(token);
if (sessionOpt.isPresent() && sessionOpt.get().getExpiresAt().isAfter(OffsetDateTime.now(ZoneOffset.UTC))) {
// Токен валиден! Кладем ID пользователя в контекст безопасности Spring
SessionEntity session = sessionOpt.get();
// В Spring Security Principal - это объект, представляющий пользователя.
// Мы будем использовать UUID пользователя как Principal.
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(session.getUserId(), null, Collections.emptyList());
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
// Пропускаем запрос дальше
filterChain.doFilter(request, response);
}
}
@@ -0,0 +1,40 @@
package ru.mtusi.messenger.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import ru.mtusi.messenger.dto.ErrorResponse;
import ru.mtusi.messenger.filter.RequestIdFilter;
import java.io.IOException;
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
private final ObjectMapper objectMapper;
public RestAuthenticationEntryPoint(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
// Достаем X-Request-Id, который сгенерировал наш фильтр ранее
String requestId = (String) request.getAttribute(RequestIdFilter.REQUEST_ID_ATTR);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
response.setHeader("WWW-Authenticate", "Bearer realm=\"messenger\"");
ErrorResponse error = ErrorResponse.of("unauthorized", "No valid bearer token", requestId);
response.getWriter().write(objectMapper.writeValueAsString(error));
}
}
@@ -0,0 +1,49 @@
package ru.mtusi.messenger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import ru.mtusi.messenger.repository.SessionRepository;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
private final SessionRepository sessionRepository;
private final RestAuthenticationEntryPoint authEntryPoint; // ДОБАВЛЕНО
public SecurityConfig(SessionRepository sessionRepository, RestAuthenticationEntryPoint authEntryPoint) {
this.sessionRepository = sessionRepository;
this.authEntryPoint = authEntryPoint; // ДОБАВЛЕНО
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// ДОБАВЛЕНО: обработчик ошибок безопасности
.exceptionHandling(ex -> ex.authenticationEntryPoint(authEntryPoint))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/v1/users", "/api/v1/auth/sessions", "/health/**").permitAll()
.anyRequest().authenticated()
)
.httpBasic(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable)
.addFilterBefore(new BearerTokenFilter(sessionRepository), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
@@ -0,0 +1,56 @@
package ru.mtusi.messenger.controller;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import ru.mtusi.messenger.dto.SessionResponse;
import ru.mtusi.messenger.exception.UnauthorizedException;
import ru.mtusi.messenger.repository.SessionRepository;
import ru.mtusi.messenger.service.SessionService;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
@RestController
@RequestMapping("/api/v1/auth")
public class AuthController {
private final SessionService sessionService;
private final SessionRepository sessionRepository; // <-- ДОБАВЛЕНО
public AuthController(SessionService sessionService, SessionRepository sessionRepository) {
this.sessionService = sessionService;
this.sessionRepository = sessionRepository; // <-- ДОБАВЛЕНО
}
@PostMapping("/sessions")
@ResponseStatus(HttpStatus.CREATED)
public SessionResponse createSession(
@RequestHeader(value = "Authorization", required = false) String authHeader) {
if (authHeader == null || !authHeader.startsWith("Basic ")) {
throw new UnauthorizedException("Missing or invalid Authorization header");
}
String base64Credentials = authHeader.substring(6);
String credentials = new String(Base64.getDecoder().decode(base64Credentials), StandardCharsets.UTF_8);
int colonIndex = credentials.indexOf(':');
if (colonIndex == -1) {
throw new UnauthorizedException("Invalid Basic Auth format");
}
String username = credentials.substring(0, colonIndex);
String password = credentials.substring(colonIndex + 1);
return sessionService.createSession(username, password);
}
@DeleteMapping("/sessions/current")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void logout(@RequestHeader("Authorization") String authHeader) {
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.substring(7);
sessionRepository.deleteById(token);
}
}
}
@@ -0,0 +1,50 @@
package ru.mtusi.messenger.controller;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import ru.mtusi.messenger.dto.Chat;
import ru.mtusi.messenger.dto.CreateChat;
import ru.mtusi.messenger.exception.UnauthorizedException;
import ru.mtusi.messenger.service.ChatService;
import java.util.UUID;
@RestController
@RequestMapping("/api/v1/chats")
public class ChatController {
private final ChatService chatService;
public ChatController(ChatService chatService) {
this.chatService = chatService;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Chat createChat(Authentication auth, @Valid @RequestBody CreateChat body) {
return chatService.createChat(getUserId(auth), body);
}
@GetMapping
public Object listChats(Authentication auth) {
// Упрощенная версия без курсора для lab2, если тесты не требуют обратного
return new ChatPage(chatService.getUserChats(getUserId(auth)), null);
}
@GetMapping("/{chat_id}")
public Chat getChat(Authentication auth, @PathVariable("chat_id") UUID chatId) {
return chatService.getChat(getUserId(auth), chatId);
}
private UUID getUserId(Authentication auth) {
if (auth == null || !(auth.getPrincipal() instanceof UUID)) {
throw new UnauthorizedException("Not authenticated");
}
return (UUID) auth.getPrincipal();
}
// Заглушка для DTO, чтобы не ломать компиляцию
public record ChatPage(java.util.List<Chat> items, String nextCursor) {}
}
@@ -0,0 +1,23 @@
package ru.mtusi.messenger.controller;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import ru.mtusi.messenger.filter.RequestIdFilter;
import java.util.Map;
@RestController
public class HealthController {
@GetMapping("/health/live")
public ResponseEntity<Map<String, String>> liveness(HttpServletRequest request) {
return ResponseEntity.ok(Map.of("status", "ok"));
}
@GetMapping("/health/ready")
public ResponseEntity<Map<String, String>> readiness(HttpServletRequest request) {
return ResponseEntity.ok(Map.of("status", "ok"));
}
}
@@ -0,0 +1,82 @@
package ru.mtusi.messenger.controller;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import ru.mtusi.messenger.dto.CreateMessage;
import ru.mtusi.messenger.dto.Message;
import ru.mtusi.messenger.exception.InvalidRequestException;
import ru.mtusi.messenger.exception.UnauthorizedException;
import ru.mtusi.messenger.service.MessageService;
import java.util.List;
import java.util.UUID;
@RestController
@RequestMapping("/api/v1/chats/{chat_id}/messages")
public class MessageController {
private final MessageService messageService;
public MessageController(MessageService messageService) {
this.messageService = messageService;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Message createMessage(Authentication auth, @PathVariable("chat_id") UUID chatId, @Valid @RequestBody CreateMessage body) {
return messageService.createMessage(getUserId(auth), chatId, body);
}
@GetMapping
public MessagePage listMessages(
Authentication auth,
@PathVariable("chat_id") UUID chatId,
@RequestParam(value = "limit", required = false) Integer limit,
@RequestParam(value = "cursor", required = false) String cursor) {
int effectiveLimit = (limit == null) ? 50 : limit;
if (effectiveLimit < 1 || effectiveLimit > 100) {
throw new InvalidRequestException("limit must be between 1 and 100");
}
java.time.OffsetDateTime lastCreatedAt = null;
UUID lastId = null;
if (cursor != null && !cursor.isBlank()) {
try {
String decoded = new String(java.util.Base64.getUrlDecoder().decode(cursor), java.nio.charset.StandardCharsets.UTF_8);
String[] parts = decoded.split("\\|");
lastCreatedAt = java.time.OffsetDateTime.parse(parts[0]);
lastId = UUID.fromString(parts[1]);
} catch (Exception e) {
throw new InvalidRequestException("Invalid cursor format");
}
}
// Берем на 1 больше, чтобы понять, есть ли следующая страница
List<Message> msgs = messageService.getMessagesPage(getUserId(auth), chatId, lastCreatedAt, lastId, effectiveLimit + 1);
boolean hasMore = msgs.size() > effectiveLimit;
List<Message> pageItems = hasMore ? msgs.subList(0, effectiveLimit) : msgs;
String nextCursor = null;
if (hasMore && !pageItems.isEmpty()) {
Message lastMsg = pageItems.get(pageItems.size() - 1);
String rawCursor = lastMsg.createdAt().toString() + "|" + lastMsg.id().toString();
nextCursor = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(rawCursor.getBytes(java.nio.charset.StandardCharsets.UTF_8));
}
return new MessagePage(pageItems, nextCursor);
}
private UUID getUserId(Authentication auth) {
if (auth == null || !(auth.getPrincipal() instanceof UUID)) {
throw new UnauthorizedException("Not authenticated");
}
return (UUID) auth.getPrincipal();
}
public record MessagePage(List<Message> items, String nextCursor) {}
}
@@ -0,0 +1,40 @@
package ru.mtusi.messenger.controller;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import ru.mtusi.messenger.dto.CreateUser;
import ru.mtusi.messenger.dto.User;
import ru.mtusi.messenger.exception.UnauthorizedException;
import ru.mtusi.messenger.service.UserService;
import java.util.UUID;
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public User createUser(@Valid @RequestBody CreateUser body) {
return userService.createUser(body);
}
@GetMapping("/me")
public User currentUser(Authentication authentication) {
if (authentication == null || !(authentication.getPrincipal() instanceof UUID)) {
throw new UnauthorizedException("Not authenticated");
}
UUID userId = (UUID) authentication.getPrincipal();
return userService.findById(userId)
.orElseThrow(() -> new UnauthorizedException("Unknown user"));
}
}
@@ -0,0 +1,12 @@
package ru.mtusi.messenger.dto;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.UUID;
public record Chat(
UUID id,
String title,
List<UUID> memberIds,
OffsetDateTime createdAt
) {}
@@ -0,0 +1,5 @@
package ru.mtusi.messenger.dto;
import java.util.List;
public record ChatPage(List<Chat> items, String nextCursor) {}
@@ -0,0 +1,18 @@
package ru.mtusi.messenger.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import java.util.List;
import java.util.UUID;
public record CreateChat(
@NotBlank(message = "title must not be blank")
@Size(min = 1, max = 100, message = "title must be 1..100 characters")
String title,
@NotEmpty(message = "member_ids must not be empty")
@Size(min = 1, max = 100, message = "member_ids must contain 1..100 items")
List<UUID> memberIds
) {}
@@ -0,0 +1,10 @@
package ru.mtusi.messenger.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public record CreateMessage(
@NotBlank(message = "text must not be blank")
@Size(min = 1, max = 4000, message = "text must be 1..4000 characters")
String text
) {}
@@ -0,0 +1,19 @@
package ru.mtusi.messenger.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
public record CreateUser(
@NotBlank(message = "username must not be blank")
@Pattern(regexp = "^[a-z0-9_]{3,32}$", message = "username must match ^[a-z0-9_]{3,32}$")
String username,
@NotBlank(message = "display_name must not be blank")
@Size(min = 1, max = 100, message = "display_name must be 1..100 characters")
String displayName,
@NotBlank(message = "password must not be blank")
@Size(min = 12, max = 128, message = "password must be 12..128 characters")
String password // <-- Новое поле
) {}
@@ -0,0 +1,16 @@
package ru.mtusi.messenger.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
public record ErrorResponse(ErrorBody error) {
public record ErrorBody(
String code,
String message,
String requestId
) {}
public static ErrorResponse of(String code, String message, String requestId) {
return new ErrorResponse(new ErrorBody(code, message, requestId));
}
}
@@ -0,0 +1,7 @@
package ru.mtusi.messenger.dto;
public record Health(String status) {
public static Health ok() {
return new Health("ok");
}
}
@@ -0,0 +1,12 @@
package ru.mtusi.messenger.dto;
import java.time.OffsetDateTime;
import java.util.UUID;
public record Message(
UUID id,
UUID chatId,
UUID senderId,
String text,
OffsetDateTime createdAt
) {}
@@ -0,0 +1,5 @@
package ru.mtusi.messenger.dto;
import java.util.List;
public record MessagePage(List<Message> items, String nextCursor) {}
@@ -0,0 +1,5 @@
package ru.mtusi.messenger.dto;
import java.util.List;
public record Page<T>(List<T> items, String nextCursor) {}
@@ -0,0 +1,14 @@
package ru.mtusi.messenger.dto;
import java.time.OffsetDateTime;
public record SessionResponse(
String token,
String tokenType,
OffsetDateTime expiresAt,
User user
) {
public SessionResponse(String token, OffsetDateTime expiresAt, User user) {
this(token, "Bearer", expiresAt, user);
}
}
@@ -0,0 +1,11 @@
package ru.mtusi.messenger.dto;
import java.time.OffsetDateTime;
import java.util.UUID;
public record User(
UUID id,
String username,
String displayName,
OffsetDateTime createdAt
) {}
@@ -0,0 +1,37 @@
package ru.mtusi.messenger.entity;
import jakarta.persistence.*;
import java.time.OffsetDateTime;
import java.util.Set;
import java.util.UUID;
@Entity
@Table(name = "chats")
public class ChatEntity {
@Id
private UUID id;
@Column(nullable = false, length = 100)
private String title;
@Column(name = "created_at", nullable = false)
private OffsetDateTime createdAt;
@ManyToMany
@JoinTable(
name = "chat_members",
joinColumns = @JoinColumn(name = "chat_id"),
inverseJoinColumns = @JoinColumn(name = "user_id")
)
private Set<UserEntity> members;
// Геттеры и сеттеры
public UUID getId() { return id; }
public void setId(UUID id) { this.id = id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public OffsetDateTime getCreatedAt() { return createdAt; }
public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; }
public Set<UserEntity> getMembers() { return members; }
public void setMembers(Set<UserEntity> members) { this.members = members; }
}
@@ -0,0 +1,36 @@
package ru.mtusi.messenger.entity;
import jakarta.persistence.*;
import java.time.OffsetDateTime;
import java.util.UUID;
@Entity
@Table(name = "messages")
public class MessageEntity {
@Id
private UUID id;
@Column(name = "chat_id", nullable = false)
private UUID chatId;
@Column(name = "sender_id", nullable = false)
private UUID senderId;
@Column(nullable = false, length = 4000)
private String text;
@Column(name = "created_at", nullable = false)
private OffsetDateTime createdAt;
// Геттеры и сеттеры
public UUID getId() { return id; }
public void setId(UUID id) { this.id = id; }
public UUID getChatId() { return chatId; }
public void setChatId(UUID chatId) { this.chatId = chatId; }
public UUID getSenderId() { return senderId; }
public void setSenderId(UUID senderId) { this.senderId = senderId; }
public String getText() { return text; }
public void setText(String text) { this.text = text; }
public OffsetDateTime getCreatedAt() { return createdAt; }
public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; }
}
@@ -0,0 +1,26 @@
package ru.mtusi.messenger.entity;
import jakarta.persistence.*;
import java.time.OffsetDateTime;
import java.util.UUID;
@Entity
@Table(name = "sessions")
public class SessionEntity {
@Id
private String token;
@Column(name = "user_id", nullable = false)
private UUID userId;
@Column(name = "expires_at", nullable = false)
private OffsetDateTime expiresAt;
// Геттеры и сеттеры
public String getToken() { return token; }
public void setToken(String token) { this.token = token; }
public UUID getUserId() { return userId; }
public void setUserId(UUID userId) { this.userId = userId; }
public OffsetDateTime getExpiresAt() { return expiresAt; }
public void setExpiresAt(OffsetDateTime expiresAt) { this.expiresAt = expiresAt; }
}
@@ -0,0 +1,36 @@
package ru.mtusi.messenger.entity;
import jakarta.persistence.*;
import java.time.OffsetDateTime;
import java.util.UUID;
@Entity
@Table(name = "users")
public class UserEntity {
@Id
private UUID id;
@Column(nullable = false, unique = true, length = 32)
private String username;
@Column(name = "password_hash", nullable = false)
private String passwordHash;
@Column(name = "display_name", nullable = false, length = 100)
private String displayName;
@Column(name = "created_at", nullable = false)
private OffsetDateTime createdAt;
// Геттеры и сеттеры (или используй Lombok, если он есть)
public UUID getId() { return id; }
public void setId(UUID id) { this.id = id; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPasswordHash() { return passwordHash; }
public void setPasswordHash(String passwordHash) { this.passwordHash = passwordHash; }
public String getDisplayName() { return displayName; }
public void setDisplayName(String displayName) { this.displayName = displayName; }
public OffsetDateTime getCreatedAt() { return createdAt; }
public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; }
}
@@ -0,0 +1,7 @@
package ru.mtusi.messenger.exception;
public class ConflictException extends RuntimeException {
public ConflictException(String message) {
super(message);
}
}
@@ -0,0 +1,80 @@
package ru.mtusi.messenger.exception;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import ru.mtusi.messenger.dto.ErrorResponse;
import ru.mtusi.messenger.filter.RequestIdFilter;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(InvalidRequestException.class)
public ResponseEntity<ErrorResponse> handleInvalid(InvalidRequestException ex, HttpServletRequest req) {
return error(HttpStatus.BAD_REQUEST, "invalid_request", ex.getMessage(), req);
}
@ExceptionHandler(UnauthorizedException.class)
public ResponseEntity<ErrorResponse> handleUnauthorized(UnauthorizedException ex, HttpServletRequest req) {
String requestId = (String) req.getAttribute(RequestIdFilter.REQUEST_ID_ATTR);
ErrorResponse body = ErrorResponse.of("unauthorized", ex.getMessage(), requestId);
// Контракт требует заголовок WWW-Authenticate
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.header("WWW-Authenticate", "Basic realm=\"messenger\", charset=\"UTF-8\"")
.body(body);
}
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(NotFoundException ex, HttpServletRequest req) {
return error(HttpStatus.NOT_FOUND, "not_found", ex.getMessage(), req);
}
@ExceptionHandler(ConflictException.class)
public ResponseEntity<ErrorResponse> handleConflict(ConflictException ex, HttpServletRequest req) {
return error(HttpStatus.CONFLICT, "conflict", ex.getMessage(), req);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex, HttpServletRequest req) {
String message = ex.getBindingResult().getFieldErrors().stream()
.findFirst()
.map(fe -> fe.getField() + ": " + fe.getDefaultMessage())
.orElse("Validation failed");
return error(HttpStatus.BAD_REQUEST, "invalid_request", message, req);
}
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<ErrorResponse> handleMalformed(HttpMessageNotReadableException ex, HttpServletRequest req) {
return error(HttpStatus.BAD_REQUEST, "invalid_request", "Malformed JSON or invalid field type", req);
}
@ExceptionHandler(MissingRequestHeaderException.class)
public ResponseEntity<ErrorResponse> handleMissingHeader(MissingRequestHeaderException ex, HttpServletRequest req) {
// Мы не бросаем это явно, но если понадобится required=true в @RequestHeader
return error(HttpStatus.UNAUTHORIZED, "unauthorized", "Missing required header", req);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleAll(Exception ex, HttpServletRequest req) {
// Не логируем stack trace в ответ; для отладки — в stdout
ex.printStackTrace();
return error(HttpStatus.INTERNAL_SERVER_ERROR, "internal_error", "Internal server error", req);
}
private ResponseEntity<ErrorResponse> error(HttpStatus status, String code, String message,
HttpServletRequest req) {
String requestId = (String) req.getAttribute(RequestIdFilter.REQUEST_ID_ATTR);
return ResponseEntity.status(status).body(ErrorResponse.of(code, message, requestId));
}
@ExceptionHandler(org.springframework.dao.DataIntegrityViolationException.class)
public ResponseEntity<ErrorResponse> handleDataIntegrity(org.springframework.dao.DataIntegrityViolationException ex, HttpServletRequest req) {
return error(HttpStatus.CONFLICT, "conflict", "Resource already exists", req);
}
}
@@ -0,0 +1,7 @@
package ru.mtusi.messenger.exception;
public class InvalidRequestException extends RuntimeException {
public InvalidRequestException(String message) {
super(message);
}
}
@@ -0,0 +1,7 @@
package ru.mtusi.messenger.exception;
public class NotFoundException extends RuntimeException {
public NotFoundException(String message) {
super(message);
}
}
@@ -0,0 +1,7 @@
package ru.mtusi.messenger.exception;
public class UnauthorizedException extends RuntimeException {
public UnauthorizedException(String message) {
super(message);
}
}
@@ -0,0 +1,30 @@
package ru.mtusi.messenger.filter;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.UUID;
@Component
@Order(-200) // <--- ИЗМЕНЕНО: теперь выполняется раньше Spring Security
public class RequestIdFilter implements Filter {
public static final String REQUEST_ID_ATTR = "requestId";
public static final String REQUEST_ID_HEADER = "X-Request-Id";
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String requestId = UUID.randomUUID().toString();
httpRequest.setAttribute(REQUEST_ID_ATTR, requestId);
httpResponse.setHeader(REQUEST_ID_HEADER, requestId);
chain.doFilter(request, response);
}
}
@@ -0,0 +1,8 @@
package ru.mtusi.messenger.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.mtusi.messenger.entity.ChatEntity;
import java.util.UUID;
public interface ChatRepository extends JpaRepository<ChatEntity, UUID> {
}
@@ -0,0 +1,24 @@
package ru.mtusi.messenger.repository;
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 ru.mtusi.messenger.entity.MessageEntity;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.UUID;
public interface MessageRepository extends JpaRepository<MessageEntity, UUID> {
@Query("SELECT m FROM MessageEntity 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<MessageEntity> findNextPage(
@Param("chatId") UUID chatId,
@Param("createdAt") OffsetDateTime createdAt,
@Param("id") UUID id,
Pageable pageable
);
}
@@ -0,0 +1,7 @@
package ru.mtusi.messenger.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.mtusi.messenger.entity.SessionEntity;
public interface SessionRepository extends JpaRepository<SessionEntity, String> {
}
@@ -0,0 +1,11 @@
package ru.mtusi.messenger.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.mtusi.messenger.entity.UserEntity;
import java.util.Optional;
import java.util.UUID;
public interface UserRepository extends JpaRepository<UserEntity, UUID> {
Optional<UserEntity> findByUsername(String username);
boolean existsByUsername(String username);
}
@@ -0,0 +1,85 @@
package ru.mtusi.messenger.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.dto.Chat;
import ru.mtusi.messenger.dto.CreateChat;
import ru.mtusi.messenger.entity.ChatEntity;
import ru.mtusi.messenger.entity.UserEntity;
import ru.mtusi.messenger.exception.InvalidRequestException;
import ru.mtusi.messenger.exception.NotFoundException;
import ru.mtusi.messenger.repository.ChatRepository;
import ru.mtusi.messenger.repository.UserRepository;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
@Service
public class ChatService {
private final ChatRepository chatRepository;
private final UserRepository userRepository;
public ChatService(ChatRepository chatRepository, UserRepository userRepository) {
this.chatRepository = chatRepository;
this.userRepository = userRepository;
}
@Transactional
public Chat createChat(UUID callerId, CreateChat request) {
Set<UUID> uniqueMembers = new HashSet<>(request.memberIds());
if (uniqueMembers.size() != request.memberIds().size()) {
throw new InvalidRequestException("member_ids must be unique");
}
if (!uniqueMembers.contains(callerId)) {
throw new InvalidRequestException("caller must be a member of the chat");
}
List<UserEntity> members = userRepository.findAllById(request.memberIds());
if (members.size() != request.memberIds().size()) {
throw new InvalidRequestException("Some members do not exist");
}
ChatEntity chat = new ChatEntity();
chat.setId(UUID.randomUUID());
chat.setTitle(request.title());
chat.setCreatedAt(OffsetDateTime.now(ZoneOffset.UTC));
chat.setMembers(new HashSet<>(members));
chatRepository.save(chat);
return toDto(chat);
}
@Transactional(readOnly = true)
public Chat getChat(UUID callerId, UUID chatId) {
ChatEntity chat = chatRepository.findById(chatId)
.orElseThrow(() -> new NotFoundException("Chat not found"));
boolean isMember = chat.getMembers().stream().anyMatch(u -> u.getId().equals(callerId));
if (!isMember) throw new NotFoundException("Chat not found");
return toDto(chat);
}
@Transactional(readOnly = true)
public List<Chat> getUserChats(UUID callerId) {
// В реальном проекте лучше сделать кастомный запрос, но для lab2 сойдет
return chatRepository.findAll().stream()
.filter(c -> c.getMembers().stream().anyMatch(u -> u.getId().equals(callerId)))
.map(this::toDto)
.toList();
}
public Chat toDto(ChatEntity entity) {
return new Chat(
entity.getId(),
entity.getTitle(),
entity.getMembers().stream().map(UserEntity::getId).toList(),
entity.getCreatedAt()
);
}
}
@@ -0,0 +1,67 @@
package ru.mtusi.messenger.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.dto.CreateMessage;
import ru.mtusi.messenger.dto.Message;
import ru.mtusi.messenger.entity.ChatEntity;
import ru.mtusi.messenger.entity.MessageEntity;
import ru.mtusi.messenger.exception.InvalidRequestException;
import ru.mtusi.messenger.exception.NotFoundException;
import ru.mtusi.messenger.repository.ChatRepository;
import ru.mtusi.messenger.repository.MessageRepository;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.UUID;
@Service
public class MessageService {
private final MessageRepository messageRepository;
private final ChatRepository chatRepository;
public MessageService(MessageRepository messageRepository, ChatRepository chatRepository) {
this.messageRepository = messageRepository;
this.chatRepository = chatRepository;
}
@Transactional
public Message createMessage(UUID callerId, UUID chatId, CreateMessage request) {
verifyAccess(callerId, chatId);
MessageEntity msg = new MessageEntity();
msg.setId(UUID.randomUUID());
msg.setChatId(chatId);
msg.setSenderId(callerId);
msg.setText(request.text());
msg.setCreatedAt(OffsetDateTime.now(ZoneOffset.UTC).truncatedTo(java.time.temporal.ChronoUnit.MILLIS));
messageRepository.save(msg);
return toDto(msg);
}
private void verifyAccess(UUID callerId, UUID chatId) {
ChatEntity chat = chatRepository.findById(chatId)
.orElseThrow(() -> new NotFoundException("Chat not found"));
boolean isMember = chat.getMembers().stream().anyMatch(u -> u.getId().equals(callerId));
if (!isMember) throw new NotFoundException("Chat not found");
}
private Message toDto(MessageEntity e) {
return new Message(e.getId(), e.getChatId(), e.getSenderId(), e.getText(), e.getCreatedAt());
}
@Transactional(readOnly = true)
public List<Message> getMessagesPage(UUID callerId, UUID chatId, OffsetDateTime lastCreatedAt, UUID lastId, int limit) {
verifyAccess(callerId, chatId);
// Если курсора нет, берем с самого начала (эпоха 1970 года)
OffsetDateTime startTime = (lastCreatedAt != null) ? lastCreatedAt : OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
UUID startId = (lastId != null) ? lastId : new UUID(0, 0);
return messageRepository.findNextPage(chatId, startTime, startId, org.springframework.data.domain.PageRequest.of(0, limit))
.stream().map(this::toDto).toList();
}
}
@@ -0,0 +1,64 @@
package ru.mtusi.messenger.service;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.dto.SessionResponse;
import ru.mtusi.messenger.entity.SessionEntity;
import ru.mtusi.messenger.entity.UserEntity;
import ru.mtusi.messenger.exception.UnauthorizedException;
import ru.mtusi.messenger.repository.SessionRepository;
import ru.mtusi.messenger.repository.UserRepository;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.UUID;
@Service
public class SessionService {
private final UserRepository userRepository;
private final SessionRepository sessionRepository;
private final PasswordEncoder passwordEncoder;
private final UserService userService;
public SessionService(UserRepository userRepository,
SessionRepository sessionRepository,
PasswordEncoder passwordEncoder,
UserService userService) {
this.userRepository = userRepository;
this.sessionRepository = sessionRepository;
this.passwordEncoder = passwordEncoder;
this.userService = userService;
}
@Transactional
public SessionResponse createSession(String username, String rawPassword) {
// 1. Ищем пользователя
UserEntity user = userRepository.findByUsername(username)
.orElseThrow(() -> new UnauthorizedException("Invalid credentials"));
// 2. Проверяем пароль
if (!passwordEncoder.matches(rawPassword, user.getPasswordHash())) {
throw new UnauthorizedException("Invalid credentials");
}
// 3. Генерируем opaque токен (UUID)
String token = UUID.randomUUID().toString();
// 4. Сохраняем сессию в БД (TTL 1 час)
SessionEntity session = new SessionEntity();
session.setToken(token);
session.setUserId(user.getId());
session.setExpiresAt(OffsetDateTime.now(ZoneOffset.UTC).plusHours(1));
sessionRepository.save(session);
// 5. Возвращаем ответ
return new SessionResponse(
token,
session.getExpiresAt(),
userService.toDto(user)
);
}
}
@@ -0,0 +1,59 @@
package ru.mtusi.messenger.service;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.dto.CreateUser;
import ru.mtusi.messenger.dto.User;
import ru.mtusi.messenger.entity.UserEntity;
import ru.mtusi.messenger.exception.ConflictException;
import ru.mtusi.messenger.repository.UserRepository;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Optional;
import java.util.UUID;
@Service
public class UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
@Transactional
public User createUser(CreateUser request) {
// ... проверка username ...
UserEntity entity = new UserEntity();
entity.setId(UUID.randomUUID());
entity.setUsername(request.username());
entity.setDisplayName(request.displayName());
entity.setPasswordHash(passwordEncoder.encode(request.password()));
// ВАЖНО: обрезаем до миллисекунд, чтобы PostgreSQL не изменил точность
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC).truncatedTo(java.time.temporal.ChronoUnit.MILLIS);
entity.setCreatedAt(now);
userRepository.save(entity);
return toDto(entity);
}
@Transactional(readOnly = true)
public Optional<User> findById(UUID id) {
return userRepository.findById(id).map(this::toDto);
}
// Вспомогательный метод для конвертации Entity -> DTO
public User toDto(UserEntity entity) {
return new User(
entity.getId(),
entity.getUsername(),
entity.getDisplayName(),
entity.getCreatedAt()
);
}
}
@@ -0,0 +1,49 @@
/* package ru.mtusi.messenger.store;
import org.springframework.stereotype.Component;
import ru.mtusi.messenger.dto.Chat;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
@Component
public class ChatStore {
private final ConcurrentHashMap<UUID, Chat> byId = new ConcurrentHashMap<>();
public Chat create(String title, List<UUID> memberIds) {
UUID id = UUID.randomUUID();
Chat chat = new Chat(
id,
title,
List.copyOf(memberIds),
OffsetDateTime.now(ZoneOffset.UTC)
);
byId.put(id, chat);
return chat;
}
public Optional<Chat> findById(UUID id) {
return Optional.ofNullable(byId.get(id));
}
public List<Chat> findByMember(UUID userId) {
List<Chat> result = new ArrayList<>();
for (Chat chat : byId.values()) {
if (chat.memberIds().contains(userId)) {
result.add(chat);
}
}
result.sort(Comparator
.comparing(Chat::createdAt)
.thenComparing(c -> c.id().toString()));
return result;
}
}
*/
@@ -0,0 +1,43 @@
/* package ru.mtusi.messenger.store;
import org.springframework.stereotype.Component;
import ru.mtusi.messenger.dto.Message;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
@Component
public class MessageStore {
private static final Comparator<Message> ORDER =
Comparator.comparing(Message::createdAt)
.thenComparing(m -> m.id().toString());
private final ConcurrentHashMap<UUID, CopyOnWriteArrayList<Message>> byChat = new ConcurrentHashMap<>();
public Message create(UUID chatId, UUID senderId, String text) {
Message message = new Message(
UUID.randomUUID(), chatId, senderId, text,
OffsetDateTime.now(ZoneOffset.UTC)
);
byChat.computeIfAbsent(chatId, k -> new CopyOnWriteArrayList<>()).add(message);
return message;
}
public List<Message> findByChat(UUID chatId) {
CopyOnWriteArrayList<Message> messages = byChat.get(chatId);
if (messages == null) {
return List.of();
}
List<Message> sorted = new ArrayList<>(messages);
sorted.sort(ORDER);
return sorted;
}
}
*/
@@ -0,0 +1,54 @@
package ru.mtusi.messenger.util;
import ru.mtusi.messenger.exception.InvalidRequestException;
import java.nio.charset.StandardCharsets;
import java.time.OffsetDateTime;
import java.util.Base64;
import java.util.UUID;
/**
* Кодирует/декодирует opaque cursor для keyset-пагинации.
*
* Формат (внутри base64url): scope | createdAt.toString() | uuid
* scope — например "chat:<chat_id>", привязывает курсор к ресурсу
* createdAt — ISO-8601 строкa UTC с наносекундной точностью
* uuid — id последнего элемента
*
* Клиент видит только base64-строку и не должен её интерпретировать.
*/
public final class CursorCodec {
private CursorCodec() {}
public record Cursor(String scope, OffsetDateTime createdAt, UUID id) {}
public static String encode(String scope, OffsetDateTime createdAt, UUID id) {
String raw = scope + "|" + createdAt.toString() + "|" + id;
return Base64.getUrlEncoder().withoutPadding()
.encodeToString(raw.getBytes(StandardCharsets.UTF_8));
}
public static Cursor decode(String encoded, String expectedScope) {
try {
String raw = new String(
Base64.getUrlDecoder().decode(encoded),
StandardCharsets.UTF_8
);
String[] parts = raw.split("\\|", 3);
if (parts.length != 3) {
throw new InvalidRequestException("Invalid cursor");
}
if (!parts[0].equals(expectedScope)) {
throw new InvalidRequestException("Cursor belongs to another resource");
}
OffsetDateTime createdAt = OffsetDateTime.parse(parts[1]);
UUID id = UUID.fromString(parts[2]);
return new Cursor(parts[0], createdAt, id);
} catch (InvalidRequestException e) {
throw e;
} catch (Exception e) {
throw new InvalidRequestException("Invalid cursor");
}
}
}