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 */
            if (authToken == null) {
                authToken = request.getParameter("token");
            }
            template.header("X-Access-Token", authToken);
            template.header("token", authToken);
            template.header("appKey", request.getHeader("appKey"));
            template.header("product", request.getHeader("product"));
        }
    }
}
