package com.winsea.svc.common.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Web配置
 * 
 * @author SunTianjun
 */
@Configuration
public class WebConfig {

	@Value("${allowed-origins:*}")
	private String allowedOrigins;

	@Value("${allowed-headers:Access-Control-Allow-Headers,Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Authorization,Access-Control-Request-Headers}")
	private String allowedHeaders;

	/**
	 * 测试用，跨域访问
	 */
	@Bean
	public Filter corsFilter() {
		return new Filter() {

			@Override
			public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
					throws IOException, ServletException {
				HttpServletRequest req = ((HttpServletRequest) request);
				HttpServletResponse res = (HttpServletResponse) response;
				if ("*".equals(allowedOrigins) || allowedOrigins.contains(req.getHeader("Origin"))) {
					res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
//					res.setHeader("Access-Control-Allow-Origin", allowedOrigins);
				}

				res.setHeader("Access-Control-Allow-Credentials", "true");
				res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
				res.setHeader("Access-Control-Allow-Headers", allowedHeaders);
				if (req.getMethod().equals("OPTIONS")) {
					response.getWriter().println("ok");
					return;
				}
				chain.doFilter(request, response);
			}

			@Override
			public void init(FilterConfig filterConfig) throws ServletException {
				// ignore
			}

			@Override
			public void destroy() {
				// ignore
			}
		};
	}
}