package de.jottyfan.camporganizer.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;

/**
 *
 * @author jotty
 *
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfiguration {

	@Bean
	protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
		return new NullAuthenticatedSessionStrategy();
	}

	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity sec, InMemoryClientRegistrationRepository crr)
			throws Exception {
		sec.csrf(o -> o.disable()).anonymous(o -> o.disable())
		// @formatter:off
			.oauth2Login(o -> o.defaultSuccessUrl("/"))
			.logout(o -> o.logoutSuccessHandler(new OidcClientInitiatedLogoutSuccessHandler(crr)))
		  .authorizeHttpRequests(o -> o.requestMatchers("/", "/impressum", "/datenschutz", "/allgemeines", "/reports/**", "/nachruf", "/verein", "/vereinsmitglieder", "/kontakt", "/css/**", "/js/**", "/images/**", "/fonts/**", "/font-awesome/**", "/webjars/**", "/ical/**").permitAll()
		  .anyRequest().authenticated())
		  .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
		  .sessionManagement(o -> o.init(sec));
		// @formatter:on
		return sec.build();
	}
}
