package com.weiqi.mis.interceptor;

import com.weiqi.mis.annotation.LoginRequired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

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

/**
 * @author zzn
 * @date 2020/2/12 12:33
 */
@Component
public class AnotationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(123);
        LoginRequired anno = null;
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            if (handlerMethod.getMethod().isAnnotationPresent(LoginRequired.class)) {
                anno = handlerMethod.getMethod().getAnnotation(LoginRequired.class);
            } else if (handlerMethod.getBeanType().isAnnotationPresent(LoginRequired.class)) {
                anno = handlerMethod.getBeanType().getAnnotation(LoginRequired.class);
            }
        }

        if (anno != null) {
            Object token = request.getSession().getAttribute("Token");
            if (token != null){
                return true;
            }else {
                response.sendRedirect("/mis/login");
                return false;
            }
        }else{//因为现在域名没有edit，所以获取不到cookie 暂时放开所有校验，之后将else注释掉即可
            return true;
        }
    }
}
