Getting “Error: String“ Invalid BCrypt Hashing. ”Error“ :) ”was selected during Mocha ExpressJS testing

I have a MEAN stack application using Passport for authentication.

I am trying to write a unit test that logs into the system and checks if you are redirected to the root ( / ). However, whenever I start 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 is 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: " john@email.com ", 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 a BCrype password? If so, how to do it?

Also, why are some of the online examples that I see for login not doing this? For example, NodeJS / Passport - checking user login with wet and superagent and How to authenticate Supertest requests with Passport?

+6
source share
2 answers

I thought I would answer this, since I had the same problem, and I could not find anywhere with a direct answer.

When you define a new user, you will need to use bcrypt to encrypt this password, and when you log in, you will need to use bcrypt to compare the password with the one that was saved by the user you selected. Otherwise, you will continue the "Invalid BCrypt Hashing" problem.

Here is a simple encryption and comparison function that I use in my application

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

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

+1
source

This is because there is only a string in your password field in the database, not a hashed string.

It should be like $2a$08$LMXAGOARNn4XmnC/rQuhfujrWVwgK/RuHuGpLtXvcv/yruY1v3yXa , but this is probably only the original password.

+1
source

Source: https://habr.com/ru/post/989245/


All Articles