package com.lantone.interceptor.interceptor;

import com.lantone.common.constant.AuthConstant;
import com.lantone.common.service.RedisService;
import com.lantone.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
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;
import java.io.PrintWriter;

/**
 * @Description:
 * @Author songxl
 * @Date 2021/9/26
 */
@Component
public class HttpInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String uuid = httpServletRequest.getHeader(AuthConstant.UUID);
        String sessionId = httpServletRequest.getHeader(AuthConstant.SESSION_ID);
        if (StringUtil.isNotBlank(uuid)) {
            if (uuid.equals(redisService.get(AuthConstant.UUID+":"+sessionId))) {
                return true;
            }
        }
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setHeader("content-type", "text/html;charset=UTF-8");
        httpServletResponse.setStatus(403);
        PrintWriter out = httpServletResponse.getWriter();
        out.println("该请求无效被拦截");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

