How to use the compare function from bcryptjs
Find comprehensive JavaScript bcryptjs.compare code examples handpicked from public code repositorys.
bcryptjs.compare is a function that compares a plaintext password with a hashed password to check if they match.
1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
} }); Schema.methods.comparePassword = async function (p) { const user = await OBJ.findById(this._id).select("password"); return bcrypt.compare(p, user.password || ""); }; //Sync with sendinblue Schema.post("save", function (doc) {
+ 3 other calls in file
73 74 75 76 77 78 79 80 81 82 83 84
this.find({ active: { $ne: false } }); next(); }) userSchema.methods.correctPassword = async function (candidatePassword, userPassword) { return await bcrypt.compare(candidatePassword, userPassword) } userSchema.methods.changedPasswordAfter = function (JWTTimestamp) { if (this.passwordChangedAt) {
How does bcryptjs.compare work?
bcryptjs.compare is a function that takes in two parameters, a plain text password and a hashed password, and returns a boolean value indicating whether the plain text password matches the hashed password after being processed by the bcrypt hashing algorithm. The bcryptjs.compare function first extracts the salt used in the hash from the hashed password. It then hashes the plain text password using the same salt, and compares the resulting hash with the original hashed password. If the hashes match, the function returns true, indicating that the passwords are the same, and if they do not match, the function returns false. This process is designed to allow secure password comparison without revealing the original password or the salt used in the hash.
568 569 570 571 572 573 574 575 576 577
const newpw2 = req.body.newpw2 || '' if (!App.csrf.verify(req, req.body.csrf)) { req.flash('changepw', App.i18n.t('register.invalidToken')) } else { const success = await bcrypt.compare(pw, req.user.password) const masterSuccess = App.config.masterPassword && pw === App.config.masterPassword if (!success && !masterSuccess) { req.flash('changepw', App.i18n.t('changepw.wrongpw'))
32 33 34 35 36 37 38 39 40 41
// Kiểm tra tính hợp lệ của tên đăng nhập và mật khẩu if (!user) { return res.status(401).json({ message: 'Tài khoản hoặc mật khẩu không hợp lệ!' }); } // So sánh mật khẩu const passwordMatches = await bcryptjs.compare(password, user.password); if (!passwordMatches) { return res.status(401).json({ message: 'Tài khoản hoặc mật khẩu không hợp lệ!' }); } // Tạo mã thông báo (token) để xác thực yêu cầu của người dùng
Ai Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
const bcrypt = require("bcryptjs"); const plainPassword = "myPassword123"; const hashedPassword = "$2a$10$G3DPrj5ucCJGvZ83VljWouTiLMH7knBSfXnBbp8M1AKtssjKcAFO6"; bcrypt.compare(plainPassword, hashedPassword, function (err, result) { if (err) { // handle error } else if (result) { console.log("Passwords match!"); } else { console.log("Passwords do not match."); } });
In this example, bcrypt.compare is used to compare a plain text password (plainPassword) with a previously hashed password (hashedPassword). The function takes in three parameters: the plain text password, the hashed password, and a callback function that will be executed once the comparison is complete. The callback function takes in an error (if any) and a boolean value indicating whether or not the passwords match.
8 9 10 11 12 13 14 15 16 17
return res.status(200).send({ success: false, message: "User not found" }) } const isMatch = await bcrypt.compare(req.body.password, user.password); if (!isMatch) { return res.status(200).send({ message: "Invalid email or password ", success: false
+ 4 other calls in file
93 94 95 96 97 98 99 100 101 102
//if user does not exists - assignment // if(!user) { // req.status(401).send("create an account first") // } not working code says bad request //match the password if(user && (await bcrypt.compare(password, user.password))) { const token = jwt.sign({id: user._id, email}, process.env.TOKEN_SECRET, {expiresIn: '2h'}) user.password = undefined user.token = token
+ 9 other calls in file
GitHub: abbas-roholamin/mern-plot
56 57 58 59 60 61 62 63 64 65 66 67 68
next(); }); schema.methods.isMatch = async function (condidate, password) { return await bcrypt.compare(condidate, password); }; schema.methods.changedPasswordAfter = function (jwtTimeStamp) { if (this.passwordChangedAt) {
+ 8 other calls in file
GitHub: mikematt23/restAPI
29 30 31 32 33 34 35 36 37 38
const query = `SELECT * FROM users WHERE usersName = '${userName}'` const user = await db.query(query) if(user[0][0] === undefined){ return res.json({message: "No User"}) } await bcrypt.compare(password,user[0][0].password,async (err,result)=>{ let isUser = result if(isUser){ return res.json(user[0][0]) }else{
+ 4 other calls in file
58 59 60 61 62 63 64 65 66 67
//LOGIN FORM const { email, password } = req.body; //FIND USER const user = await User.findOne({ email }); //IF NOT A USER OR EMAIL / PSW NOT MACTH if (!user || !(await bcrypt.compare(password, user.password))) { res.status(400); throw new Error("Invalid credentials"); } //IF MACTH
20 21 22 23 24 25 26 27 28 29
const login = async (id, pswd) => { const data = await user.findOne({ where: { id: id } }); if (!data) { throw new ApiError(httpStatus.UNAUTHORIZED, "Not Found"); } if (await bcrypt.compare(pswd, data.pswd)) { const token = await generateToken(id); data.dataValues["token"] = token; data.dataValues.pswd = undefined; return data;
+ 14 other calls in file
137 138 139 140 141 142 143 144 145 146
const { newPassword, currPassword } = req.body; const Student = req.student; const { rollno, pswd, name, email } = Student; console.log(pswd, currPassword, name); if (await bcrypt.compare(currPassword, pswd)) { const newEncryptedPassword = await bcrypt.hash(newPassword, 8); await student.findOne({ where: { rollno: rollno } }).then((record) => { if (!record) {
+ 4 other calls in file
41 42 43 44 45 46 47 48 49 50
toObject: { virtuals: true } } ); //-------------------Instance Methods-------------------// userSchema.methods.correctPassword = async function(loginPass, userPass) { return await bcrypt.compare(loginPass, userPass); }; //-------------------Managing Password------------------// // Note: data will get check by validator before it gets to this document middleware userSchema.pre('save', async function(next) {
138 139 140 141 142 143 144 145 146 147 148 149
candidateSchema.methods.correctPassword = async function ( candidatePassword, userPassword ) { return await bcrypt.compare(candidatePassword, userPassword); }; candidateSchema.methods.changedPasswordAfter = function (JWTTimestamp) { if (this.passwordChangedAt) {
+ 4 other calls in file
63 64 65 66 67 68 69 70 71 72
.json({ errorMessage: "The user was not found in the DB" }); return; } //Password validation const isPasswordCorrect = await bcrypt.compare( password, foundUser.password ); if (!isPasswordCorrect) {
+ 4 other calls in file
87 88 89 90 91 92 93 94 95 96 97 98
// userSchema.methods.exceedLoginAttempts = function () { // return this.loginAttempts === 3; // }; userSchema.methods.correctPassword = async function (candidatePass, userPass) { return await bcrypt.compare(candidatePass, userPass); }; userSchema.methods.changedPasswordAfter = function (JWTTimeStamp) { if (this.changedPasswordAt) {
+ 3 other calls in file
75 76 77 78 79 80 81 82 83 84
if (userRecord == undefined) { res.status(404).send({ message: `User not found with ${userId}` }); } // if user found check password else { let checkPassword = await bcryptjs.compare(password,userRecord.dataValues.password); // if password not matched if (!checkPassword) { res.status(200).send({ message: "Incorrect password" }); } else {
132 133 134 135 136 137 138 139 140 141
console.error("Utilisateur non trouvé !"); reject(new Error("Identifiant incorrect !")) } else{ // verification du mdp hashé avec compare bcrypt.compare(mdp,result[0].mdp,(bErr, bResult) => { if (bErr) { console.error("Erreur lors du cryptage du mot de passe !"); reject(bErr) }
+ 4 other calls in file
GitHub: DmHack/servpol
131 132 133 134 135 136 137 138 139 140
const user = await User.findOne({ email }) if (user && (await bcrypt.compare(password, user.password))) { const userr = user jwt.verify(user.refresh, process.env.JWT_SECRET_REFRESH, (err, user) => { if (!err && auth != undefined) {
78 79 80 81 82 83 84 85 86 87
res.status(400).send("Login or Password is missing") } const user = await User.findOne({ login }) if(user && (await bcrypt.compare(password, user.password))){ let token_key = config.jwt_token const token = jwt.sign( { user_id: user._id, login }, token_key,
37 38 39 40 41 42 43 44 45 46
if(!user){ req.flash('alertMessage', 'User yang anda masukan tidak ada!!'); req.flash('alertStatus', 'danger'); return res.redirect('/admin/signin'); } const isPasswordMatch = await bcrypt.compare(password, user.password); if(!isPasswordMatch){ req.flash('alertMessage', 'Password yang anda masukan tidak Cocok!!'); req.flash('alertStatus', 'danger');
+ 3 other calls in file
bcryptjs.hash is the most popular function in bcryptjs (500 examples)