package com.yutou.tools.utils;

import com.yutou.tools.mybatis.dao.UKeyDao;
import com.yutou.tools.mybatis.model.UKeyExample;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@Component
@WebFilter
public class APIFilter implements Filter {
    @Resource
    UKeyDao keyDao;
    @Resource
    RedisTools redisTools;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        String token = request.getParameter("token");
        Cookie cookie = Tools.getCookie(request, "user");
        System.out.println("接收到请求：" + request.getRequestURI() + " " + token);
        boolean isToken = false;
        boolean isCookie = false;
        if (!StringUtils.isEmpty(token)) {
            UKeyExample example = new UKeyExample();
            example.createCriteria().andKeyEqualTo(token);
            if (keyDao.selectByExample(example).size() > 0) {
                isToken = true;
            }
        }
        if (cookie != null) {
            if ("ok".equals(redisTools.get(cookie.getValue()))) {
                isCookie = true;
            }
        }
        if (!isToken) {
            System.out.println("token验证不通过:" + token);
        } else if (!isCookie) {
            System.out.println("请求无令牌，拦截");
        }
        if (!isCookie && !isToken) {
            //response.sendRedirect("/");
            if(!request.getRequestURI().contains("/login/")){
                response.sendRedirect("/");
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
