package com.ningdatech.kqapi.security.password;

import com.ningdatech.kqapi.security.AuthProperties;
import com.ningdatech.kqapi.user.helper.LoginHelper;
import lombok.RequiredArgsConstructor;
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.core.userdetails.UserDetailsService;
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;

/**
 * <p>
 * 账号密码登陆的认证配置
 * </p>
 *
 * @author WendyYang
 * @since 09:54 2023/3/2
 */
@Component
@RequiredArgsConstructor
public class PasswordAuthSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    private final AuthenticationSuccessHandler authenticationSuccessHandler;
    private final AuthenticationFailureHandler authenticationFailureHandler;
    private final UserDetailsService userDetailsService;
    private final AuthProperties authProperties;
    private final LoginHelper loginHelper;

    @Override
    public void configure(HttpSecurity http) {
        UsernamePasswordAuthFilter authFilter = new UsernamePasswordAuthFilter(authProperties.getPasswordLoginUrl(),
                authProperties.getPostOnlyByLogin());
        AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
        authFilter.setAuthenticationManager(authenticationManager);
        authFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
        authFilter.setAuthenticationFailureHandler(authenticationFailureHandler);

        PasswordAuthProvider authProvider = new PasswordAuthProvider();
        authProvider.setUserDetailsService(userDetailsService);
        // 确保对密码进行加密的encoder和解密的encoder相同
        authProvider.setLoginHelper(loginHelper);
        http.authenticationProvider(authProvider)
                .addFilterAfter(authFilter, UsernamePasswordAuthenticationFilter.class);
    }

}
