package com.ym.mec.auth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.ym.mec.auth.core.filter.PhoneLoginAuthenticationFilter;
import com.ym.mec.auth.core.filter.UsernameAuthenticationFilter;
import com.ym.mec.auth.core.handler.BaseAuthenticationFailureEvenHandler;
import com.ym.mec.auth.core.handler.BaseAuthenticationSuccessEventHandler;
import com.ym.mec.auth.core.provider.PhoneAuthenticationProvider;
import com.ym.mec.auth.core.provider.service.DefaultUserDetailsService;
import com.ym.mec.auth.service.SysUserDeviceService;
import com.ym.mec.auth.service.SysUserService;
import com.ym.mec.common.service.IdGeneratorService;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)//会拦截注解了@PreAuthrize注解的配置.
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private DefaultUserDetailsService defaultUserDetailsService;
	
	@Autowired
	private BaseAuthenticationSuccessEventHandler successEventHandler;

	@Autowired
	private BaseAuthenticationFailureEvenHandler failureEvenHandler;

	@Autowired
	private IdGeneratorService smsCodeService;

	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private SysUserDeviceService sysUserDeviceService;
	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.authenticationProvider(daoAuthenticationProvider());
		
		PhoneAuthenticationProvider provider = phoneAuthenticationProvider();
		provider.setSysUserService(sysUserService);
		auth.authenticationProvider(provider);
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// 表单登录 方式
		http.formLogin().loginPage("/loginIn").loginPage("/smsLogin").and()
			.addFilterBefore(getUsernameAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
			.addFilterBefore(getPhoneLoginAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
				//.exceptionHandling().accessDeniedHandler(baseAccessDeniedHandler).authenticationEntryPoint(baseAuthenticationEntryPoint).and()// 当未登录访问资源时
				// 请求授权
				.authorizeRequests()// 不需要权限认证的url
				.antMatchers("/usernameLogin","/smsLogin", "/refreshToken", "/v2/api-docs").permitAll()// 任何请求
				.anyRequest()// 需要身份认证
				.authenticated().and()// 关闭跨站请求防护
				.csrf().disable();
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/usernameLogin", "/smsLogin", "/refreshToken", "/v2/api-docs","/loginIn","/user/updatePassword");
	}

	@Bean
	@Override
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}

	@Bean
	public PasswordEncoder passwordEncoder() {
		return PasswordEncoderFactories.createDelegatingPasswordEncoder();
	}

	@Bean
	public DaoAuthenticationProvider daoAuthenticationProvider() {
		DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
		// 设置userDetailsService
		provider.setUserDetailsService(defaultUserDetailsService);
		// 禁止隐藏用户未找到异常
		provider.setHideUserNotFoundExceptions(false);
		// 使用BCrypt进行密码的hash
		provider.setPasswordEncoder(passwordEncoder());
		return provider;
	}

    @Bean
    public PhoneAuthenticationProvider phoneAuthenticationProvider(){
    	PhoneAuthenticationProvider provider = new PhoneAuthenticationProvider();
        // 设置userDetailsService
        provider.setUserDetailsService(defaultUserDetailsService);
        provider.setSmsCodeService(smsCodeService);
        provider.setSysUserService(sysUserService);
        provider.setSysUserDeviceService(sysUserDeviceService);
		// 禁止隐藏用户未找到异常
		provider.setHideUserNotFoundExceptions(false);
		
        return provider;
    }

	@Bean
	public UsernameAuthenticationFilter getUsernameAuthenticationFilter() throws Exception {
		UsernameAuthenticationFilter filter = new UsernameAuthenticationFilter();
		filter.setAuthenticationManager(authenticationManagerBean());
		filter.setAuthenticationSuccessHandler(successEventHandler);
		filter.setAuthenticationFailureHandler(failureEvenHandler);
		filter.setSysUserService(sysUserService);
		filter.setSysUserDeviceService(sysUserDeviceService);
		return filter;
	}

	@Bean
	public PhoneLoginAuthenticationFilter getPhoneLoginAuthenticationFilter() throws Exception {
		PhoneLoginAuthenticationFilter filter = new PhoneLoginAuthenticationFilter();
		filter.setAuthenticationManager(authenticationManagerBean());
		filter.setAuthenticationSuccessHandler(successEventHandler);
		filter.setAuthenticationFailureHandler(failureEvenHandler);
		return filter;
	}

}
