package net.northking.cctp.common.feign;

import com.hzbank.testteam.autotest.dependencies.authDependency.constants.AuthDependencyConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import net.northking.cctp.common.security.SecurityHttpConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Feign全局配置
 *
 * @author xiusong.xie
 * @since 2.4
 */
public class FeignCctpConfig implements RequestInterceptor {

    private final static Logger logger = LoggerFactory.getLogger(FeignCctpConfig.class);

    @Override
    public void apply(RequestTemplate requestTemplate) {
        String token = null;
        String userId = null;
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            token = request.getHeader(SecurityHttpConstants.HEADER_AUTHENTICATION);
            userId = request.getHeader(AuthDependencyConstants.REQUEST_HEADER_USER_ID);
        }
        logger.info("feign调用添加请求头，userId:{}，token:{}",userId,token);
        //添加token
        if (token != null && userId != null) {
            requestTemplate.header(SecurityHttpConstants.HEADER_AUTHENTICATION, token);
            requestTemplate.header(AuthDependencyConstants.REQUEST_HEADER_USER_ID, userId);
        }
    }
}
