package com.securitycontrol.gateway.config;

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


/**
 * @author HeiZi
 */
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 当前只支持POST 跟GET
        response.setHeader("Access-Control-Allow-Methods",
                "POST, GET");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers",
                "Content-Type, x-requested-with, X-Custom-Header, Authorization");
        // 对OPTIONS请求进行拦截处理
        String  options="OPTIONS";
        if(options.equalsIgnoreCase(request.getMethod())){
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(new String("不安全的请求".getBytes(),"utf-8").getBytes());
            outputStream.flush();
        }else {
            chain.doFilter(req, res);
        }

    }

    @Override
    public void destroy() {
    }
}
