package com.qiuguo.iot.gateway.config;

import com.qiuguo.iot.gateway.config.properties.CorsProperties;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 全局跨域配置.
 *
 */
// @AutoConfiguration
// @EnableConfigurationProperties(CorsProperties.class)
public class GlobalCorsConfiguration {
    
    /**
     * 允许跨域调用的过滤器.
     *
     * @param corsProperties 跨域配置
     */
    // @Bean
    // @ConditionalOnMissingBean(CorsFilter.class)
    public CorsFilter corsFilter(CorsProperties corsProperties) {
        CorsConfiguration config = new CorsConfiguration();
        // 设置允许跨域访问的域名
        config.setAllowedOriginPatterns(corsProperties.getAllowedOriginPatterns());
        // 设置允许跨域访问的方法
        config.setAllowedMethods(corsProperties.getAllowedMethods());
        // 设置允许跨域访问的请求头
        config.setAllowedHeaders(corsProperties.getAllowedHeaders());
        config.setExposedHeaders(corsProperties.getExposedHeaders());
        // 允许跨越发送cookie
        config.setAllowCredentials(corsProperties.getAllowCredentials());
        config.setMaxAge(corsProperties.getMaxAge());
        
        // 对接口配置跨域设置
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
