package com.yunniu.farming.interceptor;

import com.yunniu.farming.webadmin.model.Admin;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

@Component
@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter {

//    @Resource
    //    RedisUtil redisUtil;

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

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

    /**
     * 进入controller前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //log.info("############进入用户拦截器");
        String uri = request.getRequestURI();
//        if (uri.contains("/app/")) {
//            String token = request.getHeader("token");
//            if (null != token && !token.equals("")) {
//                if(redisUtil.get(token)!=null){
//                    return true;
//                }
//            }
//            throw new TokenException();
////            return true;
//        }
        log.info(uri);
        Admin user = (Admin) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
        if (user == null && !"/confirmUser".equals(uri)) {
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        }
        return true;
    }
}
