/*
 * @Author: Kane
 * 
 * @Date: 2023-02-28 22:52:32
 * 
 * @LastEditors: Kane
 * 
 * @FilePath: /desktop_archievement_backend/src/main/java/com/cpic/xim/web/filters/cros/CrosFilter.java
 * 
 * @Description:
 * 
 * Copyright (c) ${2022} by Kane, All Rights Reserved.
 */
package com.cpic.xim.web.filters.cros;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;

public class CrosFilter implements Filter
{
    private static Logger logger = LoggerFactory.getLogger( CrosFilter.class );

    @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" );

        logger.info( "收到" + 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 );
    }

}
