package com.github.wxiaoqi.security.auth.interceptor;

import com.github.wxiaoqi.security.auth.configuration.ClientConfiguration;
import com.github.wxiaoqi.security.auth.service.AuthClientService;
import com.github.wxiaoqi.security.common.util.ClientUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Created by ace on 2017/9/12.
 */
@Slf4j
public class ClientTokenInterceptor implements RequestInterceptor {
    private Logger logger = LoggerFactory.getLogger(ClientTokenInterceptor.class);
    @Autowired
    private ClientConfiguration clientConfiguration;
    @Autowired
    private AuthClientService authClientService;

    @Value("${auth.user.token-header:Authorization}")
    private String tokenHeader;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            requestTemplate.header(clientConfiguration.getClientTokenHeader(), authClientService.apply(clientConfiguration.getClientId(), clientConfiguration.getClientSecret()));
            requestTemplate.header("userHost", ClientUtil.getClientIp(requestAttributes.getRequest()));
            requestTemplate.header(tokenHeader,requestAttributes.getRequest().getHeader(tokenHeader));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
