package com.zjty.tynotes.pas.config;

import com.zjty.tynotes.pas.config.handler.MyAccessHandler;
import com.zjty.tynotes.pas.config.handler.MyFailHandler;
import com.zjty.tynotes.pas.config.handler.MyLogoutHandler;
import com.zjty.tynotes.pas.config.handler.MySuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.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.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.channel.ChannelProcessingFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @author mcj
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    public MyProvider myProvider;
    @Autowired
    private MyAccessHandler accessHandler;
    @Autowired
    private MyEntryPoint myEntryPoint;

    @Autowired
    private MyUserDetailsServiceImpl myUserDetailsServiceImpl;

    @Autowired
    private MyLogoutHandler myLogoutHandler;

    @Autowired
    private MyFailHandler failHandler;

    @Autowired
    private MySuccessHandler successHandler;


    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .cors().and()
                .authorizeRequests()
                .antMatchers("/pas/user/addGuanLian").permitAll()
                .antMatchers(HttpMethod.GET,"/pas/user").permitAll()
                .antMatchers("/pas/user/encryPas").permitAll()
                .antMatchers(HttpMethod.GET,"/pas/department").permitAll()
                .antMatchers("/pas/user/findUserList/**").permitAll()
                // .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .antMatchers("/pas/user/**",
                        "/pas/authority/findAuthority",
                        "/pas/role","/pas/department").hasAnyAuthority("用户管理")
                .antMatchers("/pas/authority").hasAnyAuthority("权限管理")
                .antMatchers("/pas/config").hasAnyAuthority("考勤管理")
                .antMatchers("/pas/role").hasAnyAuthority("角色管理")
                .antMatchers("/pas/department").hasAnyAuthority("部门管理")
                .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                .antMatchers("/pas/count").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginProcessingUrl("/userLogin")
                .and()
                .logout()
                .logoutUrl("/userLogout")
                //.logoutSuccessUrl("/userLogout")
                .logoutSuccessHandler(myLogoutHandler)
                .deleteCookies("JESSIONID")
                .permitAll()
                .and()
                .exceptionHandling()
                .accessDeniedHandler(accessHandler)
                .authenticationEntryPoint(myEntryPoint)
                .and()
                .addFilterAt(myFilter(), UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(corsFilter(), ChannelProcessingFilter.class)
                .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).disable().sessionManagement().maximumSessions(1).expiredUrl("/userLogout").sessionRegistry(sessionRegistry())
        ;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //swagger静态资源访问
        web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**","/swagger-resources/configuration/ui","/swagge‌​r-ui.html");
    }

    @Bean
    public MyFilter myFilter() throws Exception {
        MyFilter filter = new MyFilter();
        filter.setAuthenticationSuccessHandler(successHandler);
        filter.setAuthenticationFailureHandler(failHandler);
        filter.setFilterProcessesUrl("/userLogin");
        filter.setAuthenticationManager(this.authenticationManager());
        return filter;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsServiceImpl);
       // auth.authenticationProvider(myProvider);

      //  auth.inMemoryAuthentication().withUser("root").password(bCryptPasswordEncoder().encode("root")).roles("admin").authorities("addUser","deleteUser","updateUser","system");
    }

    @Bean
    public SessionRegistry sessionRegistry(){
        return new SessionRegistryImpl();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}
