package com.zcxk.security.smsCode;


import com.zcxk.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

@Component
public class SmsCodeSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    @Autowired
    @Qualifier("myAuthenticationSuccessHandler")
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;
    @Autowired
    private MyUserDetailService userDetailsService;
    @Autowired
    private SmsCodeCheckUserFilter smsCodeCheckUserFilter;



    @Override
    public void configure(HttpSecurity http) throws Exception {
        SmsCodeLoginAuthenticationFilter smsCodeLoginAuthenticationFilter = new SmsCodeLoginAuthenticationFilter();
        smsCodeLoginAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        smsCodeLoginAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
        smsCodeLoginAuthenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler);

        SmsCodeLoginAuthenticationProvider smsCodeLoginAuthenticationProvider = new SmsCodeLoginAuthenticationProvider();
        smsCodeLoginAuthenticationProvider.setUserDetailsService(userDetailsService);
        http.authenticationProvider(smsCodeLoginAuthenticationProvider)
                .addFilterAfter(smsCodeCheckUserFilter, UsernamePasswordAuthenticationFilter.class)
                .addFilterAfter(smsCodeLoginAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
