获得“错误:string”不是有效的BCrypt哈希“,抛出一个错误:)”在摩卡ExpressJStesting

我有一个使用Passport进行身份validation的MEAN堆栈应用程序。

我试图编写一个unit testing,login并检查您是否被redirect到根( / )。 但是,每当我运行摩卡我得到以下错误信息:

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

这是我的unit testingLoginSpec.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(); }) }) }) 

我需要BCrype我的密码吗? 如果是这样,我该怎么做?

另外,我所看到的一些在线例子是如何login的呢? 如NodeJS /护照 – testing用户login与摩卡和superagent和如何使用PassportvalidationSupertest请求?

我想我会回答这个问题,因为我有同样的问题,找不到任何直接的答案。

在你定义一个新用户的地方,你将需要使用bcrypt来encryption这个密码,当你login时你将需要使用bcrypt来比较你保存的用户的密码。 否则,你将继续得到“不是有效的BCrypt哈希”的问题。

这是我在我的应用程序中使用的一个简单的encryption和比较function

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

更多信息可以在这里find: https : //www.npmjs.com/package/bcrypt

发生这种情况是因为数据库上的密码字段只有一个string,而不是散列string。

它必须像$2a$08$LMXAGOARNn4XmnC/rQuhfujrWVwgK/RuHuGpLtXvcv/yruY1v3yXa但可能只是原来的密码。