Florian Margaine
Florian Margaine

Reputation: 60825

Redis and NodeJs - Can't auth a user

Ok, I give up.

I've tried many things to create a simple login form. The form itself renders fine, it's just the processing of the POST datas which is wrong :-)

I have a Redis database with some keys in it. Firstly, there is a users set with a list of users (currently, only user:admin). Secondly, there is a hkey user:admin with just a password. See the screen below.

Redis screenshot

With the following code, when I submit my form, it doesn't get in the callback function of the redis' calls :

var username = req.body.username;
var password = req.body.password;
// Now, check if the user he entered exists
client.sismember(['users', 'user:' + username], function(err, reply) {
  // IT NEVER GETS THERE
  if (reply) {
    // If he does, check if the password matches
    client.hget(['user:' + username, 'password'], function(err, reply) {
      if (reply === password) {
        // If the password matches, add the session and redirects to home
        req.session.username = username;
        res.redirect('/home');
      }
      else {
        options.error = "Password do not match.";
        res.render('guest', options);
      }
    });
  }
  else {
    options.error = "Username does not exist.";
    res.render('guest', options);
  }
});

I've used console.log to check some stuff, and username and password are well filled in.

There is no error concerning the redis server connection (which I have if I turn the server off), so the problem is not there.

I've tried using client.send_command() instead, but no change.

Any help would be greatly appreciated !

Upvotes: 3

Views: 1741

Answers (1)

Florian Margaine
Florian Margaine

Reputation: 60825

Ok, the answer is pretty stupid. I mean, I am stupid for not seeing this.

The asynchronous nature of this makes it pretty hard to get fully !

The problem was that later, in the code, at the end, I closed redis connection with client.end().

But this function was called before the callback could be fired, even though it was well after in the code.

Upvotes: 5

Related Questions