package com.koobietech.eas.security.config;

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;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Resource
    EasSecurityFilter easSecurityFilter;

    @Resource
    IgnoreUrlsConfig ignoreUrlsConfig;

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

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

        for (String url : ignoreUrlsConfig.getIgnored()) {
            registry.antMatchers(url).permitAll();
        }
        registry.anyRequest().authenticated();

        HttpSecurity and = httpSecurity
                .csrf()
                .disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.NEVER)
                .and();
        and.addFilterBefore( easSecurityFilter, UsernamePasswordAuthenticationFilter.class);

        return and.build();
    }

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