package com.inspect.common.security.feign;

import com.inspect.base.core.utils.ServletUtils;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.ip.IpUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;

@Component
public class FeignRequestInterceptor implements RequestInterceptor {
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest httpServletRequest = ServletUtils.getRequest();
        if (StringUtils.isNotNull(httpServletRequest)) {
            Map<String, String> headers = ServletUtils.getHeaders(httpServletRequest);
            String userId = headers.get("user_id");
            if (StringUtils.isNotEmpty(userId)) {
                requestTemplate.header("user_id", userId);
            }

            String userName = headers.get("username");
            if (StringUtils.isNotEmpty(userName)) {
                requestTemplate.header("username", userName);
            }

            String authentication = headers.get("authorization");
            if (StringUtils.isNotEmpty(authentication)) {
                requestTemplate.header("authorization", authentication);
            }

            requestTemplate.header("X-Forwarded-For", IpUtils.getIpAddr(ServletUtils.getRequest()));
        }

    }
}
