package cn.reghao.oss.store.inerceptor;

import cn.reghao.jutil.web.ServletUtil;
import cn.reghao.oss.store.service.StoreLocalService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 访问日志拦截器
 *
 * @author reghao
 * @date 2021-12-30 12:19:07
 */
@Slf4j
@Component
public class AccessLogInterceptor implements HandlerInterceptor {
    private final StoreLocalService storeLocalService;

    public AccessLogInterceptor(StoreLocalService storeLocalService) {
        this.storeLocalService = storeLocalService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        String method = request.getMethod();
        if (method.equalsIgnoreCase("HEAD")) {
            return true;
        }

        String userAgent = request.getHeader("user-agent");
        String ipv4 = request.getRemoteAddr();
        String referer = request.getHeader("referer");
        String client = ServletUtil.getRequestParam("client", "");
        if (!client.isBlank()) {
            return true;
        }

        String referFrom = storeLocalService.getReferer();
        String objectName = uri.replaceFirst("/", "");
        if (objectName.startsWith("img/")) {
            return true;
        } else if (referer == null || (referFrom != null && !referer.contains(referFrom))) {
            log.error("request object {} from {} has been blocked", uri, referer);
            response.setStatus(403);
            return false;
        }

        return true;
    }

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

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