Commit ecfbc496 authored by ourfbht's avatar ourfbht
Browse files

#1 simple auth system

parent 43df8af6
Loading
Loading
Loading
Loading
+50 −0
Original line number Diff line number Diff line
package com.example.demo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

@Configuration
public class CustomLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{

    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {

        String targetUrl = determineTargetUrl(authentication);

        if (response.isCommitted()) {
            return;
        }
        RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
        redirectStrategy.sendRedirect(request, response, targetUrl);
    }
    
    protected String determineTargetUrl(Authentication authentication) {
        String url = "/login?error=true";

        // Fetch the roles from Authentication object
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        List<String> roles = new ArrayList<String>();
        for (GrantedAuthority a : authorities) {
            roles.add(a.getAuthority());
        }

        // check user role and decide the redirect URL
        if (roles.contains("ADMIN")) {
            url = "/admin";
        } 
        else if (roles.contains("POULAIN") || roles.contains("MENTOR")) {
            url = "/member";
        }
        return url;
    }
}
+27 −22
Original line number Diff line number Diff line
package com.example.demo;

import java.security.Principal;
import java.util.Date;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import com.example.demo.HelpRequestRepository;
import com.example.demo.model.User;


@Controller
@@ -30,9 +35,9 @@ public class HelpRequestController {
    
    @PostMapping("/insertHelpRequest")
    public String insertHelpRequest(@ModelAttribute HelpRequest helpRequest, Model model) {
		//TODO : recup le poulain loggé
        //TODO 
        Poulain poulain= new Poulain();
		poulain.setId(0);
        poulain.setId(1);
        helpRequest.setPoulain(poulain);

        helpRequestRepository.save(helpRequest);
+10 −0
Original line number Diff line number Diff line
package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@@ -9,4 +12,11 @@ public class MVCController implements WebMvcConfigurer {
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
    }

    /*@Bean
    public BCryptPasswordEncoder passwordEncoder(){
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder;
    }*/

}
+42 −11
Original line number Diff line number Diff line
package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Autowired
    private CustomLoginSuccessHandler successHandler;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private DataSource dataSource;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .antMatchers("/", "/index").permitAll()
                .antMatchers("/allMentor").permitAll()
                .antMatchers("/formMentor").permitAll()
                .antMatchers("/insertMentor").permitAll()
@@ -22,22 +37,38 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
                .antMatchers("/formPoulain").permitAll()
                .antMatchers("/insertPoulain").permitAll()
                .antMatchers("/allHelpRequest").permitAll()
                .antMatchers("/formHelpRequest").permitAll()
                .antMatchers("/formHelpRequest").hasAnyAuthority("POULAIN")
                .antMatchers("/login").permitAll()
                .antMatchers("/register").permitAll()
                .antMatchers("/admin/**").hasAnyAuthority("ADMIN")
                .antMatchers("/member/**").hasAnyAuthority("POULAIN", "MENTOR")
                .and()
            .formLogin()
            .csrf().disable().formLogin()
                .loginPage("/login")
                .permitAll()
                .failureUrl("/login?error=true")
                .successHandler(successHandler)
                .usernameParameter("email")
                .passwordParameter("password")
                .and()
            .logout()
                .permitAll();
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/").and()
                .exceptionHandling()
                .accessDeniedPage("/access-denied");
    }

    @Bean
    public AuthenticationManager customAuthenticationManager() throws Exception {
        return authenticationManager();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("mentor").password("{noop}mentor").roles("MENTOR")
                .and().withUser("poulain").password("{noop}poulain").roles("POULAIN");
        auth.jdbcAuthentication().usersByUsernameQuery(
            "select email, password, '1' as enabled from auth_user where email=? and status='VERIFIED'"
        ).authoritiesByUsernameQuery(
            "select u.email, r.role_name from auth_user u inner join auth_user_role ur on(u.auth_user_id=ur.auth_user_id) inner join auth_role r on(ur.auth_role_id=r.auth_role_id) where u.email=?"
        ).dataSource(dataSource).passwordEncoder(bCryptPasswordEncoder);
    }

}
 No newline at end of file
+80 −0
Original line number Diff line number Diff line
package com.example.demo.controller;

import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.example.demo.model.User;
import com.example.demo.service.UserService;

@Controller
public class AuthenticationController {

    @Autowired
    UserService userService;

    @RequestMapping(value = { "/login" }, method = RequestMethod.GET)
    public ModelAndView login() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login"); // resources/template/login.html
        return modelAndView;
    }

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public ModelAndView register() {
        ModelAndView modelAndView = new ModelAndView();
        User user = new User();
        modelAndView.addObject("user", user);
        modelAndView.setViewName("register"); // resources/template/register.html
        return modelAndView;
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index"); // resources/template/index.html
        return modelAndView;
    }
    
    @RequestMapping(value = "/admin", method = RequestMethod.GET)
    public ModelAndView adminHome() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("admin"); // resources/template/admin.html
        return modelAndView;
    }

    @RequestMapping(value = "/member", method = RequestMethod.GET)
    public ModelAndView memberHome() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("member"); // resources/template/member.html
        return modelAndView;
    }

    @RequestMapping(value="/register", method=RequestMethod.POST)
    public ModelAndView registerUser(@Valid User user, @RequestParam("roleWanted") String roleWanted, BindingResult bindingResult, ModelMap modelMap) {
        ModelAndView modelAndView = new ModelAndView();
        
        if(bindingResult.hasErrors()) { // Check for the validations
            modelAndView.addObject("registerMessage", "Registration failed: correct the fields !");
            modelMap.addAttribute("bindingResult", bindingResult);
        }
        else if(userService.isUserAlreadyPresent(user)){ // Checking if email already taken
            modelAndView.addObject("registerMessage", "User with this email already exist !");
        }
        else { // Saving the users
            userService.save(user, roleWanted);
            return new ModelAndView("redirect:" + "/");
        }

        modelAndView.addObject("user", new User());
        modelAndView.setViewName("register");
        
        return modelAndView;
    }
}
 No newline at end of file
Loading