I have a MEAN stack app that is using Passport for authentication.

I'm trying to write a unit test that logs in and checks whether you are redirected to the root (/). However, whenever I run Mocha I get the following error message:

1) POST /home Login test should redirect to / after login:
   Error: the string "Not a valid BCrypt hash." was thrown, throw an Error :)

Here's my unit test LoginSpec.js:

var should = require("should");
var app = require("../app");
var mongoose = require("mongoose");
var User = mongoose.model("User");
var request = require("supertest");
var agent = request.agent(app);
...
describe('POST /home', function() {
    before(function(done) {
        user = new User({
            email: "[email protected]",
            firstName: "John",
            lastName: "Doe",
            password: "strongPassword",
            username: "johndoe"
        });

        user.save(done);
    })

    describe('Login test', function() {
        it ('should redirect to / after login', function(done) {
            agent.post('/login')
                .send({
                    username: 'johndoe',
                    password: 'strongPassword'
                })
                .end(function(err, res) {
                    done();
                })
        })

        after(function(done) {
            User.remove().exec();
            return done();
        })
    })
})

Do I need to BCrype my password? If so, how do I do this?

Also, how come some of the online examples I'm seeing for logging in don't do it? Such as NodeJS/Passport - Testing user login with mocha and superagent and How to authenticate Supertest requests with Passport?

2

There are 2 answers

0
Tiago GouvĂȘa On

It happen because your password field on database have just a string, not a hashed string.

It must be like $2a$08$LMXAGOARNn4XmnC/rQuhfujrWVwgK/RuHuGpLtXvcv/yruY1v3yXa but probably are just the original password.

0
Jordan On

I thought I'd answer this since I had the same issue and could not find anywhere with a direct answer.

Where you are defining a new user you will need to use bcrypt to encrypt that password, also when you are login in you will then need to use bcrypt to compare the password to the one saved in the user you have fetched. Otherwise you will continue to get the issue of "Not a valid BCrypt hash.".

Here is a simple encrypt and compare function that I use in my app

UserSchema.methods.encryptPassword = function(password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(10));
}

UserSchema.methods.validPassword = function(password) {
    return bcrypt.compareSync(password, this.password);
}

More information can be found here: https://www.npmjs.com/package/bcrypt