package com.lutao.cloud.auth.sso.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lutao.cloud.auth.service.CloudTokenDealServiceImpl;
import com.lutao.cloud.auth.sso.client.SSOHttpClient;
import com.lutao.cloud.auth.sso.handler.SSOLoginSuccessHandler;
import com.lutao.cloud.common.security.component.CloudCommenceAuthExceptionEntryPoint;
import com.lutao.cloud.common.security.service.CloudUserDetailsService;
import com.lutao.cloud.common.security.sso.SSOAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.www.BasicAuthenticationFilter;

/**
 *  SSO登录配置入口
 */
public class SSOSecurityConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity>{

	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	private SSOLoginSuccessHandler loginSuccessHandler;

	@Autowired
	private CloudUserDetailsService userDetailsService;

	@Autowired
	private CloudTokenDealServiceImpl dealService;

	@Value("${sso.login-url}")
	private String loginUrl;

	@Autowired
	private SSOHttpClient ssoHttpClient;

	@Autowired
	private CloudCommenceAuthExceptionEntryPoint cloudCommenceAuthExceptionEntryPoint;

	@Override
	public void configure(HttpSecurity http) {
		SSOAuthenticationFilter ssoAuthenticationFilter = new SSOAuthenticationFilter();
		ssoAuthenticationFilter.setSsoHttpClient(ssoHttpClient);
		ssoAuthenticationFilter.setLoginUrl(loginUrl);
		ssoAuthenticationFilter.setObjectMapper(objectMapper);
		ssoAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
		ssoAuthenticationFilter.setAuthenticationSuccessHandler(loginSuccessHandler);
		ssoAuthenticationFilter.setAuthenticationEntryPoint(cloudCommenceAuthExceptionEntryPoint);

		SSOAuthenticationProvider ssoAuthenticationProvider = new SSOAuthenticationProvider();
		ssoAuthenticationProvider.setUserDetailsService(userDetailsService);
		http.authenticationProvider(ssoAuthenticationProvider).addFilterBefore(ssoAuthenticationFilter,
				BasicAuthenticationFilter.class);

		SSOLogoutFilter ssoLogoutFilter = new SSOLogoutFilter();
		ssoLogoutFilter.setObjectMapper(objectMapper);
		ssoLogoutFilter.setDealService(dealService);
		http.addFilterBefore(ssoLogoutFilter, BasicAuthenticationFilter.class);
	}
}
