package com.springboot.cloud.common.web.interceptor;

/*
 **********************************************
 *      DATE           PERSON       REASON
 *    2020-12-04          FXY        Created
 **********************************************
 */


import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.util.Collection;
import java.util.Map;


@Slf4j
public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {

    public FeignBasicAuthRequestInterceptor(){
        log.info("========================加载自定义拦截器=========================");
    }

    //服务间调用头
    private static final String SERVER_CLIENT_TOKEN="server-client-token";
    //服务间调用秘钥
    private static final String SERVER_CLIENT_SECRET="server";
    //网关调用服务头
    private static final String X_CLIENT_TOKEN="x-client-token";

    @Override
    public void apply(RequestTemplate requestTemplate) {
        String url = requestTemplate.path();
        Map<String, Collection<String>> headers = requestTemplate.headers();
        if(!headers.containsKey(X_CLIENT_TOKEN)){
            String method = requestTemplate.method();
            String originStr = new StringBuilder().append(url).append(method).append(SERVER_CLIENT_TOKEN).append(SERVER_CLIENT_SECRET).toString();
            // 加入自定义头信息
            String md5Secret = DigestUtils.md5DigestAsHex(originStr.getBytes());
            requestTemplate.header(SERVER_CLIENT_TOKEN, md5Secret);
        }
    }
}