package com.eactive.eai.authserver.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletResponse;

@Configuration
@EnableWebSecurity
@Order(1)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	@Qualifier("eLinkUserDetailsService")
	private UserDetailsService userDetailsService;
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    	http.csrf().disable()
    			.headers().frameOptions().disable()
    			.and()
    			.authorizeRequests()
    			.antMatchers("/error.jsp").permitAll()
    			.antMatchers("/**").permitAll()
    			.and()
    			.exceptionHandling()
    			.authenticationEntryPoint((request, response, authException) -> {
    				response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    				request.setAttribute("_authServerStatusCode", HttpServletResponse.SC_UNAUTHORIZED);
    				request.setAttribute("errorMessage", "401 Unauthorized");
    				request.getRequestDispatcher("/error.jsp").forward(request, response);
    			})
    			.accessDeniedHandler((request, response, accessDeniedException) -> {
    				response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    				request.setAttribute("_authServerStatusCode", HttpServletResponse.SC_FORBIDDEN);
    				request.setAttribute("errorMessage", "403 Forbidden");
    				request.getRequestDispatcher("/error.jsp").forward(request, response);
    			})
    			.and()
    			.formLogin();
//    			.and()
//    			.httpBasic();
    }

    @Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
	}

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