0

I want to create login system using node.js and Redis (Redis package) but every time I compare input data with database data I get a confusing result. This is the first method:

const Redis = require("redis");
const client = Redis.createClient();
exports.userLogin = (username, password, errMsg, successMsg, res) => {
  client.keys("user*", (err, replies) => {
    let isFound = false;
    for (let i = 0; i < replies.length; i++) {
      client.hgetall(replies[i], (err, value) => {
        if (value.user === username && value.password === password) {
          isFound = true;
        }
      }); 
    }
    console.log(isFound);
    if (isFound) {
      successMsg(username, res);
    } else {
      errMsg(res);
    }
  })
)}

I keep getting false even if login and password are ok plus It doesn't execute errMsg function Example 1 Second example:

exports.userLogin = (username, password, errMsg, successMsg, res) => {
    client.keys("user*", (err, replies) => {
        for (let i = 0; i < replies.length; i++) {
          client.hgetall(replies[i], (err, value) => {
            if (value.user === username && value.password === password) {
              successMsg(username, res);
            } else {
              console.log("length: ", replies.length - 1);
              console.log("i: ", i);
              if(replies[i] === replies.length - 1) {
                errMsg(res);
              } else {
                console.log("else statement: ", replies[i] === replies.length - 1);
                return true;
              }
            }
          });
        }
      })
)}

Example 2

It works if password and login are ok but It doesn't if they are not correct because the page is loading something and doesn't execute the errMsg function. Do you have any ideas?

miqezjo
  • 31
  • 8

1 Answers1

1

If you can, change using redis to something better suited for storing users.

Otherwise, change how the data is stored in redis. You don't wanna read all users and loop them like that. Let the db query take care of as much as possible. Perhaps one way is to let the username be a part of the key, so that you can look up the correct user directly, and just check the password from there.

Don't forget the security parts of storing passwords and handling login. Look into hashing the password and adding a password salt if it needs to be secure.

William
  • 741
  • 4
  • 9
  • I need to use Redis. I'm only testing right now so passwords will be hashed. I will try with user as a key – miqezjo Oct 18 '17 at 07:10