0
"previousPasswords": [
        "$2a$10$.6cY1diu9kkAhQCBxlVb7unBCxHGCblucOHp4g/z6rE9a3/YQEHqq",
        "$2a$10$T.G1BZ3SCCY4p1H6sXlpz.daJuX6s/YbFReGmQlWIOMCZcwUPIhE6",
        "$2a$10$ZeW2A6YQw4dI07PDwwql/.vA4tJdvkq9EAcduIEnpFuAzjvXURi5a",
        "$2a$10$iuHu21hA9J55ai1gWrJ96OKfl7X0sD/FzT7nd0gKzw38NTYOXdiWG",
        "$2a$10$ID/fYCOJ0KOb010f7OZf1ON7RNQJwcMT1px5dBpQx2.juoBugiEQe",
        "$2a$10$lIvpPNK6lMs4CpAzBl1wZOjq9HF12lIffs7TybaWqo8v7g76KJ3s2",
        "$2a$10$Brz/WRZGKBEzLJEpzrFEwuRccVAI1K7KEXfv5GVxFV4H34r9WhMke",
        "$2a$10$QD/6DDQD2n1KWoYO6PBPtu4rp1HfX2sSy2uBbWj5d0tw.EmaEl/Yy",
        "$2a$10$sP03DLwC.yPt.c3i.CdD0OmYBS6m6XQpPycuFE49GLPWvHEvjiBXW"
    ],

**Now here I want to compare incoming password with array of hash passwords **

const ifPrevPass = await Users.findOne({
      _id: req.user._id,
      previousPasswords: body.password,
    });
  • Inside a loop?? Depends on what you want... – Marc Oct 01 '21 at 16:40
  • Looks like bcrypt. Should be easy to compare. – Wiktor Zychla Oct 01 '21 at 16:42
  • what's wrong with [`Array.prototype.includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) – Wyck Oct 01 '21 at 16:42
  • if the user is using his previous password as a new password don't save that password any solution for this particular task.? – Munsif Ali Misri Oct 01 '21 at 16:43
  • @Wyck previousPasswords contains hashed passwords and body.password is a string now the question is how can i use bcrypt.compare (val1,val2) inside findOne query – Munsif Ali Misri Oct 01 '21 at 16:51
  • I assume you would hash your current password using the [old salt](https://stackoverflow.com/a/6833165/1563833) and then compare its hash to the older hash. See this [starting point](https://security.stackexchange.com/questions/85074/is-it-safe-to-store-a-password-hash-history-for-preventing-user-to-keep-same-pas) – Wyck Oct 01 '21 at 17:06

1 Answers1

1

I came up with this solution now its working

async function checkIfPassExists(user, body) {
for (var i = 0; i < user.previousPasswords.length; i++) {
    const resultOfCompa = await bcrypt.compare(
        body.password,
        user.previousPasswords[i]
    );
    if (resultOfCompa) {
        passMatched = true;
    }
}
return passMatched;

}

const ifPrevPass = await checkIfPassExists(user, body);
    if (ifPrevPass) {
      return res.status(400).json({
        status: "error",
        message: "You have already used this password",
      });
    }