Skip to content
Snippets Groups Projects
Commit 6c111de7 authored by Jessie Ragot's avatar Jessie Ragot
Browse files

Refactor authentification, not functional, there are too many redirects the...

Refactor authentification, not functional, there are too many redirects the login page is not displayed
parent 70d2db4d
No related branches found
No related tags found
1 merge request!19[feature]models-change+authentification+registration
package com.projet.projetIndu.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class LoginController {
@GetMapping("/login")
public String showLoginForm() {
return "login"; // Correspond à login.html
}
}
......@@ -8,6 +8,8 @@ import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class CustomUserDetailsService implements UserDetailsService {
......@@ -20,15 +22,24 @@ public class CustomUserDetailsService implements UserDetailsService {
@Override
@Transactional
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = userRepository.findByEmail(email)
.orElseThrow(() -> new UsernameNotFoundException("Utilisateur non trouvé avec l'email : " + email));
System.out.println("Tentative de connexion avec l'email : " + email);
Optional<User> optionalUser = userRepository.findByEmail(email);
if (optionalUser.isEmpty()) {
System.out.println("Utilisateur non trouvé !");
throw new UsernameNotFoundException("Utilisateur non trouvé avec l'email : " + email);
}
User user = optionalUser.get();
System.out.println("Utilisateur trouvé : " + user.getEmail() + " | Rôle : " + user.getRole());
return org.springframework.security.core.userdetails.User.builder()
.username(user.getEmail()) // L'email sert d'identifiant
.password(user.getPassword()) // Mot de passe hashé en BDD
.roles(user.getRole().name()) // Récupération du rôle
.roles("ROLE_" + user.getRole())
.build();
}
}
......@@ -3,7 +3,10 @@ package com.projet.projetIndu.security;
import com.projet.projetIndu.repositories.UserRepository;
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.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
......@@ -20,17 +23,34 @@ public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN") // Accès réservé aux admins
.requestMatchers("/doctors/**").hasRole("DOCTOR") // Accès aux médecins
.requestMatchers("/patients/**").hasRole("PATIENT") // Accès aux patients
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/login", "/register", "/css/**", "/js/**").permitAll()
.requestMatchers("/admin/**").hasAuthority("ROLE_ADMIN")
.requestMatchers("/doctors/**").hasAuthority("ROLE_DOCTOR")
.requestMatchers("/patients/**").hasAuthority("ROLE_PATIENT")
.anyRequest().authenticated()
)
.formLogin(form -> form
.loginPage("/login")
.usernameParameter("email")
.defaultSuccessUrl("/", true)
.passwordParameter("password")
.successHandler((request, response, authentication) -> {
// Gestion des redirections selon les rôles
String role = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.findFirst()
.orElse(""); // Prévient une exception si aucun rôle
if (role.equals("ROLE_ADMIN")) {
response.sendRedirect("/admin/dashboard");
} else if (role.equals("ROLE_DOCTOR")) {
response.sendRedirect("/doctors/dashboard");
} else if (role.equals("ROLE_PATIENT")) {
response.sendRedirect("/patients/dashboard");
} else {
response.sendRedirect("/"); // URL par défaut
}
})
.failureUrl("/login?error=true") // En cas d'échec d'authentification
.permitAll()
)
.logout(logout -> logout
......@@ -39,7 +59,6 @@ public class SecurityConfig {
.permitAll()
);
return http.build();
}
......@@ -49,4 +68,15 @@ public class SecurityConfig {
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http, BCryptPasswordEncoder passwordEncoder, UserDetailsService userDetailsService) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder);
return authenticationManagerBuilder.build();
}
}
\ No newline at end of file
......@@ -13,8 +13,8 @@
<h3 class="text-center mb-3">Connexion</h3>
<form th:action="@{/login}" method="post">
<div class="mb-3">
<label for="username" class="form-label">Nom d'utilisateur</label>
<input type="text" class="form-control" id="username" name="username" required>
<label for="email" class="form-label">Nom d'utilisateur</label>
<input type="text" class="form-control" id="email" name="email" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Mot de passe</label>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment