package com.dayou.filter;

/**
 * Created by shenju on 2017/3/17.
 */

import com.dayou.constants.JwtConstants;
import org.springframework.http.HttpMethod;

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

//@WebFilter(urlPatterns = "/*", filterName = "Filter1_CorsFilter")
public class AFilter1_CorsFilter implements Filter {


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

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        try {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String method = request.getMethod();
            String origin = request.getHeader("Origin");

            if (origin != null) {
                response.setHeader("Access-Control-Allow-Origin", origin);
            }
            response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "originType,platform,gzhstaffcode,gzhstaffcodeTime,X-Requested-With,Content-Type,authKey,sessionStr,menuCode,x_requested_with,*," + JwtConstants.REST_TOKEN);
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Max-Age", "600");

            if (HttpMethod.OPTIONS.toString().equals(method)) {
                return;
            }

            filterChain.doFilter(request, response);
        } finally {
        }

    }

    @Override
    public void destroy() {

    }
}