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


import com.jiayue.ipfcst.common.security.filter.JwtAuthenticationTokenFilter;
import com.jiayue.ipfcst.common.security.handle.CustomAuthenticationFailureHandler;
import com.jiayue.ipfcst.common.security.handle.CustomAuthenticationSuccessHandler;
import com.jiayue.ipfcst.common.security.handle.EntryPointUnauthorizedHandler;
import com.jiayue.ipfcst.common.security.handle.RestAccessDeniedHandler;
import com.jiayue.ipfcst.common.security.user.JwtUserDetailsServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
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.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.Optional;

/**
 * @description:
 * @author: yh
 * @create: 2020-03-18 16:43
 **/
@Configuration
@EnableWebSecurity // 开启springsecurity过滤链 filter
@EnableJpaAuditing
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启注解方法级别权限控制
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements AuditorAware<String> {

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

    @Autowired
    private JwtUserDetailsServiceImpl jwtUserDetailsServiceImpl;

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

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

    //配置
    @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()
                .antMatchers("/h2-console/**").permitAll()
                .antMatchers("/uploadFileOpenInterface/**").permitAll()
                .antMatchers("/consoleOpenInterface/**").permitAll()
                .antMatchers("/uploadFileLog/**").permitAll()
                .antMatchers("/consoleVersion/**").permitAll()
                .antMatchers("/qrCode/**").permitAll()
                .antMatchers("/generateUploadFile/**").permitAll()
            .antMatchers("/powerStationDataPacker/**").permitAll()
                .antMatchers("/windTowerStatusData/**").permitAll()
                .antMatchers("/reportVersion/**").permitAll().anyRequest().authenticated()
            .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/**", "/assets/**", "/audio/**", "/");
    }

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