|
| 1 | +package com.example.solidconnection.chat.config; |
| 2 | + |
| 3 | +import com.example.solidconnection.security.authentication.TokenAuthentication; |
| 4 | +import com.example.solidconnection.security.userdetails.SiteUserDetails; |
| 5 | +import java.security.Principal; |
| 6 | +import lombok.extern.slf4j.Slf4j; |
| 7 | +import org.springframework.context.annotation.Profile; |
| 8 | +import org.springframework.messaging.Message; |
| 9 | +import org.springframework.messaging.MessageChannel; |
| 10 | +import org.springframework.messaging.simp.stomp.StompCommand; |
| 11 | +import org.springframework.messaging.simp.stomp.StompHeaderAccessor; |
| 12 | +import org.springframework.messaging.support.ChannelInterceptor; |
| 13 | +import org.springframework.stereotype.Component; |
| 14 | + |
| 15 | +@Slf4j |
| 16 | +@Component |
| 17 | +@Profile("dev") |
| 18 | +public class WebSocketLoggingInterceptor implements ChannelInterceptor { |
| 19 | + |
| 20 | + @Override |
| 21 | + public Message<?> preSend(Message<?> message, MessageChannel channel) { |
| 22 | + StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message); |
| 23 | + StompCommand command = accessor.getCommand(); |
| 24 | + |
| 25 | + if (command != null) { |
| 26 | + Long userId = extractUserId(accessor); |
| 27 | + String destination = accessor.getDestination(); |
| 28 | + logStompMessage(command, destination, userId); |
| 29 | + } |
| 30 | + |
| 31 | + return message; |
| 32 | + } |
| 33 | + |
| 34 | + private void logStompMessage(StompCommand command, String destination, Long userId) { |
| 35 | + switch (command) { |
| 36 | + case CONNECT -> log.info("[WEBSOCKET] CONNECT userId = {}", userId); |
| 37 | + case SUBSCRIBE -> log.info("[WEBSOCKET] SUBSCRIBE {} userId = {}", destination, userId); |
| 38 | + case SEND -> log.info("[WEBSOCKET] SEND {} userId = {}", destination, userId); |
| 39 | + case DISCONNECT -> log.info("[WEBSOCKET] DISCONNECT userId = {}", userId); |
| 40 | + default -> { |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + private Long extractUserId(StompHeaderAccessor accessor) { |
| 46 | + Principal user = accessor.getUser(); |
| 47 | + if (user instanceof TokenAuthentication tokenAuth) { |
| 48 | + Object principal = tokenAuth.getPrincipal(); |
| 49 | + if (principal instanceof SiteUserDetails details) { |
| 50 | + return details.getSiteUser().getId(); |
| 51 | + } |
| 52 | + } |
| 53 | + return null; |
| 54 | + } |
| 55 | +} |
0 commit comments