package cn.reghao.tnb.auth.app.config.web;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 在过滤器中全局处理跨域
 *
 * @author reghao
 * @date 2023-02-13 17:14:33
 */
public class CorsFilter implements Filter {
    private final List<String> allowedOrigins;

    public CorsFilter() {
        // TODO 修改为在配置文件中获取
        this.allowedOrigins = List.of("");
    }

    @Override
    public void destroy() {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String origin = httpServletRequest.getHeader("Origin") != null ?
                httpServletRequest.getHeader("Origin").replace(" ", "") :
                httpServletRequest.getHeader("Origin");
        // 判断数组中是否包含请求中的origin，如果包含就做跨域设置，否则就是不被允许跨域的地址，不做跨域设置
        if (origin != null && allowedOrigins.contains(origin)) {
            httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);
            //httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");
            httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept,Authorization");
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,HEAD,PUT,DELETE");
            // 带有Cookie的跨域请求，此值必须设置为true
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            // 非简单请求，只要第一次通过OPTIONS检查 在1小时之内不会在调用OPTIONS进行检测
            httpServletResponse.addHeader("Access-Control-Max-Age","3600");
        }

        if ("OPTIONS".equals(httpServletRequest.getMethod())) {
            httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
            return;
        }

        // 这里还可以添加一些想对reponse header添加的信息
        chain.doFilter(request, httpServletResponse);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {}
}
