fix: make password verification in JavaBeans

This commit is contained in:
kmitresse
2024-06-13 16:12:45 +02:00
parent 1dd75ea377
commit 96fc8a2c11
11 changed files with 85 additions and 53 deletions
@@ -20,7 +20,8 @@ public class ProfileBean {
private String oldEmail; private String oldEmail;
private String email; private String email;
private String oldPassword; private String oldPassword;
private String password; private String newPassword;
private String confirmPassword;
private String gender; private String gender;
private User user; private User user;
private HttpResponse error; private HttpResponse error;
@@ -37,6 +38,7 @@ public class ProfileBean {
EntityManager entityManager = EntityManagerProvider.getInstance(); EntityManager entityManager = EntityManagerProvider.getInstance();
entityManager.getTransaction().begin(); entityManager.getTransaction().begin();
DAO<User> userDAO; DAO<User> userDAO;
String errorMessage = "";
try { try {
userDAO= new Game_JPA_DAO_Factory().getDAOUser(); userDAO= new Game_JPA_DAO_Factory().getDAOUser();
// Vérification de l'existence de l'utilisateur // Vérification de l'existence de l'utilisateur
@@ -49,13 +51,17 @@ public class ProfileBean {
// Vérification de l'unicité de l'adresse e-mail // Vérification de l'unicité de l'adresse e-mail
User[] users = userDAO.findByField("email", email); User[] users = userDAO.findByField("email", email);
if (!oldEmail.equals(email) && users.length > 0) { if (!oldEmail.equals(email) && users.length > 0) {
error = new HttpResponse(HttpResponseCode.UNAUTHORIZED, translator.translate("profile_error_email")); errorMessage += translator.translate("profile_error_email");
entityManager.getTransaction().rollback();
return false;
} }
// Verification de l'ancien mot de passe // Verification de l'ancien mot de passe
if(!oldPassword.isEmpty() && !user.verifyPassword(oldPassword)) { if(!oldPassword.isEmpty() && !user.verifyPassword(oldPassword)) {
error = new HttpResponse(HttpResponseCode.UNAUTHORIZED, translator.translate("profile_error_old_password")); errorMessage += "<br>" + translator.translate("profile_error_old_password");
}
if(!newPassword.equals(confirmPassword)) {
errorMessage += "<br>" + translator.translate("profile_error_password");
}
if (!errorMessage.isEmpty()) {
error = new HttpResponse(HttpResponseCode.UNAUTHORIZED, errorMessage);
entityManager.getTransaction().rollback(); entityManager.getTransaction().rollback();
return false; return false;
} }
@@ -66,8 +72,8 @@ public class ProfileBean {
} }
// Mise à jour des informations de l'utilisateur // Mise à jour des informations de l'utilisateur
user.setEmail(email); user.setEmail(email);
if (!password.isEmpty()) { if (!newPassword.isEmpty()) {
user.setPassword(password); user.setPassword(newPassword);
} }
user.setGender(User.Gender.valueOf(gender)); user.setGender(User.Gender.valueOf(gender));
try { try {
@@ -126,11 +132,22 @@ public class ProfileBean {
* @param password le nouveau mot de passe de l'utilisateur * @param password le nouveau mot de passe de l'utilisateur
* @return l'entité * @return l'entité
*/ */
public ProfileBean setPassword(String password) { public ProfileBean setNewPassword(String password) {
this.password = password; this.newPassword = password;
return this; return this;
} }
/**
*
* @param confirmPassword la confirmation du nouveau mot de passe de l'utilisateur
* @return l'entité
*/
public ProfileBean setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
return this;
}
/** /**
* *
* @param gender le genre de l'utilisateur * @param gender le genre de l'utilisateur
@@ -23,6 +23,7 @@ public class RegisterBean implements Serializable {
private String username; private String username;
private String email; private String email;
private String password; private String password;
private String confirmPassword;
private String birth; private String birth;
private String gender; private String gender;
@@ -44,25 +45,33 @@ public class RegisterBean implements Serializable {
// Vérification de l'unicité du nom d'utilisateur et de l'adresse e-mail // Vérification de l'unicité du nom d'utilisateur et de l'adresse e-mail
try { try {
userDAO = jpaDaoFactory.getDAOUser(); userDAO = jpaDaoFactory.getDAOUser();
String errorMessage = "";
// Vérification de l'unicité du nom d'utilisateur // Vérification de l'unicité du nom d'utilisateur
User[] users = userDAO.findByField("username", username); User[] users = userDAO.findByField("username", username);
if (users.length > 0) { if (users.length > 0) {
error = new HttpResponse(HttpResponseCode.UNAUTHORIZED, translator.translate("register_error_username")); errorMessage += translator.translate("register_error_username");
return false;
} }
// Vérification de l'unicité de l'adresse e-mail // Vérification de l'unicité de l'adresse e-mail
users = userDAO.findByField("email", email); users = userDAO.findByField("email", email);
if (users.length > 0) { if (users.length > 0) {
error = new HttpResponse(HttpResponseCode.UNAUTHORIZED, translator.translate("register_error_email")); errorMessage += "<br>" + translator.translate("register_error_email");
}
// Vérification de la correspondance des mots de passe
if (!password.equals(confirmPassword)) {
errorMessage += "<br>" + translator.translate("register_error_password");
}
if (!errorMessage.isEmpty()) {
error = new HttpResponse(HttpResponseCode.UNAUTHORIZED, errorMessage);
return false; return false;
} }
} catch (DAOException e) { } catch (DAOException e) {
error = new HttpResponse(HttpResponseCode.INTERNAL_SERVER_ERROR, translator.translate("internal_error_1")); error = new HttpResponse(HttpResponseCode.INTERNAL_SERVER_ERROR, translator.translate("internal_error_1"));
return false; return false;
} }
// Creation de l'utilisateur // Creation de l'utilisateur
User user = new User(); User user = new User();
user.setUsername(username); user.setUsername(username);
@@ -121,6 +130,16 @@ public class RegisterBean implements Serializable {
return this; return this;
} }
/**
*
* @param confirmPassword la confirmation du mot de passe
* @return l'entité
*/
public RegisterBean setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
return this;
}
/** /**
* *
* @param email l'adresse e-mail * @param email l'adresse e-mail
@@ -18,6 +18,7 @@ public class ResetPasswordBean implements Serializable {
private String token; private String token;
private String password; private String password;
private String confirmPassword;
private String errorMessage; private String errorMessage;
private Translator translator; private Translator translator;
@@ -45,10 +46,18 @@ public class ResetPasswordBean implements Serializable {
RecoveryPasswordToken[] tokens = recoveryPasswordTokenDAO.findByField("token", token); RecoveryPasswordToken[] tokens = recoveryPasswordTokenDAO.findByField("token", token);
if (tokens.length == 0) { if (tokens.length == 0) {
errorMessage = "Ce token n'est pas valide"; errorMessage = "Ce token n'est pas valide";
entityManager.getTransaction().rollback();
return false; return false;
} }
RecoveryPasswordToken token = tokens[0]; RecoveryPasswordToken token = tokens[0];
// Verifier la correspondance des mots de passe
if (!password.equals(confirmPassword)) {
errorMessage = "Les mots de passe ne correspondent pas";
entityManager.getTransaction().rollback();
return false;
}
// Récupéreration de l'utilisateur associé au token // Récupéreration de l'utilisateur associé au token
User user = token.getUser(); User user = token.getUser();
if (user == null) { if (user == null) {
@@ -87,6 +96,16 @@ public class ResetPasswordBean implements Serializable {
return this; return this;
} }
/**
*
* @param confirmPassword la confirmation du nouveau mot de passe
* @return this
*/
public ResetPasswordBean setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
return this;
}
/** /**
* *
* @param translator le traducteur * @param translator le traducteur
@@ -65,16 +65,19 @@ public class ProfileServlet extends HttpServlet {
* @throws IOException si une erreur d'entrée/sortie survient * @throws IOException si une erreur d'entrée/sortie survient
*/ */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
Translator translator = (Translator) request.getSession().getAttribute("translator");
response.setContentType("application/json"); response.setContentType("application/json");
response.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
ProfileBean profileBean = new ProfileBean() ProfileBean profileBean = new ProfileBean()
.setTranslator(translator)
.setUsername(request.getParameter("username")) .setUsername(request.getParameter("username"))
.setOldEmail(request.getParameter("oldEmail")) .setOldEmail(request.getParameter("oldEmail"))
.setEmail(request.getParameter("email")) .setEmail(request.getParameter("email"))
.setOldPassword(request.getParameter("oldPassword")) .setOldPassword(request.getParameter("oldPassword"))
.setPassword(request.getParameter("password")) .setNewPassword(request.getParameter("password"))
.setConfirmPassword(request.getParameter("repassword"))
.setGender(request.getParameter("gender")) .setGender(request.getParameter("gender"))
; ;
@@ -50,14 +50,19 @@ public class RegisterServlet extends HttpServlet {
* @throws IOException si une erreur d'entrée/sortie survient * @throws IOException si une erreur d'entrée/sortie survient
*/ */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
Translator translator = (Translator) request.getSession().getAttribute("translator");
response.setContentType("application/json"); response.setContentType("application/json");
response.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
RegisterBean registerBean = new RegisterBean() RegisterBean registerBean = new RegisterBean()
.setTranslator(translator)
.setUsername(request.getParameter("username")) .setUsername(request.getParameter("username"))
.setEmail(request.getParameter("email")) .setEmail(request.getParameter("email"))
.setPassword(request.getParameter("password")) .setPassword(request.getParameter("password"))
.setConfirmPassword(request.getParameter("repassword"))
.setBirth(request.getParameter("birth")) .setBirth(request.getParameter("birth"))
.setGender(request.getParameter("gender")) .setGender(request.getParameter("gender"))
; ;
@@ -55,13 +55,16 @@ public class ResetPasswordServlet extends HttpServlet {
* @throws IOException si une erreur d'entrée/sortie survient * @throws IOException si une erreur d'entrée/sortie survient
*/ */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
Translator translator = (Translator) request.getSession().getAttribute("translator");
response.setContentType("application/json"); response.setContentType("application/json");
response.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
ResetPasswordBean resetPasswordBean = new ResetPasswordBean() ResetPasswordBean resetPasswordBean = new ResetPasswordBean()
.setTranslator(translator)
.setToken(request.getParameter("token")) .setToken(request.getParameter("token"))
.setPassword(request.getParameter("password")) .setPassword(request.getParameter("password"))
.setConfirmPassword(request.getParameter("repassword"))
; ;
Gson gson = new Gson(); Gson gson = new Gson();
@@ -20,15 +20,12 @@ public class Translator {
public enum Language {EN, FR} public enum Language {EN, FR}
public Translator(Language language) { public Translator(Language language) {
System.out.println("Creating translator for language: " + language.name());
this.language = language.name(); this.language = language.name();
this.parser = new JsonParser(); this.parser = new JsonParser();
} }
public static Translator generateTranslator(HttpSession session , ServletContext context) { public static Translator generateTranslator(HttpSession session , ServletContext context) {
Translator translator; Translator translator;
System.out.println("null?" + session.getAttribute("language"));
System.out.println("language EN ??: " + session.getAttribute("language").equals(Translator.Language.EN.name()));
if (session.getAttribute("language") != null && session.getAttribute("language").equals(Translator.Language.EN.name())) { if (session.getAttribute("language") != null && session.getAttribute("language").equals(Translator.Language.EN.name())) {
translator = new Translator(Translator.Language.EN); translator = new Translator(Translator.Language.EN);
} else { } else {
@@ -235,6 +235,10 @@
"EN": "Incorrect old password", "EN": "Incorrect old password",
"FR": "Ancien mot de passe incorrect" "FR": "Ancien mot de passe incorrect"
}, },
"profile_error_password" : {
"EN": "New passwords do not match",
"FR": "Les nouveaux mots de passe ne correspondent pas"
},
"statistics_title" : { "statistics_title" : {
"EN": "Statistics", "EN": "Statistics",
"FR": "Statistiques" "FR": "Statistiques"
@@ -21,19 +21,6 @@ profileForm.addEventListener("submit", onSubmit);
function onSubmit(event) { function onSubmit(event) {
event.preventDefault(); event.preventDefault();
const oldPassword = profileForm.querySelector("input[name='oldPassword']");
const password = profileForm.querySelector("input[name='password']");
const repassword = profileForm.querySelector("input[name='repeat-password']");
// Check if the password and the confirmation password are the same
if (oldPassword.value !== "" && password.value !== repassword.value) {
if (languageSelector.value === "EN") {
onError(new Error("Passwords do not match"), [oldPassword, password, repassword]);
return;
}
onError(new Error("Les mots de passe ne correspondent pas"), [oldPassword, password, repassword]);
return;
}
const {action, method} = profileForm; const {action, method} = profileForm;
const url = new URL(action); const url = new URL(action);
@@ -10,24 +10,12 @@ registerForm.addEventListener("submit", onSubmit)
function onSubmit(event) { function onSubmit(event) {
event.preventDefault(); event.preventDefault();
const password = registerForm.querySelector("input[name='password']");
const repassword = registerForm.querySelector("input[name='repassword']");
// Check if the password and the confirmation password are the same
if (password.value !== repassword.value) {
if (languageSelector.value === "EN") {
onError(new Error("Passwords do not match"), [oldPassword, password, repassword]);
return;
}
onError(new Error("Les mots de passe ne correspondent pas"), [oldPassword, password, repassword]);
return;
}
const {action, method} = registerForm; const {action, method} = registerForm;
const url = new URL(action); const url = new URL(action);
const contextPath = url.href.substring(0, url.href.lastIndexOf("/") + 1); const contextPath = url.href.substring(0, url.href.lastIndexOf("/") + 1);
inputs.forEach(input => url.searchParams.append(input.name, input.value)); inputs.forEach(input => url.searchParams.append(input.name, input.value));
console.log(url.href);
fetch(url, {headers: {"Content-Type": "application/json"}, method}) fetch(url, {headers: {"Content-Type": "application/json"}, method})
.then(res => res.json()) .then(res => res.json())
@@ -14,16 +14,6 @@ resetPasswordForm.addEventListener("submit", onSubmit)
function onSubmit(event) { function onSubmit(event) {
event.preventDefault(); event.preventDefault();
// Check if the password and the confirmation password are the same
if (passwordInput.value !== repasswordInput.value) {
if (languageSelector.value === "EN") {
onError(new Error("Passwords do not match"), [oldPassword, password, repassword]);
return;
}
onError(new Error("Les mots de passe ne correspondent pas"), [oldPassword, password, repassword]);
return;
}
const {action, method} = resetPasswordForm; const {action, method} = resetPasswordForm;
const url = new URL(action); const url = new URL(action);