package com.user.service.core;

import com.user.service.filter.JwtAuthenticationTokenFilter;
import com.user.service.filter.LogoutSuccessHandlerImpl;
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.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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;


/**
 * 如密码明文存储在数据库中，默认使用的PasswordEncoder要求数据库中的密码格式为：{id}password
 * 使用BCryptPasswordEncoder对密码进行加盐加密处理
 *
 * @author xj
 * @date 2022/07/04
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private JsonAuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private JsonAccessDenieHandler accessDeniedHandler;

    @Autowired
    private LogoutSuccessHandlerImpl logoutSuccessHandler;


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 关于认证相关均在configure中设置
     * SpringSecurity中需关闭CSRF因为前端向后端发送post请求时，必须验证csrf，否则会报错
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext,因为前后端分离项目中，后端无法获取到session
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问(anonymous未登录情况下直接访问，登录过后不允许访问)
                .antMatchers("/user/login").anonymous()
                // 放行swagger
                .antMatchers("/swagger-ui.html").anonymous()
                .antMatchers("/swagger-resources/**").anonymous()
                .antMatchers("/webjars/**").anonymous()
                .antMatchers("/*/api-docs").anonymous()
                .antMatchers("/druid/**").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();

        //把token校验过滤器添加到过滤器链中
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        http.logout().logoutUrl("/user/logout").logoutSuccessHandler(logoutSuccessHandler);
        //  配置异常处理器
        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint) // 配置认证失败处理
                .accessDeniedHandler(accessDeniedHandler);          // 授权失败处理
        //允许跨域
        http.cors();
    }

    /**
     * AuthenticationManager的authenticate方法来进行用户认证
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}