package com.changfa.config.interceptor;

import com.changfa.config.interceptor.properties.RefererProperties;
import com.changfa.config.shiro.ShiroProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class RefererInterceptor implements HandlerInterceptor {

    @Autowired
    private RefererProperties refererProperties;
    @Autowired
    private ShiroProperties shiroProperties;
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) {
        String method = req.getMethod();
        String referer = req.getHeader("referer");
        if("POST".equals(method) || "GET".equals(method)){
            if(!StringUtils.hasLength(referer)){
                // 状态置为404
              List<String> ignoreList =  shiroProperties.getIgnoreAuthc();
              if(!ObjectUtils.isEmpty(ignoreList)){
                  if(ignoreList.contains(req.getRequestURI().replace(req.getContextPath(),""))){
                      return true;
                  }
              }
                resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return false;
            }
            List<String> list = refererProperties.getRefererDomain();
            if(!ObjectUtils.isEmpty(list)){
                try{
                    referer =  referer.split(":")[1].replace("//","");
                    if(!list.contains(referer)){
                        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
                        return false;
                    }
                }catch (Exception e){

                }
            }
        }
        return true;
    }
}
