package com.ningdatech.pmapi.user.security.auth.common;

import com.ningdatech.pmapi.user.security.auth.AuthProperties;
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.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;

/**
 * 账号密码登陆的认证配置
 */
@Component
public class CommonAuthSecurityConfig
        extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    @Qualifier(value = "defaultLoginSuccessHandler")
    protected AuthenticationSuccessHandler defaultLoginSuccessHandler;

    @Autowired
    @Qualifier(value = "defaultLoginFailureHandler")
    protected AuthenticationFailureHandler defaultLoginFailureHandler;

    @Autowired
    @Qualifier(value = "commonLoginUserDetailService")
    private UserDetailsService commonLoginUserDetailService;

    @Autowired
    private AuthProperties authProperties;

    private AuthenticationManager authenticationManager;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        CommonAuthFilter commonAuthFilter =
                new CommonAuthFilter(authProperties.getCommonLoginUrl());
        authenticationManager = http.getSharedObject(AuthenticationManager.class);
        commonAuthFilter.setAuthenticationManager(authenticationManager);
        commonAuthFilter.setAuthenticationSuccessHandler(defaultLoginSuccessHandler);
        commonAuthFilter.setAuthenticationFailureHandler(defaultLoginFailureHandler);

        CommonAuthProvider authenticationProvider = new CommonAuthProvider();
        authenticationProvider.setUserDetailsService(commonLoginUserDetailService);

        http.authenticationProvider(authenticationProvider).addFilterAfter(commonAuthFilter,
                UsernamePasswordAuthenticationFilter.class);
    }
}
