forked from mtusi2026/mtusi2026lab4
Перенос из 3 лабы
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
package org.example;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class LidoApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(LidoApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package org.example.config;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.example.repository.SessionRepository;
|
||||
import org.example.service.AuthService;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AuthFilter extends OncePerRequestFilter {
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
String path = request.getRequestURI();
|
||||
return path.startsWith("/health/")
|
||||
|| path.startsWith("/actuator/");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
String auth = request.getHeader("Authorization");
|
||||
if (auth != null && auth.startsWith("Bearer ")) {
|
||||
String token = auth.substring(7).trim();
|
||||
if (!token.isEmpty()) {
|
||||
authService.resolveUserByBearer(token)
|
||||
.ifPresent(UserContext::setCurrentUser);
|
||||
}
|
||||
}
|
||||
try {
|
||||
filterChain.doFilter(request, response);
|
||||
} finally {
|
||||
UserContext.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package org.example.config;
|
||||
|
||||
import org.springframework.context.event.ContextClosedEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class GracefulShutdownListener {
|
||||
|
||||
private final ReadinessState state;
|
||||
|
||||
public GracefulShutdownListener(ReadinessState state) {
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
@EventListener(ContextClosedEvent.class)
|
||||
public void onClose(){
|
||||
state.setReady(false);
|
||||
try {
|
||||
Thread.sleep(2000);
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package org.example.config;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
public class InstanceIdFilter extends OncePerRequestFilter {
|
||||
|
||||
public static final String HEADER = "X-Instance-Id";
|
||||
private final String instanceId;
|
||||
|
||||
public InstanceIdFilter() {
|
||||
this.instanceId = resolve();
|
||||
}
|
||||
|
||||
private static String resolve() {
|
||||
String id = firstNonBlank(
|
||||
System.getenv("INSTANCE_ID"),
|
||||
System.getenv("HOSTNAME"),
|
||||
System.getProperty("HOSTNAME")
|
||||
);
|
||||
if (id == null) {
|
||||
id = "unknown-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
private static String firstNonBlank(String... values) {
|
||||
if (values == null) return null;
|
||||
for (String v : values) {
|
||||
if (v != null && !v.isBlank()) return v.trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain filterChain
|
||||
) throws ServletException, IOException {
|
||||
response.setHeader(HEADER, instanceId);
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package org.example.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
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() {
|
||||
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,17 @@
|
||||
package org.example.config;
|
||||
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
@Component
|
||||
public class ReadinessState {
|
||||
private final AtomicBoolean ready = new AtomicBoolean(true);
|
||||
public boolean isReady() {
|
||||
return ready.get();
|
||||
}
|
||||
public void setReady(boolean v) {
|
||||
ready.set(v);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package org.example.config;
|
||||
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
public class RequestIdFilter extends OncePerRequestFilter {
|
||||
|
||||
public static final String REQUEST_ID_HEADER = "X-Request-Id";
|
||||
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
String requestId = request.getHeader(REQUEST_ID_HEADER);
|
||||
|
||||
if (requestId == null || requestId.trim().isEmpty()) {
|
||||
requestId = UUID.randomUUID().toString();
|
||||
}
|
||||
|
||||
MDC.put(REQUEST_ID_HEADER, requestId);
|
||||
|
||||
request.setAttribute(REQUEST_ID_HEADER, requestId);
|
||||
response.setHeader(REQUEST_ID_HEADER, requestId);
|
||||
|
||||
try {
|
||||
filterChain.doFilter(request, response);
|
||||
} finally {
|
||||
MDC.remove(REQUEST_ID_HEADER);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package org.example.config;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.HexFormat;
|
||||
|
||||
public final class TokenHasher {
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
public TokenHasher() {}
|
||||
|
||||
public static String newRawToken(){
|
||||
byte[] bytes = new byte[32];
|
||||
RANDOM.nextBytes(bytes);
|
||||
return HexFormat.of().formatHex(bytes);
|
||||
}
|
||||
|
||||
public static String sha256(String rawToken) {
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||
byte[] dig = md.digest(rawToken.getBytes(StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(dig);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package org.example.config;
|
||||
|
||||
import org.example.model.User;
|
||||
|
||||
public class UserContext {
|
||||
private static final ThreadLocal<User> CURRENT_USER = new ThreadLocal<>();
|
||||
|
||||
public static void setCurrentUser(User user) {
|
||||
CURRENT_USER.set(user);
|
||||
}
|
||||
|
||||
public static User getCurrentUser() {
|
||||
return CURRENT_USER.get();
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
CURRENT_USER.remove();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package org.example.controller;
|
||||
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.example.dto.response.SessionInfoResponse;
|
||||
import org.example.dto.response.SessionResponse;
|
||||
import org.example.exception.UnauthorizedException;
|
||||
import org.example.service.AuthService;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/auth")
|
||||
@RequiredArgsConstructor
|
||||
public class AuthController {
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
@PostMapping("/sessions")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public SessionResponse login(HttpServletRequest request) {
|
||||
String header = request.getHeader("Authorization");
|
||||
if (header == null || !header.startsWith("Basic ")) {
|
||||
throw new UnauthorizedException("Unauthorized");
|
||||
}
|
||||
String decoded;
|
||||
try {
|
||||
decoded = new String(
|
||||
Base64.getDecoder().decode(header.substring(6).trim()),
|
||||
StandardCharsets.UTF_8);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new UnauthorizedException("Unauthorized");
|
||||
}
|
||||
int colon = decoded.indexOf(':');
|
||||
if (colon < 0) {
|
||||
throw new UnauthorizedException("Unauthorized");
|
||||
}
|
||||
String username = decoded.substring(0, colon);
|
||||
String password = decoded.substring(colon + 1);
|
||||
return authService.login(username, password);
|
||||
}
|
||||
|
||||
@DeleteMapping("/sessions/current")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void revokeCurrent(HttpServletRequest request) {
|
||||
String header = request.getHeader("Authorization");
|
||||
if (header == null || !header.startsWith("Bearer ")) {
|
||||
throw new UnauthorizedException("Unauthorized");
|
||||
}
|
||||
String token = header.substring(7).trim();
|
||||
if (token.isEmpty()) {
|
||||
throw new UnauthorizedException("Unauthorized");
|
||||
}
|
||||
authService.logoutCurrent(token);
|
||||
}
|
||||
|
||||
@GetMapping("/sessions")
|
||||
public List<SessionInfoResponse> sessions() {
|
||||
return authService.listSessionsForCurrentUser();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
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;
|
||||
import org.example.dto.MessagePage;
|
||||
import org.example.dto.create.CreateChatDto;
|
||||
import org.example.dto.create.CreateMessageDto;
|
||||
import org.example.dto.response.ChatResponse;
|
||||
import org.example.dto.update.UpdateChatDto;
|
||||
import org.example.dto.update.UpdateMessageDto;
|
||||
import org.example.model.Message;
|
||||
import org.example.service.ChatService;
|
||||
import org.example.service.MessageService;
|
||||
import org.example.service.UserService;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/chats")
|
||||
@RequiredArgsConstructor
|
||||
@Validated
|
||||
public class ChatController {
|
||||
|
||||
private final ChatService chatService;
|
||||
private final MessageService messageService;
|
||||
private final UserService userService;
|
||||
|
||||
// ——— Chats ———
|
||||
|
||||
@PostMapping
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public ChatResponse createChat(@Valid @RequestBody CreateChatDto dto) {
|
||||
return chatService.createChat(dto);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ChatPage getChats(
|
||||
@RequestParam(defaultValue = "50")
|
||||
@Max(100)
|
||||
@Min(value = 1, message = "limit must be >= 1") int limit
|
||||
) {
|
||||
return chatService.getChatsForCurrentUser(limit);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ChatResponse getChatById(@PathVariable UUID id) {
|
||||
return chatService.getChatById(id);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ChatResponse updateChat(
|
||||
@PathVariable UUID id,
|
||||
@Valid @RequestBody UpdateChatDto object
|
||||
) {
|
||||
return chatService.updateChat(id, object);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void deleteChat(@PathVariable UUID id) {
|
||||
chatService.deleteChat(id);
|
||||
}
|
||||
|
||||
// ——— Messages ———
|
||||
|
||||
@PostMapping("/{id}/messages")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public Message sendMessage(
|
||||
@PathVariable("id") UUID id,
|
||||
@RequestHeader("Idempotency-Key") String idempotencyKey,
|
||||
@Valid @RequestBody CreateMessageDto messageDto
|
||||
) {
|
||||
UUID senderId = userService.getCurrentUser().getId();
|
||||
return messageService.sendMessage(id, senderId, messageDto, idempotencyKey);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/messages")
|
||||
public MessagePage getMessages(
|
||||
@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();
|
||||
return messageService.getMessage(id, userId, cursor, limit);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}/messages/{messageId}")
|
||||
public Message updateMessage(
|
||||
@PathVariable("id") UUID id,
|
||||
@PathVariable UUID messageId,
|
||||
@Valid @RequestBody UpdateMessageDto object
|
||||
) {
|
||||
UUID userId = userService.getCurrentUser().getId();
|
||||
return messageService.updateMessage(id, messageId, userId, object);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}/messages/{messageId}")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void deleteMessage(
|
||||
@PathVariable("id") UUID id,
|
||||
@PathVariable UUID messageId
|
||||
) {
|
||||
UUID userId = userService.getCurrentUser().getId();
|
||||
messageService.deleteMessage(id, messageId, userId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package org.example.controller;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/health")
|
||||
public class HealthController {
|
||||
|
||||
private final DataSource dataSource;
|
||||
private final AtomicBoolean ready = new AtomicBoolean(true);
|
||||
|
||||
public HealthController(DataSource dataSource) {
|
||||
this.dataSource = dataSource;
|
||||
}
|
||||
|
||||
@GetMapping({"/live"})
|
||||
public ResponseEntity<Map<String, String>> live() {
|
||||
return ResponseEntity.ok(Map.of("status", "ok"));
|
||||
}
|
||||
|
||||
@GetMapping("/ready")
|
||||
public ResponseEntity<Map<String, String>> ready(){
|
||||
if (!ready.get()){
|
||||
return ResponseEntity.status(503).body(Map.of("status", "NOT_READY"));
|
||||
}
|
||||
try (Connection c = dataSource.getConnection()){
|
||||
if (!c.isValid(1)){
|
||||
return ResponseEntity.status(503).body(Map.of("status", "DB_DOWN"));
|
||||
}
|
||||
} catch (Exception e){
|
||||
return ResponseEntity.status(503).body(Map.of("status", "DB_DOWN"));
|
||||
}
|
||||
return ResponseEntity.ok(Map.of("status", "ok"));
|
||||
}
|
||||
|
||||
public void markNotReady() {
|
||||
ready.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package org.example.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.example.dto.create.CreateUserDto;
|
||||
import org.example.dto.update.UpdateUserDto;
|
||||
import org.example.model.User;
|
||||
import org.example.service.UserService;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/users")
|
||||
@RequiredArgsConstructor
|
||||
public class UserController {
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
@PostMapping
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public User createUser(@Valid @RequestBody CreateUserDto dto) {
|
||||
return userService.createUser(dto);
|
||||
}
|
||||
|
||||
@GetMapping("/me")
|
||||
public User getCurrentUser() {
|
||||
return userService.getCurrentUser();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public User getUserById(@PathVariable UUID id) {
|
||||
return userService.getUserById(id);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public User updateUser(@PathVariable String id,
|
||||
@Valid @RequestBody UpdateUserDto object) {
|
||||
return userService.updateUser(id, object);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void delete(@PathVariable String id) {
|
||||
userService.deleteUser(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.example.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonNaming;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.example.dto.response.ChatResponse;
|
||||
import org.example.model.Chat;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
|
||||
public class ChatPage {
|
||||
private List<ChatResponse> items;
|
||||
@JsonProperty("next_cursor")
|
||||
private String nextCursor;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package org.example.dto;
|
||||
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class ErrorDetail {
|
||||
private String code;
|
||||
private String message;
|
||||
private String request_id;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package org.example.dto;
|
||||
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.example.model.Message;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@RequiredArgsConstructor
|
||||
public class MessagePage {
|
||||
private List<Message> items;
|
||||
private String nextCursor;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
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 не может быть пустым")
|
||||
@CodePointSize(min = 1, max = 100)
|
||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||
private String title;
|
||||
|
||||
@JsonProperty("member_ids")
|
||||
@NotEmpty(message = "Список участников не может быть пустым")
|
||||
private List<@NotNull UUID> memberIds;
|
||||
}
|
||||
@@ -0,0 +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 = "Текст сообщения не может быть пустым")
|
||||
@CodePointSize(min = 1, max = 4000)
|
||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||
private String text;
|
||||
}
|
||||
@@ -0,0 +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
|
||||
@Size(min = 3, max = 32)
|
||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||
@Pattern(regexp = "^[a-z0-9_]{3,32}$")
|
||||
private String username;
|
||||
|
||||
@NotBlank(message = "Display name не может быть пустым")
|
||||
@CodePointSize(min = 1, max = 128)
|
||||
@JsonProperty("display_name")
|
||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||
private String displayName;
|
||||
|
||||
@NotBlank(message = "Password не может быть пустым")
|
||||
@CodePointSize(min = 12, max = 128)
|
||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||
private String password;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package org.example.dto.response;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class ChatResponse {
|
||||
private UUID id;
|
||||
private String title;
|
||||
@JsonProperty("member_ids")
|
||||
private List<UUID> memberIds;
|
||||
@JsonProperty("created_at")
|
||||
private Instant createdAt;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package org.example.dto.response;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import org.example.dto.ErrorDetail;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class ErrorResponse {
|
||||
private ErrorDetail error;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package org.example.dto.response;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class MessageResponse {
|
||||
private UUID id;
|
||||
@JsonProperty("chat_id")
|
||||
private UUID chatId;
|
||||
@JsonProperty("sender_id")
|
||||
private UUID senderId;
|
||||
private String text;
|
||||
@JsonProperty("created_at")
|
||||
private Instant createdAt;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package org.example.dto.response;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class SessionInfoResponse {
|
||||
private UUID id;
|
||||
@JsonProperty("created_at")
|
||||
private Instant createdAt;
|
||||
@JsonProperty("expires_at")
|
||||
private Instant expiresAt;
|
||||
@JsonProperty("revoked_at")
|
||||
private Instant revokedAt;
|
||||
private boolean active;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package org.example.dto.response;
|
||||
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Data
|
||||
public class SessionResponse {
|
||||
|
||||
private String token;
|
||||
|
||||
@JsonProperty("token_type")
|
||||
private String tokenType;
|
||||
|
||||
@JsonProperty("expires_at")
|
||||
private Instant expiresAt;
|
||||
|
||||
private UserResponse user;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package org.example.dto.response;
|
||||
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Builder
|
||||
public class UserResponse {
|
||||
private UUID id;
|
||||
private String username;
|
||||
@JsonProperty("display_name")
|
||||
private String displayName;
|
||||
@JsonProperty("created_at")
|
||||
private Instant createdAt;
|
||||
}
|
||||
@@ -0,0 +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
|
||||
@CodePointSize(min = 1, max = 100)
|
||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||
private String title;
|
||||
}
|
||||
@@ -0,0 +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
|
||||
@CodePointSize(min = 1, max = 4000)
|
||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||
private String text;
|
||||
}
|
||||
@@ -0,0 +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 lombok.Data;
|
||||
import org.example.config.CodePointSize;
|
||||
import org.example.config.StrictStringDeserializer;
|
||||
|
||||
@Data
|
||||
public class UpdateUserDto {
|
||||
@NotBlank
|
||||
@CodePointSize(min = 1, max = 128)
|
||||
@JsonProperty("display_name")
|
||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||
private String displayName;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package org.example.exception;
|
||||
|
||||
public class ConflictException extends RuntimeException {
|
||||
public ConflictException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package org.example.exception;
|
||||
|
||||
public class ForbiddenException extends RuntimeException {
|
||||
public ForbiddenException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
package org.example.exception;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.example.config.RequestIdFilter;
|
||||
import org.example.dto.ErrorDetail;
|
||||
import org.example.dto.response.ErrorResponse;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
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 org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@Slf4j
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
private String resolveRequestId(HttpServletRequest request) {
|
||||
Object attr = request.getAttribute(RequestIdFilter.REQUEST_ID_HEADER);
|
||||
if (attr instanceof String s && !s.isBlank()) {
|
||||
return s;
|
||||
}
|
||||
String header = request.getHeader(RequestIdFilter.REQUEST_ID_HEADER);
|
||||
if (header != null && !header.isBlank()) {
|
||||
return header.trim();
|
||||
}
|
||||
return UUID.randomUUID().toString();
|
||||
}
|
||||
|
||||
@ExceptionHandler(NotFoundException.class)
|
||||
public ResponseEntity<ErrorResponse> handleNotFound(NotFoundException ex, HttpServletRequest request) {
|
||||
String reqId = resolveRequestId(request);
|
||||
ErrorResponse body = new ErrorResponse(
|
||||
new ErrorDetail("not_found", ex.getMessage(), reqId)
|
||||
);
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.header("X-Request-Id", reqId)
|
||||
.body(body);
|
||||
}
|
||||
|
||||
@ExceptionHandler(ForbiddenException.class)
|
||||
public ResponseEntity<ErrorResponse> handleForbidden(ForbiddenException ex, HttpServletRequest request) {
|
||||
String reqId = resolveRequestId(request);
|
||||
ErrorResponse body = new ErrorResponse(
|
||||
new ErrorDetail("forbidden", ex.getMessage(), reqId)
|
||||
);
|
||||
// если в openapi нет code "forbidden" — замени на "unauthorized" или как в контракте
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN)
|
||||
.header("X-Request-Id", reqId)
|
||||
.body(body);
|
||||
}
|
||||
|
||||
@ExceptionHandler(ConflictException.class)
|
||||
public ResponseEntity<ErrorResponse> handleConflictException(
|
||||
ConflictException ex,
|
||||
HttpServletRequest request
|
||||
) {
|
||||
log.debug("Validation failed", ex);
|
||||
String reqId = resolveRequestId(request);
|
||||
ErrorResponse body = new ErrorResponse(
|
||||
new ErrorDetail("conflict", "conflict", reqId)
|
||||
);
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.header("X-Request-Id", reqId)
|
||||
.body(body);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<ErrorResponse> handleValidationException(
|
||||
MethodArgumentNotValidException ex,
|
||||
HttpServletRequest request
|
||||
) {
|
||||
log.debug("Validation failed", ex);
|
||||
String reqId = resolveRequestId(request);
|
||||
ErrorResponse body = new ErrorResponse(
|
||||
new ErrorDetail("invalid_request", "Validation Failed", reqId)
|
||||
);
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.header("X-Request-Id", reqId)
|
||||
.body(body);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MissingRequestHeaderException.class)
|
||||
public ResponseEntity<ErrorResponse> handleMissingHeader(
|
||||
MissingRequestHeaderException ex,
|
||||
HttpServletRequest request
|
||||
) {
|
||||
String reqId = resolveRequestId(request);
|
||||
ErrorResponse body = new ErrorResponse(
|
||||
new ErrorDetail("invalid_request", "Malformed JSON request body", reqId)
|
||||
);
|
||||
return ResponseEntity
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.header("X-Request-Id", reqId)
|
||||
.body(body);
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||
public ResponseEntity<ErrorResponse> handleMalformedJson(
|
||||
HttpMessageNotReadableException ex,
|
||||
HttpServletRequest request
|
||||
) {
|
||||
String reqId = resolveRequestId(request);
|
||||
ErrorResponse body = new ErrorResponse(
|
||||
new ErrorDetail("invalid_request", "Malformed JSON request body", reqId)
|
||||
);
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.header("X-Request-Id", reqId)
|
||||
.body(body);
|
||||
}
|
||||
|
||||
@ExceptionHandler(IllegalArgumentException.class)
|
||||
public ResponseEntity<ErrorResponse> handleBadRequest(
|
||||
IllegalArgumentException ex,
|
||||
HttpServletRequest request
|
||||
) {
|
||||
String reqId = resolveRequestId(request);
|
||||
ErrorResponse body = new ErrorResponse(
|
||||
new ErrorDetail("invalid_request", ex.getMessage(), reqId)
|
||||
);
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.header("X-Request-Id", reqId)
|
||||
.body(body);
|
||||
}
|
||||
|
||||
@ExceptionHandler(UserAlreadyExistsException.class)
|
||||
public ResponseEntity<ErrorResponse> handleUserAlreadyExists(
|
||||
UserAlreadyExistsException ex,
|
||||
HttpServletRequest request
|
||||
) {
|
||||
String reqId = resolveRequestId(request);
|
||||
ErrorResponse body = new ErrorResponse(
|
||||
new ErrorDetail("conflict", ex.getMessage(), reqId)
|
||||
);
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.header("X-Request-Id", reqId)
|
||||
.body(body);
|
||||
}
|
||||
|
||||
@ExceptionHandler(UnauthorizedException.class)
|
||||
public ResponseEntity<Map<String, Object>> handleUnauthorized(
|
||||
UnauthorizedException ex,
|
||||
HttpServletRequest request
|
||||
) {
|
||||
String requestId = resolveRequestId(request);
|
||||
|
||||
String path = request.getRequestURI();
|
||||
String www;
|
||||
if (path != null
|
||||
&& path.startsWith("/api/v1/auth/sessions")
|
||||
&& "POST".equalsIgnoreCase(request.getMethod())) {
|
||||
www = "Basic realm=\"messenger\", charset=\"UTF-8\"";
|
||||
} else {
|
||||
www = "Bearer realm=\"messenger\"";
|
||||
}
|
||||
|
||||
Map<String, Object> body = Map.of(
|
||||
"error", Map.of(
|
||||
"code", "unauthorized",
|
||||
"message", ex.getMessage() != null ? ex.getMessage() : "Unauthorized",
|
||||
"request_id", requestId
|
||||
)
|
||||
);
|
||||
|
||||
return ResponseEntity
|
||||
.status(HttpStatus.UNAUTHORIZED)
|
||||
.header("X-Request-Id", requestId)
|
||||
.header("WWW-Authenticate", www)
|
||||
.body(body);
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorResponse> handleAllOtherExceptions(Exception ex, HttpServletRequest request) {
|
||||
log.error("CRITICAL ERROR ON REQUEST: {}", request.getRequestURI(), ex);
|
||||
String reqId = resolveRequestId(request);
|
||||
ErrorResponse body = new ErrorResponse(
|
||||
new ErrorDetail("internal_error", "Internal server error", reqId)
|
||||
);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.header("X-Request-Id", reqId)
|
||||
.body(body);
|
||||
}
|
||||
|
||||
@ExceptionHandler(ConstraintViolationException.class)
|
||||
public ResponseEntity<ErrorResponse> handleConstraintViolation(
|
||||
ConstraintViolationException ex,
|
||||
HttpServletRequest request
|
||||
) {
|
||||
String reqId = resolveRequestId(request);
|
||||
ErrorResponse body = new ErrorResponse(
|
||||
new ErrorDetail("invalid_request", "Validation Failed", reqId)
|
||||
);
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.header("X-Request-Id", reqId)
|
||||
.body(body);
|
||||
}
|
||||
|
||||
@ExceptionHandler(DataIntegrityViolationException.class)
|
||||
public ResponseEntity<ErrorResponse> handleDataIntegrity(
|
||||
DataIntegrityViolationException ex,
|
||||
HttpServletRequest request
|
||||
) {
|
||||
String reqId = resolveRequestId(request);
|
||||
ErrorResponse body = new ErrorResponse(
|
||||
new ErrorDetail("conflict", "Conflict", reqId)
|
||||
);
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.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_request", "Invalid UUID", reqId)
|
||||
);
|
||||
// Error body: code invalid_request, request_id = reqId
|
||||
return ResponseEntity
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.header("X-Request-Id", reqId)
|
||||
.body(body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package org.example.exception;
|
||||
|
||||
public class NotFoundException extends RuntimeException {
|
||||
public NotFoundException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package org.example.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@ResponseStatus(HttpStatus.UNAUTHORIZED)
|
||||
public class UnauthorizedException extends RuntimeException {
|
||||
private final String wwwAuthenticate;
|
||||
|
||||
public UnauthorizedException(String wwwAuthenticate) {
|
||||
super("Unauthorized");
|
||||
this.wwwAuthenticate = wwwAuthenticate;
|
||||
}
|
||||
|
||||
public String getWwwAuthenticate() {
|
||||
return wwwAuthenticate;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package org.example.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@ResponseStatus(HttpStatus.CONFLICT)
|
||||
public class UserAlreadyExistsException extends RuntimeException {
|
||||
public UserAlreadyExistsException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package org.example.model;
|
||||
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
|
||||
@Entity
|
||||
@Table(name = "chats")
|
||||
@Setter
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Builder
|
||||
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
|
||||
public class Chat {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.UUID)
|
||||
private UUID id;
|
||||
|
||||
@Column(nullable = false, length = 100)
|
||||
private String title;
|
||||
|
||||
@OneToMany(mappedBy = "chat", fetch = FetchType.LAZY)
|
||||
@JsonIgnore
|
||||
@Builder.Default
|
||||
private List<ChatMember> members =new ArrayList<>();
|
||||
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
@JsonProperty("created_at")
|
||||
private Instant createdAt;
|
||||
|
||||
@Transient
|
||||
@JsonProperty("member_ids")
|
||||
private List<UUID> memberIds;
|
||||
public void setMemberIdsForResponse(List<UUID> ids) {
|
||||
this.memberIds = ids;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package org.example.model;
|
||||
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "chat_members")
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
@IdClass(ChatMember.ChatMemberId.class)
|
||||
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
|
||||
public class ChatMember {
|
||||
|
||||
@Id
|
||||
@Column(name = "chat_id")
|
||||
private UUID chatId;
|
||||
|
||||
@Id
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private UUID userId;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "chat_id", insertable = false, updatable = false)
|
||||
private Chat chat;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "user_id", insertable = false, updatable = false)
|
||||
private User user;
|
||||
|
||||
@CreationTimestamp
|
||||
@Column(name = "joined_at", nullable = false, updatable = false)
|
||||
private Instant joinedAt;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class ChatMemberId implements Serializable {
|
||||
private UUID chatId;
|
||||
private UUID userId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package org.example.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "idempotency_keys",
|
||||
uniqueConstraints = @UniqueConstraint(
|
||||
name = "uq_idempotency_user_chat_key",
|
||||
columnNames = {"user_id", "chat_id", "idempotency_key"}))
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
public class IdempotencyKey {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.UUID)
|
||||
private UUID id;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private UUID userId;
|
||||
|
||||
|
||||
@Column(name = "chat_id", nullable = false)
|
||||
private UUID chatId;
|
||||
|
||||
@Column(name = "idempotency_key", nullable = false)
|
||||
private String idempotencyKey;
|
||||
|
||||
@Column(name = "request_hash", nullable = false)
|
||||
private String requestHash;
|
||||
|
||||
@Column(name = "message_id", nullable = false)
|
||||
private UUID messageId;
|
||||
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package org.example.model;
|
||||
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "messages")
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
|
||||
public class Message {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.UUID)
|
||||
private UUID id;
|
||||
|
||||
@Column(name = "chat_id", nullable = false)
|
||||
@JsonProperty("chat_id")
|
||||
private UUID chatId;
|
||||
|
||||
@Column(name = "sender_id", nullable = false)
|
||||
@JsonProperty("sender_id")
|
||||
private UUID senderId;
|
||||
|
||||
@Column(nullable = false, columnDefinition = "TEXT")
|
||||
private String text;
|
||||
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
@JsonProperty("created_at")
|
||||
private Instant createdAt;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package org.example.model;
|
||||
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "sessions")
|
||||
@Getter
|
||||
@Setter
|
||||
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
public class Session {
|
||||
|
||||
@Id
|
||||
private UUID id;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private UUID userId;
|
||||
|
||||
@Column(name = "token", nullable = false, unique = true, length = 64)
|
||||
private String token;
|
||||
|
||||
@Column(name = "expires_at", nullable = false)
|
||||
private Instant expiresAt;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(name = "revoked_at")
|
||||
private Instant revokedAt;
|
||||
|
||||
@PrePersist
|
||||
void prePersist() {
|
||||
if (id == null) {
|
||||
id = UUID.randomUUID();
|
||||
}
|
||||
if (createdAt == null) {
|
||||
createdAt = Instant.now();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isActive(Instant now) {
|
||||
return revokedAt == null && expiresAt.isAfter(now);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package org.example.model;
|
||||
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
@Setter
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Builder
|
||||
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.UUID)
|
||||
private UUID id;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 64)
|
||||
private String username;
|
||||
|
||||
@Column(name = "display_name", nullable = false, length = 128)
|
||||
@JsonProperty("display_name")
|
||||
private String displayName;
|
||||
|
||||
@JsonIgnore
|
||||
@Column(name = "password")
|
||||
private String password;
|
||||
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
@JsonProperty("created_at")
|
||||
private Instant createdAt;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package org.example.repository;
|
||||
|
||||
import org.example.model.ChatMember;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface ChatMemberRepository extends JpaRepository<ChatMember, UUID> {
|
||||
List<ChatMember> findByUserId(UUID userId);
|
||||
List<ChatMember> findByChatId(UUID chatId);
|
||||
boolean existsByChatIdAndUserId(UUID chatId, UUID userId);
|
||||
}
|
||||
@@ -0,0 +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);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package org.example.repository;
|
||||
|
||||
import org.example.model.IdempotencyKey;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface IdempotencyKeyRepository extends JpaRepository<IdempotencyKey, UUID> {
|
||||
Optional<IdempotencyKey> findByUserIdAndChatIdAndIdempotencyKey(
|
||||
UUID userId,
|
||||
UUID chatId,
|
||||
String idempotencyKey
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package org.example.repository;
|
||||
|
||||
import org.example.model.Message;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
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> 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 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);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package org.example.repository;
|
||||
|
||||
import org.example.model.Session;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface SessionRepository extends JpaRepository<Session, UUID> {
|
||||
Optional<Session> findByToken(String token);
|
||||
void deleteByUserId(UUID userId);
|
||||
List<Session> findByUserIdOrderByCreatedAtDesc(UUID userId);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package org.example.repository;
|
||||
|
||||
import org.example.model.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, UUID> {
|
||||
boolean existsByUsername(String username);
|
||||
Optional<User> findByUsername(String username);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package org.example.service;
|
||||
|
||||
import org.example.config.TokenHasher;
|
||||
import org.example.dto.response.SessionInfoResponse;
|
||||
import org.example.dto.response.SessionResponse;
|
||||
import org.example.dto.response.UserResponse;
|
||||
import org.example.exception.UnauthorizedException;
|
||||
import org.example.model.Session;
|
||||
import org.example.model.User;
|
||||
import org.example.repository.SessionRepository;
|
||||
import org.example.repository.UserRepository;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Service
|
||||
public class AuthService {
|
||||
private final UserRepository userRepository;
|
||||
private final SessionRepository sessionRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final UserService userService;
|
||||
private final CacheService cacheService;
|
||||
private final ConcurrentHashMap<String, Object> locks = new ConcurrentHashMap<>();
|
||||
|
||||
@Value("${app.session-ttl-seconds:604800}")
|
||||
private long sessionTtlSeconds;
|
||||
|
||||
public AuthService(
|
||||
UserRepository userRepository,
|
||||
SessionRepository sessionRepository,
|
||||
PasswordEncoder passwordEncoder,
|
||||
UserService userService,
|
||||
CacheService cacheService
|
||||
) {
|
||||
this.userRepository = userRepository;
|
||||
this.sessionRepository = sessionRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.userService = userService;
|
||||
this.cacheService = cacheService;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public SessionResponse login(String username, String rawPassword) {
|
||||
User user = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new UnauthorizedException("Unauthorized"));
|
||||
|
||||
if (user.getPassword() == null
|
||||
|| !passwordEncoder.matches(rawPassword, user.getPassword())) {
|
||||
throw new UnauthorizedException("Unauthorized");
|
||||
}
|
||||
|
||||
String rawToken = TokenHasher.newRawToken();
|
||||
Instant expiresAt = Instant.now().plusSeconds(sessionTtlSeconds);
|
||||
|
||||
Session session = Session.builder()
|
||||
.userId(user.getId())
|
||||
.token(TokenHasher.sha256(rawToken))
|
||||
.expiresAt(expiresAt)
|
||||
.createdAt(Instant.now())
|
||||
.build();
|
||||
sessionRepository.save(session);
|
||||
cacheService.put(session.getToken(), user.getId(), expiresAt);
|
||||
|
||||
return SessionResponse.builder()
|
||||
.token(rawToken)
|
||||
.tokenType("Bearer")
|
||||
.expiresAt(expiresAt)
|
||||
.user(UserResponse.builder()
|
||||
.id(user.getId())
|
||||
.username(user.getUsername())
|
||||
.displayName(user.getDisplayName())
|
||||
.createdAt(user.getCreatedAt())
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void logout(String rawToken){
|
||||
if (rawToken == null || rawToken.isBlank()){
|
||||
return;
|
||||
}
|
||||
sessionRepository.findByToken(TokenHasher.sha256(rawToken))
|
||||
.ifPresent(s -> {
|
||||
s.setRevokedAt(Instant.now());
|
||||
sessionRepository.save(s);
|
||||
});
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void logoutCurrent(String rawToken) {
|
||||
String tokenHash = TokenHasher.sha256(rawToken);
|
||||
var session = sessionRepository
|
||||
.findByToken(tokenHash)
|
||||
.filter(s -> s.isActive(Instant.now()))
|
||||
.orElseThrow(() -> new UnauthorizedException("Unauthorized"));
|
||||
|
||||
session.setRevokedAt(Instant.now());
|
||||
sessionRepository.save(session);
|
||||
cacheService.deleteSession(tokenHash);
|
||||
}
|
||||
|
||||
|
||||
private final ConcurrentHashMap<String, Object> inflight = new ConcurrentHashMap<>();
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Optional<User> resolveUserByBearer(String rawToken) {
|
||||
if (rawToken == null || rawToken.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
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) {
|
||||
cachedUserId = cacheService.get(hash);
|
||||
if (cachedUserId.isPresent()) {
|
||||
return userRepository.findById(cachedUserId.get());
|
||||
}
|
||||
|
||||
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 {
|
||||
inflight.remove(hash, lock);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<SessionInfoResponse> listSessionsForCurrentUser() {
|
||||
User user = userService.getCurrentUser();
|
||||
Instant now = Instant.now();
|
||||
return sessionRepository.findByUserIdOrderByCreatedAtDesc(user.getId())
|
||||
.stream()
|
||||
.map(s -> SessionInfoResponse.builder()
|
||||
.id(s.getId())
|
||||
.createdAt(s.getCreatedAt())
|
||||
.expiresAt(s.getExpiresAt())
|
||||
.revokedAt(s.getRevokedAt())
|
||||
.active(s.isActive(now))
|
||||
.build())
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package org.example.service;
|
||||
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class CacheService {
|
||||
|
||||
private static final String PREFIX = "session:";
|
||||
private final StringRedisTemplate redis;
|
||||
|
||||
public void put(String token, UUID userId, Instant expiresAt){
|
||||
long ttlSec = Duration.between(Instant.now(), expiresAt).getSeconds();
|
||||
if (ttlSec <= 0){
|
||||
return;
|
||||
}
|
||||
try {
|
||||
redis.opsForValue().set(
|
||||
PREFIX + token,
|
||||
userId.toString(),
|
||||
ttlSec,
|
||||
TimeUnit.SECONDS
|
||||
);
|
||||
} catch (Exception e){
|
||||
log.warn("Сессия не попала в Redis");
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<UUID> get(String token){
|
||||
try {
|
||||
String v = redis.opsForValue().get(PREFIX + token);
|
||||
if (v == null || v.isBlank()){
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(UUID.fromString(v));
|
||||
} catch (Exception e){
|
||||
log.warn("Сессии нет в Redis");
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteSession(String token){
|
||||
try {
|
||||
redis.delete(PREFIX + token);
|
||||
} catch (Exception e){
|
||||
log.warn("Сессия не удалена в Redis");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package org.example.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.example.dto.ChatPage;
|
||||
import org.example.dto.create.CreateChatDto;
|
||||
import org.example.dto.response.ChatResponse;
|
||||
import org.example.dto.update.UpdateChatDto;
|
||||
import org.example.exception.NotFoundException;
|
||||
import org.example.model.Chat;
|
||||
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;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ChatService {
|
||||
|
||||
private final ChatRepository chatRepository;
|
||||
private final ChatMemberRepository chatMemberRepository;
|
||||
private final UserService userService;
|
||||
|
||||
@Transactional
|
||||
public ChatResponse createChat(CreateChatDto dto) {
|
||||
User currentUser = userService.getCurrentUser();
|
||||
UUID currentId = currentUser.getId();
|
||||
|
||||
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(
|
||||
"creator must be in member_ids");
|
||||
}
|
||||
for (UUID memberId : memberIds) {
|
||||
if (!userService.exists(memberId)) {
|
||||
throw new IllegalArgumentException("unknown member_id");
|
||||
}
|
||||
}
|
||||
|
||||
Chat chat = chatRepository.save(
|
||||
Chat.builder()
|
||||
.title(dto.getTitle())
|
||||
.build()
|
||||
);
|
||||
|
||||
for (UUID memberId : memberIds) {
|
||||
chatMemberRepository.save(
|
||||
ChatMember.builder()
|
||||
.chatId(chat.getId())
|
||||
.userId(memberId)
|
||||
.build()
|
||||
);
|
||||
}
|
||||
|
||||
return toResponse(chat.getId());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public ChatResponse getChatById(UUID chatId) {
|
||||
requireMember(chatId);
|
||||
return toResponse(chatId);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public ChatResponse getChatById(String chatId) {
|
||||
return getChatById(parseUuid(chatId));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public ChatPage getChatsForCurrentUser(int limit) {
|
||||
if (limit < 1 || limit > 100) {
|
||||
throw new IllegalArgumentException("limit must be 1..100");
|
||||
}
|
||||
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
|
||||
public ChatResponse updateChat(UUID id, UpdateChatDto object) {
|
||||
requireMember(id);
|
||||
Chat chat = chatRepository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException("Чат не найден"));
|
||||
chat.setTitle(object.getTitle());
|
||||
chatRepository.save(chat);
|
||||
return toResponse(id);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ChatResponse updateChat(String id, UpdateChatDto object) {
|
||||
return updateChat(parseUuid(id), object);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteChat(UUID id) {
|
||||
requireMember(id);
|
||||
chatRepository.deleteById(id);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteChat(String id) {
|
||||
deleteChat(parseUuid(id));
|
||||
}
|
||||
|
||||
/** Для MessageService: текущий user — участник, иначе 404 */
|
||||
@Transactional(readOnly = true)
|
||||
public void requireMember(UUID chatId) {
|
||||
User currentUser = userService.getCurrentUser();
|
||||
if (!chatRepository.existsById(chatId)
|
||||
|| !chatMemberRepository.existsByChatIdAndUserId(chatId, currentUser.getId())) {
|
||||
throw new NotFoundException("Чат не найден");
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public boolean isMember(UUID chatId, UUID userId) {
|
||||
return chatMemberRepository.existsByChatIdAndUserId(chatId, userId);
|
||||
}
|
||||
|
||||
private ChatResponse toResponse(UUID chatId) {
|
||||
Chat chat = chatRepository.findById(chatId)
|
||||
.orElseThrow(() -> new NotFoundException("Чат не найден"));
|
||||
|
||||
List<UUID> ids = chatMemberRepository.findByChatId(chatId).stream()
|
||||
.map(ChatMember::getUserId)
|
||||
.toList();
|
||||
|
||||
return ChatResponse.builder()
|
||||
.id(chat.getId())
|
||||
.title(chat.getTitle())
|
||||
.memberIds(ids)
|
||||
.createdAt(chat.getCreatedAt())
|
||||
.build();
|
||||
}
|
||||
|
||||
private static UUID parseUuid(String id) {
|
||||
try {
|
||||
return UUID.fromString(id);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new NotFoundException("Чат не найден");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package org.example.service;
|
||||
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.example.model.IdempotencyKey;
|
||||
import org.example.model.Message;
|
||||
import org.example.repository.IdempotencyKeyRepository;
|
||||
import org.example.repository.MessageRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class MessageIdempotencyWriter {
|
||||
|
||||
private final MessageRepository messageRepository;
|
||||
private final IdempotencyKeyRepository idempotencyKeyRepository;
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public Message insertNew(
|
||||
UUID chatId,
|
||||
UUID senderId,
|
||||
String text,
|
||||
String key,
|
||||
String hash) {
|
||||
|
||||
Message message = messageRepository.save(
|
||||
Message.builder()
|
||||
.chatId(chatId)
|
||||
.senderId(senderId)
|
||||
.text(text)
|
||||
.createdAt(Instant.now())
|
||||
.build()
|
||||
);
|
||||
|
||||
idempotencyKeyRepository.saveAndFlush(
|
||||
IdempotencyKey.builder()
|
||||
.userId(senderId)
|
||||
.chatId(chatId)
|
||||
.idempotencyKey(key)
|
||||
.requestHash(hash)
|
||||
.messageId(message.getId())
|
||||
.build()
|
||||
);
|
||||
return message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package org.example.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.example.dto.MessagePage;
|
||||
import org.example.dto.create.CreateMessageDto;
|
||||
import org.example.dto.update.UpdateMessageDto;
|
||||
import org.example.exception.ConflictException;
|
||||
import org.example.exception.ForbiddenException;
|
||||
import org.example.exception.NotFoundException;
|
||||
import org.example.model.IdempotencyKey;
|
||||
import org.example.model.Message;
|
||||
import org.example.repository.IdempotencyKeyRepository;
|
||||
import org.example.repository.MessageRepository;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.example.config.TokenHasher.sha256;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class MessageService {
|
||||
|
||||
private final MessageRepository messageRepository;
|
||||
private final IdempotencyKeyRepository idempotencyKeyRepository;
|
||||
private final ChatService chatService;
|
||||
private final MessageIdempotencyWriter writer;
|
||||
|
||||
@Transactional(readOnly = true) // или без write на этом уровне
|
||||
public Message sendMessage(
|
||||
UUID chatId,
|
||||
UUID senderId,
|
||||
CreateMessageDto messageObject,
|
||||
String idempotencyKey) {
|
||||
|
||||
chatService.requireMember(chatId);
|
||||
if (!chatService.isMember(chatId, senderId)) {
|
||||
throw new ForbiddenException("Пользователь не является участником чата");
|
||||
}
|
||||
|
||||
String key = idempotencyKey.trim();
|
||||
String hash = sha256(messageObject.getText());
|
||||
|
||||
Optional<IdempotencyKey> exists =
|
||||
idempotencyKeyRepository.findByUserIdAndChatIdAndIdempotencyKey(senderId, chatId, key);
|
||||
|
||||
if (exists.isPresent()) {
|
||||
return messageFromIdem(exists.get(), hash);
|
||||
}
|
||||
|
||||
try {
|
||||
return writer.insertNew(chatId, senderId, messageObject.getText(), key, hash);
|
||||
} catch (DataIntegrityViolationException e) {
|
||||
IdempotencyKey rec = idempotencyKeyRepository
|
||||
.findByUserIdAndChatIdAndIdempotencyKey(senderId, chatId, key)
|
||||
.orElseThrow(() -> e);
|
||||
return messageFromIdem(rec, hash);
|
||||
}
|
||||
}
|
||||
|
||||
private Message messageFromIdem(IdempotencyKey row, String hash) {
|
||||
if (!row.getRequestHash().equals(hash)) {
|
||||
throw new ConflictException("Idempotency key conflict");
|
||||
}
|
||||
return messageRepository.findById(row.getMessageId())
|
||||
.orElseThrow(() -> new IllegalStateException("idempotency message missing"));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public MessagePage getMessage(UUID chatId, UUID userId, String cursor, int limit) {
|
||||
if (limit < 1 || limit > 100) {
|
||||
throw new IllegalArgumentException("limit must be between 1 and 100");
|
||||
}
|
||||
|
||||
chatService.requireMember(chatId);
|
||||
if (!chatService.isMember(chatId, userId)) {
|
||||
throw new NotFoundException("Чат не найден");
|
||||
}
|
||||
|
||||
Pageable pageable = PageRequest.of(0, limit);
|
||||
List<Message> items;
|
||||
|
||||
if (cursor == null || cursor.isBlank()) {
|
||||
items = messageRepository.findByChatIdOrderByCreatedAtAscIdAsc(chatId, pageable);
|
||||
} else {
|
||||
UUID cursorId;
|
||||
try {
|
||||
cursorId = UUID.fromString(cursor.trim());
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new IllegalArgumentException("Invalid cursor");
|
||||
}
|
||||
|
||||
Message cursorMsg = messageRepository.findByIdAndChatId(cursorId, chatId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Invalid cursor"));
|
||||
|
||||
items = messageRepository.findNextPage(
|
||||
chatId,
|
||||
cursorMsg.getCreatedAt(),
|
||||
cursorMsg.getId(),
|
||||
pageable
|
||||
);
|
||||
}
|
||||
|
||||
String nextCursor = null;
|
||||
if (items.size() == limit && !items.isEmpty()) {
|
||||
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);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public MessagePage getMessage(String chatId, String userId, String cursor, int limit){
|
||||
return getMessage(parseUuid(chatId, true), parseUuid(userId, false), cursor, limit);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Message updateMessage(UUID chatId, UUID messageId, UUID userId, UpdateMessageDto object) {
|
||||
chatService.requireMember(chatId);
|
||||
Message message = messageRepository.findByIdAndChatId(messageId, chatId)
|
||||
.orElseThrow(() -> new NotFoundException("Сообщение не найден"));
|
||||
if (!message.getSenderId().equals(userId)){
|
||||
throw new ForbiddenException("Вы не можете редактировать чужие сообщения");
|
||||
}
|
||||
message.setText(object.getText());
|
||||
return messageRepository.save(message);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Message updateMessage(String chatId, String messageId, String userId, UpdateMessageDto object) {
|
||||
return updateMessage(
|
||||
parseUuid(chatId, true),
|
||||
parseUuid(messageId, true),
|
||||
parseUuid(userId, false),
|
||||
object);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteMessage(UUID chatId, UUID messageId, UUID userId) {
|
||||
chatService.getChatById(chatId);
|
||||
|
||||
Message msg = messageRepository.findByIdAndChatId(messageId, chatId)
|
||||
.orElseThrow(() -> new NotFoundException("Сообщение не найдено"));
|
||||
|
||||
if (!msg.getSenderId().equals(userId)) {
|
||||
throw new ForbiddenException("Вы не можете удалять сообщения других участников");
|
||||
}
|
||||
messageRepository.delete(msg);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteMessage(String chatId, String messageId, String userId) {
|
||||
deleteMessage(
|
||||
parseUuid(chatId, true),
|
||||
parseUuid(messageId, true),
|
||||
parseUuid(userId, false)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
private static UUID parseUuid(String value, boolean notFoundOnBad) {
|
||||
try {
|
||||
return UUID.fromString(value.trim());
|
||||
} catch (Exception e) {
|
||||
if (notFoundOnBad) {
|
||||
throw new NotFoundException("Не найдено");
|
||||
}
|
||||
throw new IllegalArgumentException("Invalid id");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package org.example.service;
|
||||
|
||||
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;
|
||||
import org.example.model.User;
|
||||
import org.example.repository.UserRepository;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class UserService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
@Transactional
|
||||
public User createUser(CreateUserDto userObject) {
|
||||
if (userRepository.existsByUsername(userObject.getUsername())) {
|
||||
throw new UserAlreadyExistsException("Пользователь с таким username уже существует: " + userObject.getUsername());
|
||||
}
|
||||
try {
|
||||
User user = User.builder()
|
||||
.username(userObject.getUsername())
|
||||
.displayName(userObject.getDisplayName())
|
||||
.password(passwordEncoder.encode(userObject.getPassword()))
|
||||
.build();
|
||||
return userRepository.save(user);
|
||||
} catch (DataIntegrityViolationException e){
|
||||
throw new UserAlreadyExistsException(
|
||||
"Пользователь с таким username уже есть: " + userObject.getUsername());
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public User getCurrentUser() {
|
||||
User user = UserContext.getCurrentUser();
|
||||
if (user == null) {
|
||||
throw new UnauthorizedException("Unauthorized");
|
||||
}
|
||||
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) {
|
||||
requireCurrentUser();
|
||||
return userRepository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException("Пользователь не найден"));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
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("Пользователь не найден");
|
||||
}
|
||||
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));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public boolean exists(UUID id) {
|
||||
return userRepository.existsById(id);
|
||||
}
|
||||
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public boolean exists(String id) {
|
||||
try {
|
||||
return exists(parseUuid(id));
|
||||
}catch (IllegalArgumentException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static UUID parseUuid(String id) {
|
||||
try {
|
||||
return UUID.fromString(id);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new NotFoundException("Пользователь с id: " + id + " не найден");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user