package cn.com.victorysoft.business.filter;

import cn.com.victorysoft.business.util.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

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

/**
 * Referer验证
 *
 * @author stareast
 */
public class ReferFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String referer = request.getHeader("referer");
        String ip = request.getServerName();
        if (StringUtils.isEmpty(referer) || !(referer.contains(ip))) {
            response.setContentType("text/plain; charset=GBK");
            response.setStatus(400);
            response.getWriter().write("禁止非法访问!");
            return;
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void destroy() {

    }
}
