package com.jiayue.ipp.common.security.config;


import com.jiayue.ipfcst.common.core.util.SpringContextHolder;
import com.jiayue.ipp.common.security.filter.JwtAuthenticationTokenFilter;
import com.jiayue.ipp.common.security.handle.CustomAuthenticationFailureHandler;
import com.jiayue.ipp.common.security.handle.CustomAuthenticationSuccessHandler;
import com.jiayue.ipp.common.security.handle.EntryPointUnauthorizedHandler;
import com.jiayue.ipp.common.security.handle.RestAccessDeniedHandler;
import com.jiayue.ipp.common.security.user.impl.JwtUserDetailsServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @description:
 * @author: yh
 * @create: 2020-03-18 16:43
 **/
@Configuration
@EnableWebSecurity // 开启springsecurity过滤链 filter
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启注解方法级别权限控制
@Slf4j
@ComponentScan(basePackages = "com.jiayue.ipp.common.security") // 替换为包含JwtUserDetailsServiceImpl的包名
public class WebSecurityConfig extends WebSecurityConfigurerAdapter  {

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 明文+随机盐值》加密存储
        return new BCryptPasswordEncoder();
    }


    @Autowired
    JwtUserDetailsServiceImpl jwtUserDetailsServiceImpl;
    @Autowired
    EntryPointUnauthorizedHandler entryPointUnauthorizedHandler;
    @Autowired
    CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
    @Autowired
    CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
    @Autowired
    RestAccessDeniedHandler restAccessDeniedHandler;
    @Autowired
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    //用户查询
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(jwtUserDetailsServiceImpl);
    }


    //配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.headers().frameOptions().sameOrigin();
        http.cors().and()
                // 由于使用的是JWT，我们这里不需要csrf
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers("/pushSocket/**").permitAll()
                .antMatchers("/druid/**").permitAll()
                .and()
                .formLogin().loginProcessingUrl("/user/login")
                .successHandler(customAuthenticationSuccessHandler)
                .failureHandler(customAuthenticationFailureHandler)
                .and().headers().cacheControl();

        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        http.exceptionHandling().authenticationEntryPoint(entryPointUnauthorizedHandler).accessDeniedHandler(restAccessDeniedHandler);

    }

    //针对静态资源放行
    @Override
    public void configure(WebSecurity web) throws Exception {
        /*super.configure(web);*/
        web.ignoring().antMatchers("/static/**" , "/");
    }

//    @Override
//    public Optional<String> getCurrentAuditor() {
////        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        return Optional.of(authentication == null ? "admin" : authentication.getName());
//    }
}
