/*
 * Copyright 2002-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.beecode.inz.war;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
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.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;

import com.beecode.inz.authentication.UserLogoutSuccessHandler;
import com.beecode.inz.authentication.filter.InzWebAuthenticationFilter;
import com.beecode.inz.authentication.handler.RESTAuthenticationEntryPoint;
import com.beecode.inz.authentication.handler.RESTAuthenticationFailureHandler;
import com.beecode.inz.authentication.handler.RESTAuthenticationSuccessHandler;
import com.beecode.inz.authentication.provider.TenantUserAuthenticationProvider;


/**
 * @author Joe Grandja
 */
@EnableWebSecurity
@Configuration
public class SecurityConfig {
	
	@Autowired
	private TenantUserAuthenticationProvider provider;
	
	@Autowired
	private RESTAuthenticationEntryPoint authenticationEntryPoint;
	@Autowired
	private RESTAuthenticationFailureHandler authenticationFailureHandler;
	@Autowired
	private RESTAuthenticationSuccessHandler authenticationSuccessHandler;
	@Autowired
	private TokenBasedRememberMeServices tokenBasedRememberMeServices;
	
	@Configuration
	@Order(1)
	public  class AppSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			http.csrf().disable();
			http.cors().disable();
			http.rememberMe().rememberMeServices(tokenBasedRememberMeServices);
			http.antMatcher("/app/login").authorizeRequests().antMatchers("/app/login","/logout").permitAll();
			http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
			InzWebAuthenticationFilter filter = new InzWebAuthenticationFilter();
			http.addFilterAt(filter, UsernamePasswordAuthenticationFilter.class);
			filter.setAuthenticationManager(authenticationManager());
			filter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
			filter.setAuthenticationFailureHandler(authenticationFailureHandler);
			http.logout().logoutUrl("/logout").logoutSuccessHandler(new UserLogoutSuccessHandler()).invalidateHttpSession(true).deleteCookies("x-auth-token").and();
			
			http.authenticationProvider(provider);
		}
		
		@Override
		protected void configure(AuthenticationManagerBuilder auth) throws Exception {
			auth.authenticationProvider(provider);
		}

		@Override
		protected AuthenticationManager authenticationManager() throws Exception {
			return super.authenticationManager();
		}
	
	}
	
	@Configuration
	@Order(2)
	public  class InzWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			http.csrf().disable();
			http.cors().disable();
			//http.authorizeRequests().anyRequest().authenticated();
			http.authorizeRequests()
				.antMatchers(HttpMethod.OPTIONS).permitAll()
				.antMatchers("/api/login").permitAll()
				.anyRequest().authenticated();
			
			http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
			InzWebAuthenticationFilter filter = new InzWebAuthenticationFilter();
			filter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
			filter.setAuthenticationFailureHandler(authenticationFailureHandler);
			filter.setAuthenticationManager(authenticationManager());
			filter.setRememberMeServices(tokenBasedRememberMeServices);
			http.addFilterAt(filter,UsernamePasswordAuthenticationFilter.class);
			http.rememberMe().rememberMeServices(tokenBasedRememberMeServices);
			http.authenticationProvider(provider);
		}
		
		@Override
		protected void configure(AuthenticationManagerBuilder auth) throws Exception {
			auth.authenticationProvider(provider);
		}

		@Override
		protected AuthenticationManager authenticationManager() throws Exception {
			return super.authenticationManager();
		}
	
	}
}