package com.zfire.jiasm.syncdata.config.filter;

import com.zfire.jiasm.syncdata.utils.ApplicationContextUtils;
import com.zfire.jiasm.syncdata.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class WebsocketFilter implements Filter {

    private static final String TOKEN_KEY = "Sec-WebSocket-Protocol";

    RedisUtil redisUtil;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (redisUtil == null) {
            redisUtil = ApplicationContextUtils.getBean(RedisUtil.class);
        }
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String token = request.getHeader(TOKEN_KEY);

        log.info("websocket连接 Token安全校验，Path = {}，token:{}", request.getRequestURI(), token);

        try {
            // 校验用户token
//            AdminUserCom adminUserCom = (AdminUserCom) redisUtil.get(Constant.RedisPrefix.TOKEN_MGR + token);
//            if(Objects.isNull(adminUserCom)) {
//                throw new RemoteException("token非法无效!");
//            }
        } catch (Exception exception) {
            log.error("websocket连接校验失败，{}，token:{}", exception.getMessage(), token);
            return;
        }
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        response.setHeader(TOKEN_KEY, token);
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
