package com.skr.mdm.filter;

import com.skr.mdm.authentication.user.IllegalUserRequestException;
import com.skr.mdm.authentication.user.UserAuthenticationEntryPoint;
import com.skr.mdm.authentication.user.UserTimeCheckException;
import com.skr.mdm.util.AntiReplayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
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;
import java.util.ArrayList;
import java.util.List;

/**
 * 重放攻击过滤器
 *
 * @author nfq
 * @date 2021/4/12 16:21
 */
@Component
@Slf4j
public class UserPreventReplayFilter extends OncePerRequestFilter {

    private static final List<String> IGNORE_URI_LIST = new ArrayList<>();

    static {
        IGNORE_URI_LIST.add("webjars");
        IGNORE_URI_LIST.add("swagger-resources");
        IGNORE_URI_LIST.add("v2");
        IGNORE_URI_LIST.add("swagger-ui.html");
        IGNORE_URI_LIST.add("doc.html");
        IGNORE_URI_LIST.add("druid");
        IGNORE_URI_LIST.add("favicon.ico");
        IGNORE_URI_LIST.add("mdm/actuator");
    }

    @Autowired
    private AntiReplayUtil antiReplayUtil;
    @Autowired
    private UserAuthenticationEntryPoint userAuthenticationEntryPoint;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestUri = request.getRequestURI();
        for (String uri : IGNORE_URI_LIST) {
            if (requestUri.contains(uri)) {
                filterChain.doFilter(request, response);
                return;
            }
        }
        try {
            // 防重放
            antiReplayUtil.userAntiReplay(request);
        } catch (IllegalUserRequestException | UserTimeCheckException e) {
            log.warn("重放校验失败");
            userAuthenticationEntryPoint.commence(request, response, e);
            return;
        }
        filterChain.doFilter(request, response);
    }
}
