How to use bcryptjs

Comprehensive bcryptjs code examples:

How to use bcryptjs.compareSync:

30
31
32
33
34
35
36
37
38
39
    oldData: req.body,
  });
}
//Comparamos input contra hash
console.log(userToLogin);
let passwordCheck = bcryptjs.compareSync(
  req.body.password,
  userToLogin.password
);
if (passwordCheck) {

How to use bcryptjs.genSalt:

13
14
15
16
17
18
19
20
21
22
router.put("/:id", async (req, res) => {
  // removed || req.body.isAdmin from the below if statement because it seemed useless because anyone can say they are an admin
  if (req.body.userId === req.params.id) {
    if (req.body.password) {
      try {
        const salt = await bcrypt.genSalt(10);
        req.body.password = await bcrypt.hash(req.body.password, salt);
      } catch (err) {
        return res.status(500).json(err);
      }

How to use bcryptjs.genSaltSync:

527
528
529
530
531
532
533
534
535
536
    length: 6,
    numbers: true
});

//Hashing algorithm
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync(password, salt);

//base 64 encode
'use strict';

How to use bcryptjs.hashSync:

68
69
70
71
72
73
74
75
76
77
let errors = validationResult(req);
if (errors.isEmpty()) {
  const newUser = {
    id: users[users.length - 1].id + 1,
    ...req.body,
    password: bcryptjs.hashSync(req.body.password, 10),
    favouriteProducts: [],
    image: req.file ? req.file.filename : "imagenPerfil.png",
    rol: "user"
  };

How to use bcryptjs.compare:

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) {

How to use bcryptjs.hash:

1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
  updatedAt: { type: Date, default: Date.now },
});


Schema.pre("save", function (next) {
  if (this.isModified("password") || this.isNew) {
    bcrypt.hash(this.password, 10, (e, hash) => {
      this.password = hash;
      return next();
    });
  } else {