package cn.quantgroup.customer.config.http.security;

import cn.quantgroup.customer.config.http.mvc.filter.CsrfHeaderFilter;
import cn.quantgroup.customer.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;

@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private final IUserService userService;
    private final PasswordEncoder passwordEncoder;

    @Value("${allowed.routes}")
    private String allowedRoutes;
    @Autowired
    public WebSecurityConfig(IUserService userService, PasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        String allowedRoutes = "/test/**,/error/**,/repay/**,/channel/**,/order/**,/operate/sys/**,/user/**,/work_order/**,/vcc/**,/transactionReceiptRecord/**";
        String[] allowedRoutesArr = allowedRoutes.split(",");
        http.httpBasic().and()
                .authorizeRequests()
                .antMatchers(allowedRoutesArr)
                .permitAll().anyRequest().authenticated()
                .and()
                .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
                .csrf().csrfTokenRepository(csrfTokenRepository())
                .and()
                .csrf()
                .disable()
                .logout();

    }

    private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        return repository;
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder);
    }

    @Override
    public UserDetailsService userDetailsServiceBean() {
        return userService;
    }


}
