/**
 * @Author: Kane Wang <wangkane@qq.com>
 * @Date: 2025-03-15 18:40:54
 * @LastEditors: Kane Wang
 * @LastModified: 2025-03-16 08:56:20
 * @FilePath: src/main/java/com/cpic/xim/web/filters/cros/CrosFilter.java
 * @Description:
 * 
 *               Copyright (c) 2025 by Kane All rights reserved
 */
package com.cpic.xim.web.filters.cros;

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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;

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

    /**
     *
     * @param req
     * @param resp
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    @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 );
    }

}
