package org.springblade.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.constant.IPInterceptorConstant;
import org.springblade.common.utils.IPUtils;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.tool.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author: Silent
 * @Description
 * @Date: Created in 16:56 2021/11/16
 * @Modified By:
 */
@Slf4j
public class IPInterceptor implements HandlerInterceptor {
	@Autowired
	private BladeRedis bladeRedis;

	@PostConstruct
	public void init(){
		IPUtils.addToRedis();
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		Map<String,String> map = bladeRedis.hGetAll(IPInterceptorConstant.CACHE_KEY);
		if(map.containsKey(IPUtils.getRealIp(request))){
			response.setContentType("application/json;charset=utf-8");
			response.getWriter().write(JSONObject.toJSONString(R.fail("您已经被拉入黑名单，无法访问")));
			return false;
		}
		return true;
	}
}
