0

I am new to nodejs but I am trying to use it as server for an online game I am designing. I come across the tutorial and I am just playing around with the code to see how I can modify it to suit me need. https://github.com/scotch-io/easy-node-authentication/tree/linking

1 thing I couldn't solve however is while using bcrypt, my code below is trying to isolate the issue:

//check-hash

var bcrypt   = require('bcrypt-nodejs');
var salt = bcrypt.genSaltSync(8);

var newAccount = {
    username: "admin",
    password: "1235",
    email: "test@domain.com",
    AccCreateOn: Date.now(),
    LastLogin: Date.now()
}
newAccount.generateHash  = function(password) {
    return bcrypt.hashSync(password,  salt);
};

// checking if password is  valid
newAccount.validPassword  = function(password) {
    return bcrypt.compareSync(password,  this.password);
};
console.log (newAccount.password);
newAccount.password = newAccount.generateHash(this.password);
console.log(newAccount.validPassword("1235")); //false
console.log(newAccount.validPassword("1236"));//false

I already figure out the line at fault is

return bcrypt.compareSync(password,  this.password);

which if I change this.password to newAccount.password it will work just fine.

what is wrong as I thought this.password in this context is newAccount.password, or is it not?

Nick Li
  • 312
  • 2
  • 12
  • Bcrypt (and all password functions) verify a plaintext against a hash. You're trying to compare two plaintexts. (Also, don't use `sync`). – OrangeDog Nov 14 '16 at 14:01
  • Sorry somehow a line was missing in the script above, I am actually trying to compare a plaintexts with the hashed password – Nick Li Nov 15 '16 at 07:36
  • Are you sure this line`newAccount.password = newAccount.generateHash(this.password);` is correct? . You are passing the current module password variable, which doesn't exits. – Hosar Nov 15 '16 at 07:55
  • Hosar - sorry but what do you mean by it doesn't exist? newAccount.password isn't it password field within the newAccount object? (call me an idiot if you want since I started learning programming 2 weeks ago and I may have something wrong fundamentally, but please point it out) – Nick Li Nov 15 '16 at 11:39
  • Possible duplicate of [How does the "this" keyword work](http://stackoverflow.com/q/3127429/476716). – OrangeDog Nov 15 '16 at 12:32
  • > You are passing the current module password variable – OrangeDog Nov 15 '16 at 12:35
  • @OrangeDog Argh...I think I get it now, just to clarify though `newAccount.password = newAccount.generateHash(this.password)`this.password in here since it is in argument where function was not called yet, and therefore is referring to the module, while; `newAccount.validPassword = function(password) { return bcrypt.compareSync(password, this.password)};` in here if I call newAccount.validPassword, the ThisBinding will be the object 'newAccount', is this right? – Nick Li Nov 16 '16 at 07:46

0 Answers0