package org.springblade.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import org.springblade.common.utils.IPUtils;
import org.springblade.core.log.logger.BladeLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

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

/**
 * 拦截站外请求过滤器
 */
@Component
public class ExteriorRequestHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    private BladeLogger logger;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestStr = request.getHeader("referer");
        if (requestStr == null) {
            responseWrite(response,"{\"request\":\"error\",\"msg\":\"非法或恶意请求\"}");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("serverName", request.getServerName());
            jsonObject.put("uri", request.getRequestURI());
            String ip = IPUtils.getIP(request);
            jsonObject.put("ip", ip);
            logger.warn("【非法或恶意请求】", jsonObject.toJSONString());
            return false;
        }
        return true;
    }

    public void responseWrite(HttpServletResponse response,String resStr){
        PrintWriter writer=null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer=response.getWriter();
            writer.print(resStr);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (writer!=null) writer.close();
        }
    }
}
