package com.koobietech.eas.security.config;

import com.koobietech.eas.security.exception.EasAuthenticationEntryPoint;
import com.koobietech.eas.security.exception.EasAuthenticationFailureHandler;
import com.koobietech.eas.security.filter.EasSecurityFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * @author lc
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Resource
    EasSecurityFilter easSecurityFilter;

    @Resource
    IgnoreUrlsConfig ignoreUrlsConfig;

    @Bean
    public SecurityFilterChain buildSecurityFilterChain(HttpSecurity httpSecurity) throws Exception {

        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry
                registry = httpSecurity.authorizeRequests();

        for (String url : ignoreUrlsConfig.getIgnored()) {
            registry.antMatchers(url).permitAll();
        }
        registry.anyRequest()
                .access("@SecurityAccessService.hasPermission(request, authentication)");

        HttpSecurity and = httpSecurity
                .csrf()
                .disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.NEVER)
                .and()
                //处理异常信息
                .exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler())
                .authenticationEntryPoint(restAuthenticationEntryPoint())
                .and();
        and.addFilterBefore( easSecurityFilter, UsernamePasswordAuthenticationFilter.class);

        return and.build();
    }

    @Bean
    public EasAuthenticationFailureHandler restfulAccessDeniedHandler() {
        return new EasAuthenticationFailureHandler();
    }

    @Bean
    public EasAuthenticationEntryPoint restAuthenticationEntryPoint() {
        return new EasAuthenticationEntryPoint();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
