package com.ruoyi.web.modules.openstats.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.web.modules.openstats.constant.OpenStatsConstants;
import com.ruoyi.web.modules.openstats.support.OpenStatsTokenSupport;

/**
 * 商城数据统计 Open API Token 校验
 */
@Component
public class OpenStatsTokenFilter extends OncePerRequestFilter
{
    @Autowired
    private OpenStatsTokenSupport tokenSupport;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        String token = request.getHeader(OpenStatsConstants.TOKEN_HEADER);
        if (!tokenSupport.isValidToken(token))
        {
            AjaxResult result = AjaxResult.error(HttpStatus.UNAUTHORIZED, "无效的访问令牌");
            ServletUtils.renderString(response, JSON.toJSONString(result));
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        chain.doFilter(request, response);
    }
}
