package org.springblade.common.interceptor;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.springblade.sing.desk.enums.IpBlackType;
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;

/**
 * @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();
	}

	/**
	 * 拦截IP黑名单
	 *
	 * @param request
	 * @param response
	 * @param handler
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String type = Convert.convert(String.class, bladeRedis.hGet(IPInterceptorConstant.CACHE_KEY, IPUtils.getRealIp(request)), null);
		if (StringUtils.isNotEmpty(type) && StringUtils.equals(IpBlackType.REFUSE.name(),type)) {
			IoUtil.writeUtf8(response.getOutputStream(), true, JSONObject.toJSONString(R.fail("您已经被拉入黑名单，无法访问")));
			return false;
		}
		return true;
	}
}
