package io.github.qifan777.knowledge.interceptor;

import io.github.qifan777.knowledge.context.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * <p>
 *
 * </p>
 *
 * @author taohongrun
 * @since 2024/12/4
 */
public class LoginInterceptor implements HandlerInterceptor {
   private ValueOperations<String,String> valueOperations;

    public LoginInterceptor(ValueOperations valueOperations) {
        this.valueOperations = valueOperations;
    }

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

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取redis用户信息
        //cookie格式为token=xxxxx
        //获取token
        String token = request.getHeader("Cookie").split("=")[1];

        String userId = valueOperations.get(token);
        if(userId.isEmpty()) return false;
        UserContext.setThreadUserId(userId);
        return true;
    }
}
