package com.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import javax.sql.DataSource;

/**
 *
 * Define configuration for Spring Security.
 *
 * @author Laurentiu Marcut
 */
@Configuration
@EnableWebSecurity
@ComponentScan({ "com.config" })
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("select email, password, 1 from user where email = ? ")
                .authoritiesByUsernameQuery("select user, role from user_role where user = ? ");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/projects").access("hasRole('ROLE_USER')")
                .and()
                    .formLogin()
                        .loginPage("/login")
                        .defaultSuccessUrl("/projects")
                        .failureUrl("/login?error")
                        .usernameParameter("email")
                        .passwordParameter("password")
                .and()
                    .logout()
                        .logoutSuccessUrl("/login?logout");
    }
}
