package com.style24.admin.support.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.web.util.matcher.AntPathRequestMatcher;

import com.style24.admin.support.security.TsaAuthenticationProvider;
import com.style24.admin.support.security.handler.TsaLoginSuccessHandler;
import com.style24.admin.support.security.handler.TsaLogoutSuccessHandler;

/**
 * Java Security를 이용한 Login 처리
 * 
 * @author gagamel
 * @since 2020. 10. 5
 */
@Configuration
@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
//@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class TsaSecurityConfig extends WebSecurityConfigurerAdapter {

	private static final String[] UNAUTHORIZED_RESOURCE_LIST = new String[] {"/*", "/index"};

	private static final String[] UNSECURED_RESOURCE_LIST = new String[] {"/image/**", "/ux/**", "/data/**", "/smartEditor/**"};

	@Autowired
	private TsaAuthenticationProvider authenticationProvider;

	/**
	 * Register the Authentication Provider
	 */
	@Override
	public void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.authenticationProvider(authenticationProvider);
	}

	@Override
	protected void configure(HttpSecurity httpSecurity) throws Exception {
		// static resources
		httpSecurity.authorizeRequests()
			.antMatchers(UNAUTHORIZED_RESOURCE_LIST).permitAll()
//			.anyRequest().authenticated()
//				.antMatchers("/backoffice/**").hasAnyAuthority(FccConstants.ROLE.ADMIN.value())
//				.antMatchers(new String[] { "/backoffice/*", "/backoffice/chairman/**" }).hasAnyAuthority(FccConstants.ROLE.CC_CHIEF.value())
//				.antMatchers(new String[] { "/backoffice/*", "/backoffice/evaluator/**" }).hasAnyAuthority(FccConstants.ROLE.COUNSELOR.value())
			.and()
			.formLogin()
			.usernameParameter("userId")
			.passwordParameter("passwd")
			.loginPage("/signin")
			.loginProcessingUrl("/login")
			.successHandler(loginSuccessHandler())
			.failureUrl("/?error=true")
			.and()
			.logout()
			.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
			.logoutSuccessHandler(logoutSuccessHandler())
			.and()
			.csrf().disable() // CSRF(Cross Site Request Forgery) 해제
//			.csrf().requireCsrfProtectionMatcher(requireCsrfProtectionMatcher())
			.exceptionHandling()
			.accessDeniedPage("/403")
			.and()
			.headers().frameOptions().disable() // iframe deny 설정 제거(네이버스마트에디터 사용 때문에 추가)
//			.and()
//			.rememberMe().tokenRepository(persistentTokenRepository())
//				.tokenValiditySeconds(60 * 60 * 24 * 10) // 10 days
//				.useSecureCookie(true)
//				.key("sisunTsa")
//			.and()
//			.sessionManagement()
//				.maximumSessions(1)
//				.maxSessionsPreventsLogin(false)
//				.maxSessionsPreventsLogin(true)
//				.sessionRegistry(sessionRegistry())
//				.expiredUrl("/index")
		;
	}

	@Override
	public void configure(WebSecurity webSecurity) throws Exception {
		webSecurity
			.ignoring()
			.antMatchers(UNSECURED_RESOURCE_LIST);
	}

	@Bean
	public TsaLoginSuccessHandler loginSuccessHandler() {
		return new TsaLoginSuccessHandler();
	}

	@Bean
	public TsaLogoutSuccessHandler logoutSuccessHandler() {
		return new TsaLogoutSuccessHandler();
	}

//	@Bean
//	public RequestMatcher requireCsrfProtectionMatcher() {
//		GagaCsrfSecurityRequestMatcher bean = new GagaCsrfSecurityRequestMatcher();
//
//		bean.setDisableUrls(new String[] {
//				"/",
//				"/index",
//				"/customer/post/find/form"
//		});
//
//		return bean;
//	}

}
