Open frodoe7 opened 6 months ago
@recrsn Do you think, I have to use another library to achieve this approach?
It doesn't depend on this library
it's more a conceptual probleme isn't depend on the library. here is some tips you can use for your issue :
Add a field to store previous passwords in your user schema. For example, you can name this field previousPasswords
and define it as an array of strings.
const userSchema = new Schema({
// ...
password: {
type: String,
required: true,
},
previousPasswords: [String], // Field to store previous passwords
// ...
});
When a user attempts to change, you can check if they are using a previous password.
const isPreviousPassword = user.previousPasswords.some(async (prevPassword) => {
return await bcrypt.compare(newPassword, prevPassword);
});
if (isPreviousPassword) {
// The new password is a previous password
// Handle this accordingly (e.g., return an error)
} else {
// The new password is valid
// Continue with the normal authentication process
}
When a user changes their password, instead of just hashing the new password, you can also add the old password to the previousPasswords
array.
const newPassword = "newPassword"; // Get the new password from the user
// Hashify and update the current password
user.password = await hashify(newPassword);
// Add the old password to the list of previous passwords
user.previousPasswords.push(oldPassword);
// Save the changes to the database
await user.save();
With this approach, you no longer need to simultaneously search through all stored hashes, as you have the previous passwords directly associated with the user.
Note: Replace hashify and searchPreviousPasswords with your actual functions for hashing and searching previous passwords in your application.
When the user change his password he add a new password to the table before adding it, I need to ensure he did not use that password before
so, I have array of hashes and the original password
here's the function which hashify the password
here's the function which search if the password is used before or not
That solution is not working
NodeJS version : 20.10.0 Bcrypt version : 5.1.1