package org.qinan.safetyeval.start.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
@SuppressWarnings("deprecation")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final WebSecurityProperties properties;

    public WebSecurityConfig(WebSecurityProperties properties) {
        this.properties = properties;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        String[] authenticated = properties.authenticatedPatterns();
        String[] permitAll = properties.permitAllPatterns();

        if (permitAll.length > 0) {
            http.csrf().ignoringAntMatchers(permitAll);
        }

        org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer<HttpSecurity>
                .ExpressionInterceptUrlRegistry requests = http.authorizeRequests();

        // Authentication rules take priority when they overlap with a public prefix.
        if (authenticated.length > 0) {
            requests.antMatchers(authenticated).authenticated();
        }
        if (permitAll.length > 0) {
            requests.antMatchers(permitAll).permitAll();
        }

        requests.anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic();
    }
}
