Correction validation all formulaire version final

This commit is contained in:
jleroy
2024-04-25 14:54:23 +02:00
parent 8ebddc6d18
commit 7513587b76
5 changed files with 156 additions and 6 deletions

View File

@@ -1,5 +1,6 @@
package fr.eni.enchere.controllers; package fr.eni.enchere.controllers;
import com.fasterxml.jackson.databind.JsonNode;
import fr.eni.enchere.bll.ArticleService; import fr.eni.enchere.bll.ArticleService;
import fr.eni.enchere.bll.CategorieService; import fr.eni.enchere.bll.CategorieService;
import fr.eni.enchere.bll.RetraitService; import fr.eni.enchere.bll.RetraitService;
@@ -9,21 +10,31 @@ import fr.eni.enchere.bo.Categorie;
import fr.eni.enchere.bo.Retrait; import fr.eni.enchere.bo.Retrait;
import fr.eni.enchere.bo.UserProfil; import fr.eni.enchere.bo.UserProfil;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
@Controller() @Controller()
@RequestMapping("/article") @RequestMapping("/article")
public class ArticleController { public class ArticleController {
private final String API_URL = "https://apicarto.ign.fr/api/codes-postaux/communes/";
@Autowired @Autowired
private final ArticleService articleService; private final ArticleService articleService;
private final UserService userService; private final UserService userService;
@@ -88,7 +99,8 @@ public class ArticleController {
@RequestParam("code_postal") String code_postal, @RequestParam("code_postal") String code_postal,
@RequestParam("ville") String ville, @RequestParam("ville") String ville,
@RequestParam("dateDebut") String dateDebut, @RequestParam("dateDebut") String dateDebut,
@RequestParam("dateFin") String dateFin) { @RequestParam("dateFin") String dateFin,
RedirectAttributes redirectAttributes) {
//Récupérer l'utilisateur pour set l'article //Récupérer l'utilisateur pour set l'article
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName(); String username = authentication.getName();
@@ -107,10 +119,99 @@ public class ArticleController {
dDateDebut = format.parse(dateDebut); dDateDebut = format.parse(dateDebut);
dDateFin = format.parse(dateFin); dDateFin = format.parse(dateFin);
} catch (ParseException e) { } catch (ParseException e) {
e.printStackTrace(); redirectAttributes.addAttribute("erreur", "La date de début n'est pas valide.");
redirectAttributes.addAttribute("erreur", "La date de fin n'est pas valide.");
} }
article.setDateDebutEnch(dDateDebut); article.setDateDebutEnch(dDateDebut);
article.setDateFinEnch(dDateFin); article.setDateFinEnch(dDateFin);
//Vérification du formulaire
//Vérification du nom de l'article
String regex = "^[a-zA-Z0-9 ]*$";
if (article.getNom().length() < 3){
redirectAttributes.addAttribute("erreur", "Le nom de l'article doit contenir au moin 3 caractères.");
return "redirect:/article/new";
}
if (!Pattern.matches(regex, article.getNom())){
redirectAttributes.addAttribute("erreur", "Le nom de l'article ne doit pas contenir de caractère speciaux.");
return "redirect:/article/new";
}
//Vérification description de l'article
if (article.getDesc().length() < 20){
redirectAttributes.addAttribute("erreur", "La description de l'article doit contenir au moin 20 caractères.");
return "redirect:/article/new";
}
//Vérification de la photo
if (article.getPhoto() != null && !article.getPhoto().isEmpty()) {
if (article.getPhoto().getSize() > 5 * 1024 * 1024) {
redirectAttributes.addAttribute("erreur", "La photo ne doit pas faire plus de 5 Mo.");
return "redirect:/article/new";
}
if (!article.getPhoto().getOriginalFilename().toLowerCase().endsWith(".jpg")) {
redirectAttributes.addAttribute("erreur", "L'image doit avoir une extension .jpg.");
return "redirect:/article/new";
}
}
//Vérification du prix initial
if (article.getPrixInitial() > 2000000000 && article.getPrixInitial() < 0){
redirectAttributes.addAttribute("erreur", "Le prix doit être compris entre 0 et 2 000 000 000 crédits.");
return "redirect:/article/new";
}
//Vérifier les dates
LocalDate dateDebutEnch = LocalDate.parse(dateDebut);
LocalDate dateActuelle = LocalDate.now();
if (dateDebutEnch.isBefore(dateActuelle)) {
redirectAttributes.addAttribute("erreur", "La date de début d'enchère ne peux pas être infèrieur à la date du jour.");
return "redirect:/article/new";
}
LocalDate dateFinEnch = LocalDate.parse(dateFin);
LocalDate datePlusUnJour = LocalDate.now().plusDays(1);
if (dateFinEnch.isBefore(datePlusUnJour)) {
redirectAttributes.addAttribute("erreur", "La date de début d'enchère ne peux pas être infàrieur à la date du jour + 1.");
return "redirect:/article/new";
}
//Vérification rue
if (!Pattern.matches("^[a-zA-Z0-9 ]+$", retrait.getRue())){
redirectAttributes.addAttribute("erreur", "Le rue n'est pas valide.");
return "redirect:/article/new";
}
if (retrait.getRue().isEmpty()){
redirectAttributes.addAttribute("erreur", "Entrer une rue.");
return "redirect:/article/new";
}
//Vérifier code postal et ville
if(Pattern.matches("^\\d{5}$", retrait.getCode_postale())){
//Récupérer les villes en fonction du code postal
RestTemplate restTemplate = new RestTemplate();
List<String> villeCodePostal = new ArrayList<>(); // Initialisez la liste pour éviter les NullPointerException
String apiUrl = API_URL + retrait.getCode_postale();
ResponseEntity<JsonNode> response = restTemplate.getForEntity(apiUrl, JsonNode.class); // Désérialiser en JsonNode
if (response.getStatusCode().is2xxSuccessful()) {
JsonNode responseBody = response.getBody();
if (responseBody.isArray()) { // Vérifiez si le corps de la réponse est un tableau JSON
for (JsonNode node : responseBody) {
String cityName = node.get("nomCommune").asText();
villeCodePostal.add(cityName);
System.out.println(cityName);
}
} else {
redirectAttributes.addAttribute("erreur", "Une erreur est survenue !");
return "redirect:/article/new";
}
if (!villeCodePostal.contains(userProfile.getVille())) {
String showCity = String.join(", ", villeCodePostal);
redirectAttributes.addAttribute("erreur", "Essayer : " + showCity);
return "redirect:/article/new";
}
} else {
redirectAttributes.addAttribute("erreur", "La ville n'est pas valide.");
return "redirect:/article/new";
}
} else {
redirectAttributes.addAttribute("erreur", "Le code postal n'est pas valide.");
return "redirect:/article/new";
}
//Validation du formulaire
retrait.setNumArticle(articleService.saveArticle(article)); retrait.setNumArticle(articleService.saveArticle(article));
retraitService.setRetrait(retrait); retraitService.setRetrait(retrait);
return "redirect:/accueil"; return "redirect:/accueil";

View File

@@ -9,6 +9,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.apache.commons.validator.routines.EmailValidator; import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
import fr.eni.enchere.bll.UserService; import fr.eni.enchere.bll.UserService;
@@ -17,6 +19,8 @@ import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.util.UriComponentsBuilder;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
@@ -45,6 +49,11 @@ public class InscriptionController {
@GetMapping @GetMapping
public String viewInscription(Model model) { public String viewInscription(Model model) {
// Vérifier si l'utilisateur est déjà authentifié
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!authentication.getName().equals("anonymousUser")){
return "redirect:/accueil";
}
model.addAttribute("userProfile", new UserProfil()); model.addAttribute("userProfile", new UserProfil());
return "inscription"; return "inscription";
} }
@@ -56,6 +65,9 @@ public class InscriptionController {
if (allUsernames.contains(userProfile.getPseudo())) { if (allUsernames.contains(userProfile.getPseudo())) {
result.rejectValue("pseudo", "error.userProfile", "Ce pseudo est déjà utilisé."); result.rejectValue("pseudo", "error.userProfile", "Ce pseudo est déjà utilisé.");
} }
if (userProfile.getPseudo().isEmpty()){
result.rejectValue("pseudo", "error.userProfile", "Entrer un pseudo.");
}
// Vérifier si l'e-mail existe déjà // Vérifier si l'e-mail existe déjà
List<String> allEmails = userService.listEmail(); List<String> allEmails = userService.listEmail();
if (allEmails.contains(userProfile.getEmail())) { if (allEmails.contains(userProfile.getEmail())) {
@@ -78,6 +90,9 @@ public class InscriptionController {
if (!Pattern.matches("^[a-zA-Z0-9 ]+$", userProfile.getRue())){ if (!Pattern.matches("^[a-zA-Z0-9 ]+$", userProfile.getRue())){
result.rejectValue("rue", "error.userProfile", "Le rue n'est pas valide."); result.rejectValue("rue", "error.userProfile", "Le rue n'est pas valide.");
} }
if (userProfile.getRue().isEmpty()){
result.rejectValue("rue", "error.userProfile", "Entrer une rue.");
}
//Vérifier code postal et ville //Vérifier code postal et ville
if(Pattern.matches("^\\d{5}$", userProfile.getCode_postal())){ if(Pattern.matches("^\\d{5}$", userProfile.getCode_postal())){
//Récupérer les villes en fonction du code postal //Récupérer les villes en fonction du code postal
@@ -93,7 +108,7 @@ public class InscriptionController {
villeCodePostal.add(cityName); villeCodePostal.add(cityName);
} }
} else { } else {
result.rejectValue("ville", "error.userProfile", "La réponse de l'API n'est pas un tableau JSON."); result.rejectValue("ville", "error.userProfile", "Une erreur est survenue !");
} }
if (!villeCodePostal.contains(userProfile.getVille())) { if (!villeCodePostal.contains(userProfile.getVille())) {
String showCity = String.join(", ", villeCodePostal); String showCity = String.join(", ", villeCodePostal);
@@ -109,12 +124,24 @@ public class InscriptionController {
if (!confirmPassword.equals(userProfile.getPassword())) { if (!confirmPassword.equals(userProfile.getPassword())) {
result.rejectValue("password", "error.userProfile", "Les mots de passe ne correspond pas."); result.rejectValue("password", "error.userProfile", "Les mots de passe ne correspond pas.");
} }
// Vérifier si le mot de passe est sécurisé
String passwordRegex = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}$";
Pattern pattern = Pattern.compile(passwordRegex);
// Vérifier si le mot de passe correspond à l'expression régulière
if (!pattern.matcher(userProfile.getPassword()).matches()){
result.rejectValue("password", "error.userProfile", "Le mot de passe ne correspond pas aux critères de sécurité.");
}
// Si des erreurs de validation sont détectées, retourner à la page de création de compte // Si des erreurs de validation sont détectées, retourner à la page de création de compte
if (result.hasErrors()) { if (result.hasErrors()) {
return "inscription"; return "inscription";
} }
// Sinon, enregistrer l'utilisateur et rediriger vers la page de connexion // Sinon, enregistrer l'utilisateur et rediriger vers la page de connexion
//userService.setUtilisateur(userProfile); userService.setUtilisateur(userProfile);
return "redirect:/login"; // Dans votre méthode setUser après la validation réussie
UriComponentsBuilder builder = UriComponentsBuilder.fromPath("/login");
builder.queryParam("username", userProfile.getPseudo());
builder.queryParam("password", userProfile.getPassword());
// Rediriger vers la méthode POST de /login avec les paramètres
return "redirect:" + builder.toUriString();
} }
} }

View File

@@ -3,6 +3,8 @@ package fr.eni.enchere.controllers;
import fr.eni.enchere.bll.UserService; import fr.eni.enchere.bll.UserService;
import fr.eni.enchere.bo.UserProfil; import fr.eni.enchere.bo.UserProfil;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@@ -22,6 +24,11 @@ public class LoginController {
@GetMapping("/login") @GetMapping("/login")
public String login(Model modele) { public String login(Model modele) {
// Vérifier si l'utilisateur est déjà authentifié
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!authentication.getName().equals("anonymousUser")){
return "redirect:/accueil";
}
return "security/login"; return "security/login";
} }

View File

@@ -13,6 +13,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import java.util.regex.Pattern;
@Controller() @Controller()
@RequestMapping("/profil") @RequestMapping("/profil")
public class ProfilController { public class ProfilController {
@@ -110,6 +112,14 @@ public class ProfilController {
result.rejectValue("confirmPassword", "invalid", "La confirmation du mot de passe ne correspond pas au nouveau mot de passe"); result.rejectValue("confirmPassword", "invalid", "La confirmation du mot de passe ne correspond pas au nouveau mot de passe");
return "editProfil"; // Rediriger vers la page de modification du profil avec une erreur return "editProfil"; // Rediriger vers la page de modification du profil avec une erreur
} }
// Vérifier si le mot de passe est sécurisé
String passwordRegex = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}$";
Pattern pattern = Pattern.compile(passwordRegex);
// Vérifier si le mot de passe correspond à l'expression régulière
if (!pattern.matcher(userProfile.getNewPassword()).matches()){
result.rejectValue("confirmPassword", "invalid", "Le mot de passe ne correspond pas aux critères de sécurité.");
return "editProfil";
}
// Mettez à jour le mot de passe de l'utilisateur avec le nouveau mot de passe // Mettez à jour le mot de passe de l'utilisateur avec le nouveau mot de passe
userService.setUtilisateur(userProfile); userService.setUtilisateur(userProfile);
return "redirect:/profil"; // Rediriger vers la page de profil après la modification réussie return "redirect:/profil"; // Rediriger vers la page de profil après la modification réussie

View File

@@ -37,7 +37,7 @@
<!-- Mise à prix --> <!-- Mise à prix -->
<div> <div>
<label for="prix">Mise à prix:</label> <label for="prix">Mise à prix:</label>
<input type="number" id="prix" th:field="*{prixInitial}" min="0" step="0.01" required> <input type="number" id="prix" th:field="*{prixInitial}" min="0" max="2000000000" step="0.01" required>
</div> </div>
<!-- Date début enchère --> <!-- Date début enchère -->
@@ -71,6 +71,11 @@
<div> <div>
<button type="submit">Enregistrer</button> <button type="submit">Enregistrer</button>
</div> </div>
<!-- En cas d'erreur -->
<div th:if="${param.erreur != null}">
<p style="color: red;" th:text="${param.erreur}"></p>
</div>
</form> </form>
<form th:action="@{/accueil}" method="post"> <form th:action="@{/accueil}" method="post">
<button type="submit">Annuler</button> <button type="submit">Annuler</button>