package com.yeejoin.amos.boot.biz.common.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author DELL
 */
public class FeignAuthRequestInterceptor implements RequestInterceptor {
    public FeignAuthRequestInterceptor() {

    }

    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            /* Get token from header */
            String authToken = StringUtils.isEmpty(request.getHeader("X-Access-Token")) ? request.getHeader("token") : request.getHeader("X-Access-Token");
            /* If token not found get it from request parameter */
            String appKey =  request.getHeader("appKey");
            String product =  request.getHeader("product");
            if (authToken == null) {
                authToken = request.getParameter("token");
            }
            if (appKey == null) {
                appKey = request.getParameter("appKey");
            }
            if (product == null) {
                product = request.getParameter("product");
            }
            template.header("X-Access-Token", authToken);
            template.header("token", authToken);
            template.header("appKey", appKey);
            template.header("product", product);
        }
    }
}
