package com.njzscloud.common.mvc.ws.support;

import cn.hutool.core.lang.Assert;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.security.support.Token;
import com.njzscloud.common.security.support.UserDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;

import java.security.Principal;

/**
 * 消息拦截器
 */
@Slf4j
public class WebSocketChannelInterceptor implements ChannelInterceptor {

    /**
     * 消息发送之前
     */
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel messageChannel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);

        // 心跳消息
        Object header = accessor.getHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER);
        if (SimpMessageType.HEARTBEAT.name().equals(header)) return message;

        Principal user = accessor.getUser();

        Assert.notNull(user, () -> Exceptions.exception("未登录，不能发送消息"));

        UserDetail userDetail = (UserDetail) user;
        Token token = userDetail.getToken();

        Assert.isFalse(token.isExpired(), () -> Exceptions.exception("登录已过期，不能发送消息"));

        return message;
    }
}

