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 email;
private String oldPassword;
private String password;
private String newPassword;
private String confirmPassword;
private String gender;
private User user;
private HttpResponse error;
@@ -37,6 +38,7 @@ public class ProfileBean {
EntityManager entityManager = EntityManagerProvider.getInstance();
entityManager.getTransaction().begin();
DAO<User> userDAO;
String errorMessage = "";
try {
userDAO= new Game_JPA_DAO_Factory().getDAOUser();
// 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
User[] users = userDAO.findByField("email", email);
if (!oldEmail.equals(email) && users.length > 0) {
error = new HttpResponse(HttpResponseCode.UNAUTHORIZED, translator.translate("profile_error_email"));
entityManager.getTransaction().rollback();
return false;
errorMessage += translator.translate("profile_error_email");
}
// Verification de l'ancien mot de passe
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();
return false;
}
@@ -66,8 +72,8 @@ public class ProfileBean {
}
// Mise à jour des informations de l'utilisateur
user.setEmail(email);
if (!password.isEmpty()) {
user.setPassword(password);
if (!newPassword.isEmpty()) {
user.setPassword(newPassword);
}
user.setGender(User.Gender.valueOf(gender));
try {
@@ -126,11 +132,22 @@ public class ProfileBean {
* @param password le nouveau mot de passe de l'utilisateur
* @return l'entité
*/
public ProfileBean setPassword(String password) {
this.password = password;
public ProfileBean setNewPassword(String password) {
this.newPassword = password;
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
@@ -23,6 +23,7 @@ public class RegisterBean implements Serializable {
private String username;
private String email;
private String password;
private String confirmPassword;
private String birth;
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
try {
userDAO = jpaDaoFactory.getDAOUser();
String errorMessage = "";
// Vérification de l'unicité du nom d'utilisateur
User[] users = userDAO.findByField("username", username);
if (users.length > 0) {
error = new HttpResponse(HttpResponseCode.UNAUTHORIZED, translator.translate("register_error_username"));
return false;
errorMessage += translator.translate("register_error_username");
}
// Vérification de l'unicité de l'adresse e-mail
users = userDAO.findByField("email", email);
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;
}
} catch (DAOException e) {
error = new HttpResponse(HttpResponseCode.INTERNAL_SERVER_ERROR, translator.translate("internal_error_1"));
return false;
}
// Creation de l'utilisateur
User user = new User();
user.setUsername(username);
@@ -121,6 +130,16 @@ public class RegisterBean implements Serializable {
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
@@ -18,6 +18,7 @@ public class ResetPasswordBean implements Serializable {
private String token;
private String password;
private String confirmPassword;
private String errorMessage;
private Translator translator;
@@ -45,10 +46,18 @@ public class ResetPasswordBean implements Serializable {
RecoveryPasswordToken[] tokens = recoveryPasswordTokenDAO.findByField("token", token);
if (tokens.length == 0) {
errorMessage = "Ce token n'est pas valide";
entityManager.getTransaction().rollback();
return false;
}
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
User user = token.getUser();
if (user == null) {
@@ -87,6 +96,16 @@ public class ResetPasswordBean implements Serializable {
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
@@ -65,16 +65,19 @@ public class ProfileServlet extends HttpServlet {
* @throws IOException si une erreur d'entrée/sortie survient
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
Translator translator = (Translator) request.getSession().getAttribute("translator");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
ProfileBean profileBean = new ProfileBean()
.setTranslator(translator)
.setUsername(request.getParameter("username"))
.setOldEmail(request.getParameter("oldEmail"))
.setEmail(request.getParameter("email"))
.setOldPassword(request.getParameter("oldPassword"))
.setPassword(request.getParameter("password"))
.setNewPassword(request.getParameter("password"))
.setConfirmPassword(request.getParameter("repassword"))
.setGender(request.getParameter("gender"))
;
@@ -50,14 +50,19 @@ public class RegisterServlet extends HttpServlet {
* @throws IOException si une erreur d'entrée/sortie survient
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
Translator translator = (Translator) request.getSession().getAttribute("translator");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
RegisterBean registerBean = new RegisterBean()
.setTranslator(translator)
.setUsername(request.getParameter("username"))
.setEmail(request.getParameter("email"))
.setPassword(request.getParameter("password"))
.setConfirmPassword(request.getParameter("repassword"))
.setBirth(request.getParameter("birth"))
.setGender(request.getParameter("gender"))
;
@@ -55,13 +55,16 @@ public class ResetPasswordServlet extends HttpServlet {
* @throws IOException si une erreur d'entrée/sortie survient
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
Translator translator = (Translator) request.getSession().getAttribute("translator");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
ResetPasswordBean resetPasswordBean = new ResetPasswordBean()
.setTranslator(translator)
.setToken(request.getParameter("token"))
.setPassword(request.getParameter("password"))
.setConfirmPassword(request.getParameter("repassword"))
;
Gson gson = new Gson();
@@ -20,15 +20,12 @@ public class Translator {
public enum Language {EN, FR}
public Translator(Language language) {
System.out.println("Creating translator for language: " + language.name());
this.language = language.name();
this.parser = new JsonParser();
}
public static Translator generateTranslator(HttpSession session , ServletContext context) {
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())) {
translator = new Translator(Translator.Language.EN);
} else {
@@ -235,6 +235,10 @@
"EN": "Incorrect old password",
"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" : {
"EN": "Statistics",
"FR": "Statistiques"
@@ -21,19 +21,6 @@ profileForm.addEventListener("submit", onSubmit);
function onSubmit(event) {
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 url = new URL(action);
@@ -10,24 +10,12 @@ registerForm.addEventListener("submit", onSubmit)
function onSubmit(event) {
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 url = new URL(action);
const contextPath = url.href.substring(0, url.href.lastIndexOf("/") + 1);
inputs.forEach(input => url.searchParams.append(input.name, input.value));
console.log(url.href);
fetch(url, {headers: {"Content-Type": "application/json"}, method})
.then(res => res.json())
@@ -14,16 +14,6 @@ resetPasswordForm.addEventListener("submit", onSubmit)
function onSubmit(event) {
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 url = new URL(action);