package com.mortals.xhx.base.framework.filter;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 
 * 请求过滤链
 * @author: zxfei
 * @date: 2022/4/20 14:52
 */
//@Component
@Slf4j
public class RequestFilter extends OncePerRequestFilter implements Filter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            request = new ContentCachingRequestWrapper(request);
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            throw e;
        } finally {
            //清理ThreadLocal
            MDC.clear();
        }
    }


    /*private void setUsername(HttpServletRequest request) {
        //通过token解析出username
        String token = authTokenService.getToken(request);
        //String token = request.getHeader("token");
        if (!ObjectUtils.isEmpty(token)) {
            MDC.put("token",token);
            MDC.put("token", token);
            try {
                SessionUserInfo info = tokenService.getUserInfo();
                if (info != null) {
                    String username = info.getUsername();
                    MDC.put("username", username);
                }
            } catch (CommonJsonException e) {
                log.info("无效的token:{}", token);
            }
        }
    }*/
}
