Hi,
For reference I’m new to Next.js and authentication.
In the exercises in the ‘Authentication with Next Auth’ I am trying to create a change password page.
I have created a client page which takes the old and new password and now I’m trying to create an api route where I compare the old and new passwords to I can update the hashed password in the database.
However, I’m struggling in that I’m not sure how to compare the current password with the old, in fact I’m not even sure if this is the approach I want to take (i.e. it’s not even possible to compare hashed passwords so it’s the wrong approach etc).
Could someone point me in the right direction with how I’m supposed to approach this, am I missing something obvious?
Assume you have this form:
new password: [ ]
confirm password: [ ]
old password: [ ]
Step 1: if newPassword != confirmPassword - error
Step 2: If newPassword does not meet password requirements - error
Step 3: Use bcrypt on oldPassword to get a string hashedOldPassword
Step 4: Does hashedOldPassword equal hashedPassword in the user table?
Step 5: If they match - hash newPassword and store hashedNewPassword into the user table.
Hi @JerryHobby, thanks for your response, is it actually possible to do step 3?
I found the below which makes me wonder if I’m following the right approach?
Hashing is a software process of generating fixed character length hash values for a text file. This is a one-way function meaning the original text file cannot be generated back from the hash value .
That is correct. It is one way. Meaning you cannot retrieve the password back from encoding. But you validate by encoding the new password and comparing.
This prevents anyone from downloading the password file and using it to access the site. It’s pretty clever really. Passwords cannot be unencrypted. So you compare encrypted to encrypted and that does work.
Ah, yes of course, that makes sense, thank-you!
I had a similar issue when working with password changes in Next.js. To compare passwords, hash the old password from the client and compare it with the hashed password in your database. For updating, hash the new password and store it.
If you’re unsure about this approach, consider using a library like bcrypt for password hashing and comparison. You can also check how to generate strong password here if you’re struggling. It’s really handy for creating secure passwords.