package com.njcn.interceptor;

import com.njcn.utils.AppConfig;
import com.njcn.utils.PubUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Enumeration;
import java.util.Properties;

/**
 * @author hongawen
 * @date: 2020/9/7 14:07
 */
public class CSRFInterceptor implements HandlerInterceptor {
    // 日志记录
    private static final Logger logger = LoggerFactory.getLogger(CSRFInterceptor.class);

    @Resource
    private AppConfig appConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //referer判断
        String referrer = request.getHeader("referer");
        logger.debug("referrer:{}",referrer);
        StringBuffer stringBuffer = new StringBuffer();
        String serverNameClientHost= request.getServerName();
        String serverNameIP = appConfig.getSystemHost();
        stringBuffer.append(request.getScheme()).append("://").append(serverNameClientHost);
        logger.debug("basePath:{}",stringBuffer);
        //过滤下127.0.0.1
        if(StringUtils.isEmpty(referrer) || referrer.lastIndexOf(String.valueOf(stringBuffer))==0 ){
            //当reffer和host一起乱改后，进来了，需要进行白名单处理，内部发布的时候，需要注释这块代码
//            if( !(referrer.lastIndexOf("127.0.0.1") < 0) && !(referrer.lastIndexOf("localhost") < 0) && !(referrer.lastIndexOf(serverNameIP)<0)){
//                return false;
//            }
            //token验证,只判断ajax请求
            boolean flag=isAjax(request);
            if(flag){
                //获取uri
                String requestURI = request.getRequestURI();
                String clientToken = request.getHeader("AuthToken");
                String timestamp = request.getHeader("cnsjt");
                if(clientToken.equalsIgnoreCase(PubUtils.getEncodSM3(requestURI+timestamp))){
                    return true;
                }else{
                    return false;
                }
            }else{
                return true;
            }
        } else{
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    /**
     * 是否是Ajax请求
     * @param request
     * @return
     */
    public static boolean isAjax(HttpServletRequest request){
        return  "XMLHttpRequest".equalsIgnoreCase((request).getHeader("X-Requested-With"));
    }
}
