This commit is contained in:
2026-10-17 08:59:12 +03:00
parent 95aed3c25b
commit 7ffebe65d0
52 changed files with 1315 additions and 204 deletions
@@ -0,0 +1,26 @@
package ru.mtusi.messenger.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tools.jackson.databind.DeserializationFeature;
import tools.jackson.databind.cfg.CoercionAction;
import tools.jackson.databind.cfg.CoercionInputShape;
@Configuration
@Slf4j
public class JacksonConfig {
@Bean
public JsonMapperBuilderCustomizer strictJacksonCustomizer() {
log.warn(">>> Strict JsonMapper customizer applied");
return builder -> builder
.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.withCoercionConfigDefaults(config -> {
config.setCoercion(CoercionInputShape.Integer, CoercionAction.Fail);
config.setCoercion(CoercionInputShape.Float, CoercionAction.Fail);
});
}
}
@@ -16,7 +16,7 @@ public class AuthController implements AuthApi {
@Override
public ResponseEntity<SessionDTO> createSession(HttpServletRequest request) {
return ResponseEntity.status(HttpStatus.CREATED).body(authService.login(request.getHeader(HttpHeaders.AUTHORIZATION)));
return ResponseEntity.status(HttpStatus.CREATED).body(authService.login(request.getHeader(HttpHeaders.AUTHORIZATION), request.getContentLengthLong()));
}
@Override
@@ -7,6 +7,7 @@ import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.RestController;
import ru.mtusi.messenger.dto.ChatDTO;
import ru.mtusi.messenger.dto.ChatPageDTO;
import ru.mtusi.messenger.dto.CreateChatDTO;
import ru.mtusi.messenger.security.SessionPrincipal;
import ru.mtusi.messenger.service.ChatService;
@@ -18,9 +19,9 @@ public class ChatController implements ChatsApi {
private final ChatService chatService;
@Override
public ResponseEntity<ChatDTO> createChat(ChatDTO chatDTO, @AuthenticationPrincipal SessionPrincipal principal) {
public ResponseEntity<ChatDTO> createChat(CreateChatDTO createChatDTO, @AuthenticationPrincipal SessionPrincipal principal) {
return ResponseEntity.status(HttpStatus.CREATED)
.body(chatService.createChat(principal.userId(), chatDTO));
.body(chatService.createChat(principal.userId(), createChatDTO));
}
@Override
@@ -8,6 +8,7 @@ package ru.mtusi.messenger.controller;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import ru.mtusi.messenger.dto.ChatDTO;
import ru.mtusi.messenger.dto.ChatPageDTO;
import ru.mtusi.messenger.dto.CreateChatDTO;
import ru.mtusi.messenger.dto.ErrorDTO;
import java.util.UUID;
@@ -37,7 +38,7 @@ public interface ChatsApi {
/**
* POST /api/v1/chats : Создать чат; вызывающий должен входить в member_ids
*
* @param chatDTO (required)
* @param createChatDTO (required)
* @return Успех (status code 201)
* or Неверный запрос (status code 400)
* or Нет действительной аутентификации (status code 401)
@@ -89,7 +90,7 @@ public interface ChatsApi {
)
ResponseEntity<ChatDTO> createChat(
@Parameter(name = "CreateChatDTO", description = "", required = true) @Valid @RequestBody ChatDTO chatDTO, @AuthenticationPrincipal SessionPrincipal principal
@Parameter(name = "CreateChatDTO", description = "", required = true) @Valid @RequestBody CreateChatDTO createChatDTO, @AuthenticationPrincipal SessionPrincipal principal
);
@@ -5,6 +5,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.RestController;
import ru.mtusi.messenger.dto.CreateUserDTO;
import ru.mtusi.messenger.dto.UserDTO;
import ru.mtusi.messenger.security.SessionPrincipal;
import ru.mtusi.messenger.service.UserService;
@@ -20,7 +21,7 @@ public class UserController implements UsersApi {
}
@Override
public ResponseEntity<UserDTO> registerUser(UserDTO userDTO) {
return ResponseEntity.status(HttpStatus.CREATED).body(userService.registerUser(userDTO));
public ResponseEntity<UserDTO> registerUser(CreateUserDTO createUserDTO) {
return ResponseEntity.status(HttpStatus.CREATED).body(userService.registerUser(createUserDTO));
}
}
@@ -6,6 +6,7 @@
package ru.mtusi.messenger.controller;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import ru.mtusi.messenger.dto.CreateUserDTO;
import ru.mtusi.messenger.dto.ErrorDTO;
import ru.mtusi.messenger.dto.UserDTO;
import io.swagger.v3.oas.annotations.Operation;
@@ -89,7 +90,7 @@ public interface UsersApi {
/**
* POST /api/v1/users : Создать пользователя
*
* @param userDTO (required)
* @param createUserDTO (required)
* @return Успех (status code 201)
* or Неверный запрос (status code 400)
* or Конфликт (status code 409)
@@ -130,7 +131,7 @@ public interface UsersApi {
)
ResponseEntity<UserDTO> registerUser(
@Parameter(name = "UserDTO", description = "", required = true) @Valid @RequestBody UserDTO userDTO
@Parameter(name = "CreateUserDTO", description = "", required = true) @Valid @RequestBody CreateUserDTO createUserDTO
);
}
@@ -36,10 +36,12 @@ public class GlobalExceptionHandler {
@ExceptionHandler(UnauthorizedException.class)
public ResponseEntity<ErrorDTO> unauthorized(UnauthorizedException e, HttpServletRequest req) {
String scheme = req.getRequestURI().equals("/api/v1/auth/sessions")
? "Basic" : "Bearer";
boolean isLogin = "/api/v1/auth/sessions".equals(req.getRequestURI());
String challenge = isLogin
? "Basic realm=\"messenger\", charset=\"UTF-8\""
: "Bearer realm=\"messenger\"";
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.header("WWW-Authenticate", scheme + " realm=\"messenger\"")
.header("WWW-Authenticate", challenge)
.body(errors.error(ErrorErrorDTO.CodeEnum.UNAUTHORIZED, e.getMessage(), req));
}
@@ -0,0 +1,101 @@
package ru.mtusi.messenger.dto;
import java.util.Objects;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Generated;
import org.hibernate.validator.constraints.CodePointLength;
@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0")
public class CreateChatDTO {
private String title;
@Valid
private List<UUID> memberIds = new ArrayList<>();
public CreateChatDTO() {
super();
}
public CreateChatDTO(String title, List<UUID> memberIds) {
this.title = title;
this.memberIds = memberIds;
}
public CreateChatDTO title(String title) {
this.title = title;
return this;
}
@NotNull
@CodePointLength(min = 1, max = 100)
@Schema(name = "title", requiredMode = Schema.RequiredMode.REQUIRED)
@JsonProperty("title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public CreateChatDTO memberIds(List<UUID> memberIds) {
this.memberIds = memberIds;
return this;
}
public CreateChatDTO addMemberIdsItem(UUID memberIdsItem) {
if (this.memberIds == null) {
this.memberIds = new ArrayList<>();
}
this.memberIds.add(memberIdsItem);
return this;
}
@NotNull
@Valid
@Size(min = 1, max = 100)
@Schema(name = "member_ids", requiredMode = Schema.RequiredMode.REQUIRED)
@JsonProperty("member_ids")
public List<UUID> getMemberIds() {
return memberIds;
}
public void setMemberIds(List<UUID> memberIds) {
this.memberIds = memberIds;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CreateChatDTO that = (CreateChatDTO) o;
return Objects.equals(title, that.title) && Objects.equals(memberIds, that.memberIds);
}
@Override
public int hashCode() {
return Objects.hash(title, memberIds);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class CreateChatDTO {\n");
sb.append(" title: ").append(toIndentedString(title)).append("\n");
sb.append(" memberIds: ").append(toIndentedString(memberIds)).append("\n");
sb.append("}");
return sb.toString();
}
private String toIndentedString(Object o) {
if (o == null) return "null";
return o.toString().replace("\n", "\n ");
}
}
@@ -0,0 +1,110 @@
package ru.mtusi.messenger.dto;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.*;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Generated;
import org.hibernate.validator.constraints.CodePointLength;
@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", comments = "Generator version: 7.10.0")
public class CreateUserDTO {
private String username;
private String displayName;
private String password;
public CreateUserDTO() {
super();
}
public CreateUserDTO(String username, String displayName, String password) {
this.username = username;
this.displayName = displayName;
this.password = password;
}
public CreateUserDTO username(String username) {
this.username = username;
return this;
}
@NotNull
@Pattern(regexp = "^[a-z0-9_]{3,32}$")
@Schema(name = "username", requiredMode = Schema.RequiredMode.REQUIRED)
@JsonProperty("username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public CreateUserDTO displayName(String displayName) {
this.displayName = displayName;
return this;
}
@NotNull
@CodePointLength(min = 1, max = 100)
@Schema(name = "display_name", requiredMode = Schema.RequiredMode.REQUIRED)
@JsonProperty("display_name")
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public CreateUserDTO password(String password) {
this.password = password;
return this;
}
@NotNull
@CodePointLength(min = 12, max = 128)
@Schema(name = "password", requiredMode = Schema.RequiredMode.REQUIRED, accessMode = Schema.AccessMode.WRITE_ONLY)
@JsonProperty(value = "password", access = JsonProperty.Access.WRITE_ONLY)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CreateUserDTO createUser = (CreateUserDTO) o;
return Objects.equals(this.username, createUser.username) &&
Objects.equals(this.displayName, createUser.displayName) &&
Objects.equals(this.password, createUser.password);
}
@Override
public int hashCode() {
return Objects.hash(username, displayName, password);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class CreateUserDTO {\n");
sb.append(" username: ").append(toIndentedString(username)).append("\n");
sb.append(" displayName: ").append(toIndentedString(displayName)).append("\n");
sb.append(" password: ").append(password != null ? "***" : "null").append("\n");
sb.append("}");
return sb.toString();
}
private String toIndentedString(Object o) {
if (o == null) return "null";
return o.toString().replace("\n", "\n ");
}
}
@@ -22,8 +22,6 @@ public class UserDTO {
private String displayName;
private String password;
private Instant createdAt;
public UserDTO() {
@@ -36,7 +34,6 @@ public class UserDTO {
public UserDTO(String username, String displayName, String password) {
this.username = username;
this.displayName = displayName;
this.password = password;
}
public UserDTO username(String username) {
@@ -96,26 +93,10 @@ public class UserDTO {
this.displayName = displayName;
}
public UserDTO password(String password) {
this.password = password;
return this;
}
/**
* Get password
* @return password
*/
@NotNull
@CodePointLength(min = 1, max = 100)
@Schema(name = "password", requiredMode = Schema.RequiredMode.REQUIRED)
@JsonProperty("password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserDTO createdAt(Instant createdAt) {
this.createdAt = createdAt;
@@ -148,13 +129,12 @@ public class UserDTO {
return Objects.equals(this.id, userDTO.id) &&
Objects.equals(this.username, userDTO.username) &&
Objects.equals(this.displayName, userDTO.displayName) &&
Objects.equals(this.password, userDTO.password) &&
Objects.equals(this.createdAt, userDTO.createdAt);
}
@Override
public int hashCode() {
return Objects.hash(id, username, displayName, password, createdAt);
return Objects.hash(id, username, displayName, createdAt);
}
@Override
@@ -164,7 +144,6 @@ public class UserDTO {
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" username: ").append(toIndentedString(username)).append("\n");
sb.append(" displayName: ").append(toIndentedString(displayName)).append("\n");
sb.append(" password: ").append(toIndentedString(password)).append("\n");
sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n");
sb.append("}");
return sb.toString();
@@ -4,6 +4,7 @@ import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import ru.mtusi.messenger.dto.ChatDTO;
import ru.mtusi.messenger.dto.CreateChatDTO;
import ru.mtusi.messenger.model.Chat;
import ru.mtusi.messenger.model.User;
@@ -19,7 +20,7 @@ public interface ChatMapper {
@Mapping(target = "createdAt", ignore = true)
@Mapping(target = "members", ignore = true)
@Mapping(target = "messages", ignore = true)
Chat toChat(ChatDTO dto);
Chat toChat(CreateChatDTO dto);
@Mapping(target = "memberIds", source = "members", qualifiedByName = "usersToIds")
ChatDTO toChatDto(Chat chat);
@@ -2,6 +2,7 @@ package ru.mtusi.messenger.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import ru.mtusi.messenger.dto.CreateUserDTO;
import ru.mtusi.messenger.dto.UserDTO;
import ru.mtusi.messenger.model.User;
@@ -13,8 +14,7 @@ public interface UserMapper {
@Mapping(target = "passwordHash", ignore = true)
@Mapping(target = "chats", ignore = true)
@Mapping(target = "messages", ignore = true)
User toUser(UserDTO dto);
@Mapping(target = "password", ignore = true)
User toUser(CreateUserDTO dto);
UserDTO toUserDto(User user);
}
@@ -18,14 +18,18 @@ public class ApiAuthenticationEntryPoint implements AuthenticationEntryPoint {
private final ApiErrorFactory errors;
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
String scheme = request.getRequestURI().equals("/api/v1/auth/sessions") ? "Basic" : "Bearer";
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
boolean isLogin = "/api/v1/auth/sessions".equals(request.getRequestURI());
String challenge = isLogin
? "Basic realm=\"messenger\", charset=\"UTF-8\""
: "Bearer realm=\"messenger\"";
errors.writeError(
response,
request,
HttpStatus.UNAUTHORIZED,
scheme + " realm=\"messenger\"",
challenge,
ErrorErrorDTO.CodeEnum.UNAUTHORIZED,
"No valid authentication");
}
@@ -6,6 +6,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import ru.mtusi.messenger.dto.SessionDTO;
import ru.mtusi.messenger.dto.UserDTO;
import ru.mtusi.messenger.exception.InvalidRequestException;
import ru.mtusi.messenger.exception.UnauthorizedException;
import ru.mtusi.messenger.security.BasicCredentials;
import ru.mtusi.messenger.security.SessionPrincipal;
@@ -16,7 +17,10 @@ public class AuthService {
private final UserService userService;
private final SessionService sessionService;
public SessionDTO login(String authorizationHeader) {
public SessionDTO login(String authorizationHeader, long contentLength) {
if (contentLength > 0) {
throw new InvalidRequestException("Request body is not allowed");
}
var creds = BasicCredentials.parse(authorizationHeader);
UserDTO userDTO = userService.authenticate(creds.username(), creds.password());
return sessionService.createSession(userDTO);
@@ -8,6 +8,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.dto.ChatDTO;
import ru.mtusi.messenger.dto.ChatPageDTO;
import ru.mtusi.messenger.dto.CreateChatDTO;
import ru.mtusi.messenger.exception.InvalidRequestException;
import ru.mtusi.messenger.exception.NotFoundException;
import ru.mtusi.messenger.mapper.ChatMapper;
@@ -28,15 +29,15 @@ public class ChatService {
private final ChatRepository chatRepository;
@Transactional
public ChatDTO createChat(UUID caller, ChatDTO chatDTO) {
Set<User> members = chatValidator.validateCreate(caller, chatDTO);
Chat chat = buildChat(chatDTO, members);
public ChatDTO createChat(UUID caller, CreateChatDTO createChatDTO) {
Set<User> members = chatValidator.validateCreate(caller, createChatDTO);
Chat chat = buildChat(createChatDTO, members);
chat = persistChat(chat);
return chatMapper.toChatDto(chat);
}
private Chat buildChat(ChatDTO chatDTO, Set<User> members) {
Chat chat = chatMapper.toChat(chatDTO);
private Chat buildChat(CreateChatDTO createChatDTO, Set<User> members) {
Chat chat = chatMapper.toChat(createChatDTO);
chat.setMembers(members);
return chat;
}
@@ -93,13 +94,13 @@ public class ChatService {
}
private CursorCodec.Cursor parseChatsCursor(String cursor) {
if (cursor == null || cursor.isBlank()) {
if (cursor == null)
return null;
}
if (cursor.isEmpty())
throw new InvalidRequestException("Cursor must not be empty");
CursorCodec.Cursor decoded = CursorCodec.decode(cursor);
if (decoded.scopeId() != null) {
if (decoded.scopeId() != null)
throw new InvalidRequestException("Invalid cursor");
}
return decoded;
}
@@ -1,29 +1,49 @@
package ru.mtusi.messenger.service;
import com.zaxxer.hikari.HikariDataSource;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import ru.mtusi.messenger.dto.HealthDTO;
import ru.mtusi.messenger.exception.ServiceUnavailableException;
import javax.sql.DataSource;
@Service
@RequiredArgsConstructor
public class HealthService {
private final JdbcTemplate jdbcTemplate;
private final DataSource dataSource;
public HealthDTO readiness() {
requirePoolAvailable();
requireDatabaseReachable();
return ok();
}
public HealthDTO liveness() {
return ok();
}
private void requirePoolAvailable() {
if (dataSource instanceof HikariDataSource hikari) {
var pool = hikari.getHikariPoolMXBean();
if (pool != null && pool.getActiveConnections() >= hikari.getMaximumPoolSize()) {
throw new ServiceUnavailableException("Database connection pool exhausted");
}
}
}
private void requireDatabaseReachable() {
try {
jdbcTemplate.queryForObject("SELECT 1", Integer.class);
} catch (Exception e) {
throw new ServiceUnavailableException("Database unavailable");
}
HealthDTO h = new HealthDTO();
h.setStatus(HealthDTO.StatusEnum.OK);
return h;
}
public HealthDTO liveness() {
private HealthDTO ok() {
HealthDTO h = new HealthDTO();
h.setStatus(HealthDTO.StatusEnum.OK);
return h;
@@ -83,13 +83,13 @@ public class MessageService {
}
private CursorCodec.Cursor parseMessagesCursor(String cursor, UUID chatId) {
if (cursor == null || cursor.isBlank()) {
if (cursor == null)
return null;
}
if (cursor.isEmpty())
throw new InvalidRequestException("Cursor must not be empty");
CursorCodec.Cursor decoded = CursorCodec.decode(cursor);
if (decoded.scopeId() == null || !decoded.scopeId().equals(chatId)) {
if (decoded.scopeId() == null || !decoded.scopeId().equals(chatId))
throw new InvalidRequestException("Cursor from another chat");
}
return decoded;
}
@@ -6,6 +6,7 @@ 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.CreateUserDTO;
import ru.mtusi.messenger.dto.UserDTO;
import ru.mtusi.messenger.exception.ConflictException;
import ru.mtusi.messenger.exception.NotFoundException;
@@ -59,9 +60,9 @@ public class UserService {
}
@Transactional
public UserDTO registerUser(UserDTO userDTO) {
User user = userMapper.toUser(userDTO);
user.setPasswordHash(passwordEncoder.encode(userDTO.getPassword()));
public UserDTO registerUser(CreateUserDTO createUserDTO) {
User user = userMapper.toUser(createUserDTO);
user.setPasswordHash(passwordEncoder.encode(createUserDTO.getPassword()));
try {
return userMapper.toUserDto(userRepository.saveAndFlush(user));
} catch (DataIntegrityViolationException exception) {
@@ -3,6 +3,7 @@ package ru.mtusi.messenger.validation;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import ru.mtusi.messenger.dto.ChatDTO;
import ru.mtusi.messenger.dto.CreateChatDTO;
import ru.mtusi.messenger.exception.InvalidRequestException;
import ru.mtusi.messenger.exception.NotFoundException;
import ru.mtusi.messenger.model.User;
@@ -19,9 +20,9 @@ public class ChatValidator {
private final UserService userService;
public Set<User> validateCreate(UUID caller, ChatDTO chatDTO) {
List<UUID> memberIds = chatDTO.getMemberIds();
String title = chatDTO.getTitle();
public Set<User> validateCreate(UUID caller, CreateChatDTO createChatDTO) {
List<UUID> memberIds = createChatDTO.getMemberIds();
String title = createChatDTO.getTitle();
requireNotBlank(title, "Title must not be blank");
requireNonEmpty(memberIds, "member_ids must not be empty");