Files
nahodka-back/src/main/java/com/krylov/refound/util/WsStompInterceptor.java
2026-10-11 23:26:11 +03:00

176 lines
7.0 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.krylov.refound.util;
import com.krylov.refound.security.JwtService;
import com.krylov.refound.service.ChatService;
import com.krylov.refound.service.UserService;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class WsStompInterceptor implements ChannelInterceptor {
private static final String USER_ID_ATTR = "userId";
private static final String ROLE_ATTR = "role";
/** /topic/chat/{chatId} */
private static final Pattern CHAT_TOPIC = Pattern.compile("^/topic/chat/(\\d+)$");
/** /topic/user/{userId}/unread */
private static final Pattern UNREAD_TOPIC = Pattern.compile("^/topic/user/(\\d+)/unread$");
/** /user/{userId}/queue/** — личная очередь одного пользователя */
private static final Pattern USER_QUEUE = Pattern.compile("^/user/[^/]+/queue/.+$");
private final JwtService jwtService;
private final UserService userService;
// ChatService тянет SimpMessagingTemplate, а тот — конфигурацию WebSocket,
// в которую регистрируется этот же интерцептор. Без @Lazy получается цикл.
private final ChatService chatService;
public WsStompInterceptor(JwtService jwtService, UserService userService,
@Lazy ChatService chatService) {
this.jwtService = jwtService;
this.userService = userService;
this.chatService = chatService;
}
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
if (StompCommand.CONNECT.equals(accessor.getCommand())) {
handleConnect(accessor);
} else if (StompCommand.SUBSCRIBE.equals(accessor.getCommand())) {
handleSubscribe(accessor);
}
return message;
}
private void handleConnect(StompHeaderAccessor accessor) {
String authorization = accessor.getFirstNativeHeader("Authorization");
if (authorization == null || !authorization.startsWith("Bearer ")) {
throw new IllegalArgumentException("Missing Authorization header");
}
String token = authorization.substring(7);
if (!jwtService.isTokenValid(token)) {
throw new IllegalArgumentException("Invalid JWT token");
}
String login = jwtService.extractLogin(token);
// getUserIdByLogin бросает 404, если пользователя нет
Long userId = userService.getUserIdByLogin(login);
String role = jwtService.extractRole(token);
if (role == null) {
role = userService.getRoleByLogin(login);
}
accessor.getSessionAttributes().put(USER_ID_ATTR, userId);
accessor.getSessionAttributes().put(ROLE_ATTR, role);
// Таймзону присылает клиент на CONNECT; применяется при сохранении Message
String timezone = accessor.getFirstNativeHeader(TimeZoneContext.WS_HEADER);
if (timezone != null) {
accessor.getSessionAttributes().put(TimeZoneContext.SESSION_ATTRIBUTE, timezone);
}
log.info("WS connected: userId={} role={}", userId, role);
}
/**
* Авторизация подписки. Без неё любой авторизованный пользователь может читать
* чужие чаты и счётчики непрочитанных сообщений, подписавшись на их топики.
*/
private void handleSubscribe(StompHeaderAccessor accessor) {
String destination = accessor.getDestination();
Long userId = userIdFromSession(accessor);
String role = roleFromSession(accessor);
if (userId == null) {
log.warn("Subscribe без CONNECT: destination={}", destination);
throw new MessagingException("Ошибка авторизации");
}
if (isAdminsOnly(destination)) {
if (!isAdmin(role)) {
log.warn("Попытка подписки на служебный канал '{}' пользователем с ролью {}", destination, role);
throw new MessagingException("Доступ запрещён");
}
return;
}
Matcher unread = UNREAD_TOPIC.matcher(destination);
if (unread.matches()) {
Long targetUserId = Long.valueOf(unread.group(1));
if (!userId.equals(targetUserId)) {
log.warn("Попытка подписки на чужой счётчик непрочитанных: userId={} target={}", userId, targetUserId);
throw new MessagingException("Доступ запрещён");
}
return;
}
if (USER_QUEUE.matcher(destination).matches()) {
String[] parts = destination.split("/");
if (parts.length < 3 || !userId.toString().equals(parts[2])) {
log.warn("Попытка подписки на чужую личную очередь: userId={} destination={}", userId, destination);
throw new MessagingException("Доступ запрещён");
}
return;
}
Matcher chat = CHAT_TOPIC.matcher(destination);
if (chat.matches()) {
Long chatId = Long.valueOf(chat.group(1));
if (!chatService.isParticipant(chatId, userId)) {
log.warn("Пользователь {} не участник чата {} — подписка запрещена", userId, chatId);
throw new MessagingException("Доступ запрещён");
}
return;
}
// Неизвестные топики закрыты по умолчанию: иначе появится канал,
// который случайно разрешит чужие данные.
log.warn("Подписка на неизвестный канал '{}' пользователем {}", destination, userId);
throw new MessagingException("Доступ запрещён");
}
private boolean isAdminsOnly(String destination) {
return destination != null
&& (destination.startsWith("/topic/ads") || destination.startsWith("/topic/fullscreen-ads"));
}
private boolean isAdmin(String role) {
return "ADMIN".equalsIgnoreCase(role);
}
private Long userIdFromSession(StompHeaderAccessor accessor) {
if (accessor.getSessionAttributes() == null) {
return null;
}
Object value = accessor.getSessionAttributes().get(USER_ID_ATTR);
return value instanceof Long id ? id : null;
}
private String roleFromSession(StompHeaderAccessor accessor) {
if (accessor.getSessionAttributes() == null) {
return null;
}
Object value = accessor.getSessionAttributes().get(ROLE_ATTR);
return value instanceof String role ? role : null;
}
}