package top.weiyuexin.interceptor;

import cn.hutool.crypto.digest.DigestUtil;
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 top.weiyuexin.service.UserService;

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

/**
 * @PackageName: top.weiyuexin.interceptor
 * @ProjectName: oj-spring-boot
 * @ClassName: LoginInterceptor
 * @Author: Weiyuexin
 * @Email: 3022422894@qq.com
 * @Date: 2023/4/27 17:19
 */


public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        String username=null;
        String password=null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("username")){
                username=cookie.getValue();
            }
            if (cookie.getName().equals("password")){
                password=cookie.getValue();
            }
        }
        System.out.println(username+"  "+password);
        if (username==null || password==null || userService.getByNameAndPasswordAndIsAdmin(username, DigestUtil.md5Hex(password))==null){
            response.sendRedirect("/login");
            return false;
        }
//        //未登录，跳转到登录页
//        if (request.getCookies() == null || true) {
//            response.sendRedirect("/login");
//        }
        return true;
    }

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

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
