package com.jiayue.ssi.filter;

import com.jiayue.ssi.util.InterfaceLimitUtil;
import com.jiayue.ssi.util.ResponseVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 接口访问限制过滤器
 *
 * @author xsl
 * @since 2023/02/24
 */
@RequiredArgsConstructor
@Order(1)
@Slf4j
public class InterfaceLimitFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
        if (!InterfaceLimitUtil.checkInterface(request, 1000, 1)) {
            log.error("接口拦截：{} 请求超过限制频率【{}次/{}ms】,IP为{}", request.getRequestURI(), 1000, 1, request.getRemoteAddr());
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setStatus(401);
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("请求过于频繁，请稍后再试！");
            return;
        }
        filterChain.doFilter(request, response);
    }
}
