User authentication with password created by Meteor

1.2k Views Asked by At

I am trying to authenticate user from server, using password created in Meteor by accounts-password and stored in DB. However passwords never match. What I am doing wrong?

    var bcrypt = require('bcryptjs');
    var crypto = require('crypto');
    var raw_pass = 'my_pass';
    var pass = crypto.createHash('sha256').update(raw_pass).digest('hex');              
    var encryptedPassword = bcrypt.hashSync(pass, bcrypt.genSaltSync(10));
    bcrypt.compare(doc.services.password.bcrypt, encryptedPassword, function(err, result) {
                if(result) {
                   console.log('OK');
                }
                else {
                   console.log(403);
                }
            });
4

There are 4 best solutions below

1
On BEST ANSWER

Arguments for bcrypt.compare are 'plain string' and 'encrypted string'. So the right solution is:

var raw_pass = 'my_pass';
var pass-256 = crypto.createHash('sha256').update(raw_pass).digest('hex');              
bcrypt.compare(meteor.password, pass-256, function(err, result) {
            if(result) {
               console.log('OK');
            }
            else {
               console.log(403);
            }
        });
4
On

It would help us if you print out the output of bcrypt.compare. It might be returning 0, which would mean success, but in your if statement, 0 would be interpreted as false.

3
On

Account password doesn't use crypto for the password. It's only use bcrypt and salt to generate the encrypted password.

You can check compare password here

0
On

The right way to check a plain password against a meteor generated one is by using sha256 and bcrypt as follows

var bcrypt = require('bcrypt')
var sha256 = require('sha256')
const samePassword = bcrypt.compareSync(
                        sha256(plainTextPassword),
                        user.services.password.bcrypt
                     )