package com.project.framework.interceptor;

import com.alibaba.fastjson2.JSON;
import com.project.common.core.domain.AjaxResult;
import com.project.common.utils.AESUtil;
import com.project.common.utils.ServletUtils;
import com.project.common.utils.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

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

/**
 * @Description
 * @Author bqyang
 * @Date 2025/3/6 13:59
 * @Version 1.0
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    private static final String TOKEN_KEY = "X-Access-Token";

    private static final String SECRET_KEY = "M2p5yEL67eZct7gtvT";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader(TOKEN_KEY);
        // 简单的token验证逻辑
        if (StringUtils.isBlank(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            AjaxResult ajaxResult = AjaxResult.error("token传参异常！");
            ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
            return false;
        }

        String encrToken = AESUtil.decrypt(token);
        if ( !SECRET_KEY.equals(encrToken)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            AjaxResult ajaxResult = AjaxResult.error("token传参异常！");
            ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
            return false;
        }
        return true;
    }
}
