package com.dashitech.config;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * API-rest服务拦截器 <br/>
 * 对请求进行ip校验,出错返回拒绝信息
 */
public class ApiFilterConfig extends HandlerInterceptorAdapter {
    private static Log log = LogFactory.getLog(ApiFilterConfig.class);

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

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

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");

//        HandlerMethod hm = (HandlerMethod) handler;
//        String visitMethod = hm.getMethod().getName();

        //校验
        boolean flag = check(request.getRemoteHost());

        //验证失败，拒绝请求
  /*      if (!flag) {
            MessageResult result = new MessageResult();
            result.setSuccess(false);
            result.setMsg("403 forbidden");
            response.getWriter().print(JsonUtil.toJsonString(result));
        }else {
            log.error("ApiFilter Check Error："+ request.getRequestURL().toString() + "  IP："+ request.getRemoteAddr());
        }*/

        return flag;
    }

    private boolean check(String ip) {
//        if (StringUtils.isNotEmpty(ip) && (ip.equals("127.0.0.1") || ip.equals("localhost") || ip.equals("0:0:0:0:0:0:0:1"))) {
//            return true;
//        }
//        return false;
        return true;
    }
}