Search code examples
javascriptarraysnode.jsmongoosebcrypt

Check e-mail and password hash from an array


Implying I have an array containing E-mail and password combinations i.e.:

["[email protected]", "johnspasswordhashhere", "[email protected]", "janetpasswordhashhere", "[email protected]", "timspasswordhashhere" ]

How do I compare whether the provided e-mail and password hash match? I need to use bcrypt.compare(passtotestvar, passhash) to compare.


Solution

  • You could first sort the users and passwords, then loop over each user to check the credentials

    const arr = ["[email protected]", "johnspasswordhashhere", "[email protected]", "janetpasswordhashhere", "[email protected]", "timspasswordhashhere"]
    const sorted = arr.reduce((a, e, i) => (i % 2 || a.push([]), a[a.length - 1].push(e), a), [])
    console.log(sorted)

    Then you could use bcrypt's compare function, which does all the work for you:

    // from DB
    const users = {
      '[email protected]': 'HASHEDPW',
      '[email protected]': 'HASHEDPW',
      '[email protected]': 'HASHEDPW'
    }
    
    
    sorted.forEach(([email, password]) => {
      bcrypt.compare(password, users[email]).then((e, r) => {
        // r = true if hash = hashed pw
      })
    })