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

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 AgentAuthSecurityConfig
        extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

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

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

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

    @Autowired
    private AuthProperties authProperties;

    private AuthenticationManager authenticationManager;

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

        AgentAuthProvider authenticationProvider = new AgentAuthProvider();
        authenticationProvider.setUserDetailsService(agentLoginUserDetailService);

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