I have got some issues about bcrypt is that changing password.
Users.js
import Users from "../db/users";
import ApiError from "../errors/ApiError";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import getUserIp from "../middlewares/getUserIP";
import Session from "../middlewares/Session";
import sendVerificationEmail from "../middlewares/VerificationEmail";
export default (router) => {
router.put("/user/change-password", Session, async (req, res) => {
const { oldPassword, newPassword, confirmPassword } = req.body;
const user = req.user;
try {
const existingUser = await Users.findById(user._id);
if (!existingUser) {
throw new ApiError("User Not Found", 404, "notFoundUser");
}
const isMatchPassword = await bcrypt.compare(
oldPassword,
existingUser.password
);
if (!isMatchPassword) {
throw new ApiError(
"Incorrect old password",
404,
"incorrectOldPassword"
);
}
if (newPassword !== confirmPassword) {
throw new ApiError(
"New password and confirm password do not match",
404,
"passwordsDoNotMatch"
);
}
const isSamePassword = await bcrypt.compare(
newPassword,
existingUser.password
);
if (isSamePassword) {
throw new ApiError(
"New Password cannot be the same as the old password",
400,
"sameAsOldPassword"
);
}
const hashedPassword = await bcrypt.hash(newPassword, 10);
existingUser.password = hashedPassword;
await existingUser.save();
console.log("Old Password (unhashed):", oldPassword);
console.log("New Password (unhashed):", newPassword);
console.log("Old Password (hashed):", existingUser.password);
console.log("New Password (hashed):", hashedPassword);
return res
.status(200)
.json({ message: "Password has been changed successfully", user });
} catch (error) {
console.log(error);
res.status(error.statusCode || 500).json({
message: error.message || "Password change failed",
code: error.code || "passwordChangeFailed",
});
}
});
};
So my issue is that when i change password as you see it gets back a hashed password in log space. But it does not upload the hashed password what i logged. It uploads another hashed password, as you can see in the pictures.
This is my logged and it is also true hashed password.
so this is also my user hashed password after the change password.
Users Models.
import mongoose from "mongoose";
import bcrypt from "bcryptjs";
import generatedId from "../utils/uuid";
const Schema = mongoose.Schema;
const { ObjectId } = Schema.Types;
const randomColorGenerator = () => {
return Math.floor(Math.random() * 16777215).toString(16);
};
const UserSchema = new Schema(
{
uuid: {
type: String,
default: generatedId(),
unique: true,
required: true,
},
locale: {
type: String,
required: true,
default: "tr",
enum: ["tr", "en"],
},
role: {
type: String,
required: true,
default: "user",
enum: ["user", "admin"],
},
name: {
type: String,
required: true,
},
surname: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
phoneNumber: {
type: String,
required: true,
unique: true,
},
identityNumber: {
type: String,
required: true,
default: "00000000000",
},
password: {
type: String,
required: true,
},
avatarColor: {
type: String,
default: randomColorGenerator(),
required: true,
},
address: {
//fatura ve sipariş adresi diye ikiye ayrılabilir
type: String,
required: true,
},
city: {
type: String,
required: true,
},
country: {
type: String,
required: true,
default: "Turkey",
},
zipCode: {
type: String,
required: true,
},
ip: {
type: String,
required: true,
//default: "85.34.78.112", //cihazın ip'sini alır
},
isVerified: {
type: Boolean,
default: false,
},
cardUserKey: {
type: String,
required: false,
unique: true,
},
},
{
_id: true,
collection: "users",
timestamps: true,
toJSON: {
transform: (doc, ret) => {
delete ret.__v;
delete ret.password;
return {
...ret,
};
},
},
}
);
UserSchema.pre("save", async function (next) {
try {
// this.password = await bcrypt.hash(this.password, 10);
if (this.isModified("password")) {
//password incorrect hatasını böyle çözdük
this.password = await bcrypt.hash(this.password, 10);
}
return next();
} catch (err) {
return next(err);
}
next();
});
const Users = mongoose.model("Users", UserSchema);
export default Users;
Login route.
router.post("/login", async (req, res) => {
const { email, password } = req.body;
const user = await Users.findOne({ email });
if (!email || !password) {
throw new ApiError(
"Email and Password is required",
401,
"requiredEmailAndPassword"
);
}
if (!user) {
throw new ApiError(
"Incorrect Password or email2",
401,
"userOrPasswordIncorrect"
);
}
if (user.isVerified == false) {
throw new ApiError(
"You have to verificate your account.",
401,
"accountNotVerified"
);
}
const passwordConfirmed = await bcrypt.compare(password, user.password);
console.log("kullanıcı girdisi:", password);
console.log("hashlenmiş hali:", user.password);
if (passwordConfirmed) {
const userJson = user.toJSON();
const token = jwt.sign(userJson, process.env.JWT_SECRET);
res.json({
token: `Bearer ${token}`,
user: userJson,
});
} else {
throw new ApiError(
"Incorrect Password or email",
401,
"userOrPasswordIncorrect"
);
}
});
So there is a big problem is that when i copy logged hashed password and then ı paste it to manually in mongodb users data, ı can login. But as you see in second picture hashed password does not work. Instead of that logged password works.