package com.cftech.sys.filter;

import com.cftech.core.config.MpGlobalConfig;
import com.cftech.core.jwt.JWTStatus;
import com.cftech.core.util.JWTUtils;
import com.cftech.core.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.security.web.firewall.StrictHttpFirewall;
import org.springframework.security.web.util.matcher.RegexRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Pattern;

/**
 * CSRFToken 取消针对移动端的设置
 * Created by Jasper Huang on 2018/6/1.
 */
    public class CsrfSecurityRequestMatcher implements RequestMatcher {
    private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
    private RegexRequestMatcher unprotectedMatcher = new RegexRequestMatcher("^(/assets/|/static/|/mobile/|/a/materialUpload/upload*).*", null);
    private static Logger logger = LoggerFactory.getLogger(CsrfSecurityRequestMatcher.class);

    @Override
    public boolean matches(HttpServletRequest request) {
        //查看来源的REFER 是否是域名发起的
        if("GET".equals(request.getMethod()))
        {
            String refer = request.getHeader("Referer");
            if(StringUtils.isNotBlank(refer))
            {
                try {
                    String remoteHost = new URL(refer).getHost();
                    if((!MpGlobalConfig.JWT_DOMAIN.equals(remoteHost)))
                    {
                        return true;
                    }
                } catch (MalformedURLException e) {
                    logger.error("PC后台转换Refer异常",e);
                }
            }
        }
        if(allowedMethods.matcher(request.getMethod()).matches()){
            return false;
        }
//        System.out.print( request.getPathInfo());
//        if(request.getRequestURI().endsWith(request.getContextPath())||
//                request.getRequestURI().endsWith(request.getContextPath()+"/")||
//                request.getRequestURI().endsWith(request.getContextPath()+"/page/login"))
//        {
//            return false;
//        }
        return !unprotectedMatcher.matches(request);
    }
}
