package com.mx.cneeds.server.datashow.config;

import com.mx.cneeds.common.converter.RequestParamterConverter;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName FeignConfig
 * @Author zzrdark
 * @Date 2020-03-04 17:26
 * @Description TODO
 **/
@Configuration
@Slf4j
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {

        //只支持 servlet
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if(requestAttributes == null){
            return;
        }
        HttpServletRequest request = requestAttributes.getRequest();

        if (request.getRequestURL().toString().contains("/user/login")){
            String authString = RequestParamterConverter.authorizationConverter("clientapp","112233");
            requestTemplate.header("Authorization",authString);
        }else{
            requestTemplate.query("login_username",username);
        }

    }
}
