/*
 * @Author: Kane
 * @Date: 2023-05-25 11:02:53
 * @LastEditors: Kane
 * @FilePath: /NewCitizenQueryResult/src/main/java/com/cpic/xim/web/filters/CrosFilter.java
 * @Description: 
 * 
 * Copyright (c) ${2022} by Kane, All Rights Reserved. 
 */

package com.cpic.xim.web.filters;

import java.io.IOException;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpMethod;

public class CrosFilter implements Filter
{
    @Override
    public void doFilter( ServletRequest req, ServletResponse resp, FilterChain chain )
            throws ServletException, IOException
    {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String method = request.getMethod();
        String originHeader = request.getHeader( "Origin" );
        
        System.out.println( "收到" + method + "请求，来自" + originHeader);
        
        // 如果是Options请求
        if ( method.equals(HttpMethod.OPTIONS.toString()) )
        {
            originHeader = "*";
        }
        
        response.setHeader( "Access-Control-Allow-Origin", originHeader );
        response.setHeader( "Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT" );
        response.setHeader( "Access-Control-Max-Age", "0" );
        response.setHeader( "Access-Control-Allow-Headers",
                "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token" );
        response.setHeader( "Access-Control-Allow-Credentials", "true" );
        response.setHeader( "XDomainRequestAllowed", "1" );
        response.setHeader( "XDomainRequestAllowed", "1" );

        chain.doFilter( request, response );
    }

}
