package com.jiayue.ssi.config;

import com.jiayue.ssi.constant.CacheConstants;
import com.jiayue.ssi.entity.SysBlacklist;
import com.jiayue.ssi.interceptor.TokenStatusInterceptor;
import com.jiayue.ssi.service.SysBlacklistService;
import com.jiayue.ssi.service.SysParameterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.StrictHttpFirewall;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.Arrays;
import java.util.List;

/**
* MVC配置
*
* @author xsl
* @since 2023/03/03
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    SysParameterService sysParameterService;
    @Autowired
    SysBlacklistService sysBlacklistService;

    @Override
    public void addInterceptors(InterceptorRegistry registry){
        // 刷新token拦截器注册
        registry.addInterceptor(new TokenStatusInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/refreshToken","/error","/getVerifyCode","/login","/index.html","/user/login","/css/**","/images/**","/js/**","/fonts/**");
    }

    /**
     * 加载黑名单
     */
    @Bean
    public void initBlackList() {
        // 加载上报对象缓存
        List<SysBlacklist> sysBlacklists = sysBlacklistService.list();
        for (SysBlacklist sysBlacklist:sysBlacklists){
            CacheConstants.blacklistMap.put(sysBlacklist.getIp(),sysBlacklist);
        }
    }

    @Bean
    public ServletContextInitializer servletContextInitializer() {
        return new ServletContextInitializer() {
            @Override
            public void onStartup(ServletContext servletContext) throws ServletException {
                // 解决加密会话（SSL）Cookie 中缺少 Secure 属性
                servletContext.getSessionCookieConfig().setSecure(true);
            }
        };
    }
}
