package com.qiaoba.auth.config;

import com.qiaoba.api.auth.constants.SecurityConstant;
import com.qiaoba.auth.filter.SecurityContextHolderFilter;
import com.qiaoba.auth.handler.AccessDeniedHandler;
import com.qiaoba.auth.handler.LogoutHandler;
import com.qiaoba.auth.properties.AuthConfigProperties;
import com.qiaoba.common.base.constant.BaseConstant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;

/**
 * SpringSecurity安全配置
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/5/15 11:23
 */
@Configuration
@RequiredArgsConstructor
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Slf4j
public class SpringSecurityConfig {

    private final AuthConfigProperties authConfigProperties;
    private final AccessDeniedHandler accessDeniedHandler;
    private final SecurityContextHolderFilter securityContextHolderFilter;
    private final LogoutHandler logoutHandler;


    @Bean
    SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests();
        //白名单
        for (String url : authConfigProperties.getWhitelist()) {
            registry.antMatchers(url).permitAll();
        }
        // 文件资源 无需鉴权
        registry.antMatchers(BaseConstant.RESOURCE_PATTERN).permitAll();
        // 由于使用的是JWT，我们这里不需要csrf
        httpSecurity.csrf()
                .disable()
                //添加自定义未授权和未登录结果返回
                .exceptionHandling()
                .authenticationEntryPoint(accessDeniedHandler)
                .and()
                // 基于token，所以不需要session
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //跨域请求会先进行一次options请求
                .antMatchers(HttpMethod.OPTIONS)
                .permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest()
                .authenticated();
        // 禁用缓存
        httpSecurity.headers().cacheControl();
        // 退出处理
        httpSecurity.logout().logoutUrl(SecurityConstant.LOGOUT_URI).logoutSuccessHandler(logoutHandler);
        // 添加JWT filter
        httpSecurity.addFilterBefore(securityContextHolderFilter, UsernamePasswordAuthenticationFilter.class);
        httpSecurity.addFilterBefore(securityContextHolderFilter, LogoutFilter.class);
        return httpSecurity.build();
    }
}
