package com.seer.teach.filter.cors;

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class CorsConfig {

    @Bean
    @ConfigurationProperties(prefix = "zs.cors")
    public Cors cors() {
        return new Cors();
    }

    @Bean
    public CorsWebFilter corsWebFilter(Cors cors) {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOriginPatterns(cors.getOrigins());
        // 允许的HTTP方法
        config.addAllowedMethod("*");
        // 允许的请求头
        config.addAllowedHeader("*");
        config.setAllowCredentials(true);
        // 暴露的响应头
        config.addExposedHeader("token");
        config.addExposedHeader("Content-Disposition");
        config.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source =
                new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }

    @Getter
    @Setter
    public static class Cors {
        private List<String> origins = new ArrayList<>();
    }
}
