package com.izouma.zhirongip.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
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;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableConfigurationProperties({JwtConfig.class})
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;

    // Custom JWT based security filter
    @Autowired
    JwtAuthorizationTokenFilter authenticationTokenFilter;

    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(jwtUserDetailsService)
                .passwordEncoder(passwordEncoderBean());
    }

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

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

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // We don't need CSRF for this example
        httpSecurity.csrf().disable()
                .cors().and()
                // dont authenticate this particular request
                .authorizeRequests()
                //swagger-ui放行路径
                .antMatchers("/v2/api-docs", "/swagger-ui.html", "/swagger-resources/**", "/webjars/**").permitAll()
                .antMatchers("/user/register").permitAll()
                .antMatchers("/user/forgotPassword").permitAll()
                .antMatchers("/upload/**").permitAll()
                .antMatchers("/files/**").permitAll()
                .antMatchers("/static/**").permitAll()
                .antMatchers("/auth/**").permitAll()
                .antMatchers("/captcha/**").permitAll()
                .antMatchers("/admin/**").permitAll()
                .antMatchers("/systemVariable/all").permitAll()
                .antMatchers("/**/excel").permitAll()
                .antMatchers("/wx/**").permitAll()
                .antMatchers("/sms/sendVerify").permitAll()
                .antMatchers("/sms/verify").permitAll()
                .antMatchers("/navigation/backAll").permitAll()
                .antMatchers("/copyright/all").permitAll()
                .antMatchers("/copyright/get/**").permitAll()
                .antMatchers("/funding/all").permitAll()
                .antMatchers("/funding/get/**").permitAll()
                .antMatchers("/logo/all").permitAll()
                .antMatchers("/logo/get/**").permitAll()
                .antMatchers("/logoDemand/all").permitAll()
                .antMatchers("/logoDemand/get/**").permitAll()
                .antMatchers("/technicalManager/all").permitAll()
                .antMatchers("/technicalManager/get/**").permitAll()
                .antMatchers("/technicalManager/recommend").permitAll()
                .antMatchers("/technologyProduct/all").permitAll()
                .antMatchers("/technologyProduct/get/**").permitAll()
                .antMatchers("/serviceProvider/all").permitAll()
                .antMatchers("/serviceProvider/get/**").permitAll()
                .antMatchers("/patentDemand/all").permitAll()
                .antMatchers("/patentDemand/get/**").permitAll()
                .antMatchers("/patent/all").permitAll()
                .antMatchers("/patent/get/**").permitAll()
                .antMatchers("/copyright/all").permitAll()
                .antMatchers("/copyright/get/**").permitAll()
                .antMatchers("/techProductDemand/all").permitAll()
                .antMatchers("/techProductDemand/get/**").permitAll()
                .antMatchers("/copyrightDemand/all").permitAll()
                .antMatchers("/copyrightDemand/get/**").permitAll()
                .antMatchers("/successCase/all").permitAll()
                .antMatchers("/successCase/get/**").permitAll()
                .antMatchers("/purchase/all").permitAll()
                .antMatchers("/purchase/get/**").permitAll()
                .antMatchers("/purchase/recommend").permitAll()
                .antMatchers("/policyLaw/all").permitAll()
                .antMatchers("/policyLaw/get/**").permitAll()
                .antMatchers("/banner/all").permitAll()
                .antMatchers("/intellectualProperty/all").permitAll()
                .antMatchers("/intellectualProperty/get/**").permitAll()
                .antMatchers("/information/all").permitAll()
                .antMatchers("/information/get/**").permitAll()
                .antMatchers("/digital/all").permitAll()
                .antMatchers("/digital/get/**").permitAll()
                .antMatchers("/setting/byFlag").permitAll()
                .antMatchers("/serviceDetail/getByNavigationId/**").permitAll()
                .antMatchers("/sysConfig/get/**").permitAll()
                .antMatchers("/partner/all").permitAll()
                .antMatchers("/company/all").permitAll()
                .antMatchers("/expert/all").permitAll()
                .antMatchers("/navigation/supply").permitAll()
                .antMatchers("/navigation/demand").permitAll()
                .antMatchers("/all/**").permitAll()
                .antMatchers("/error").permitAll()
                .antMatchers("/401").permitAll()
                .antMatchers("/404").permitAll()
                .antMatchers("/500").permitAll()
                .antMatchers("/MP_verify*").permitAll()
                // all other requests need to be authenticated
                .anyRequest().authenticated().and()
                // make sure we use stateless session; session won't be used to
                // store user's state.
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
                .and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // Add a filter to validate the tokens with every request
        httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // AuthenticationTokenFilter will ignore the below paths
        web.ignoring()
                .antMatchers("/auth/**")

                // allow anonymous resource requests
                .and()
                .ignoring()
                .antMatchers(
                        HttpMethod.GET,
                        "/",
                        "/*.html",
                        "/**/favicon.ico",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js"
                );
    }
}
