美好的一天,
我无法登录,因为bcrypt compareSync始终返回false:
var user = new User({
username: req.body.username,
password: bcrypt.hashSync(req.body.password, 10),
email: req.body.email
});
以下是我在创建帐户时定义用户的方式:
Response {_body: "{"success":false,"message":"Invalid login credentials!"}", status: 401, ok: false, statusText: "Unauthorized", headers: Headers, …}
尝试登录时收到的错误:
{{1}}
答案 0 :(得分:0)
我如何在模型中实现bcrypt集成:
import * as mongoose from "mongoose";
import * as bcrypt from "bcryptjs";
export interface IUser extends mongoose.Document {
name: string;
username: string;
password: string;
comparePassword(candidatePassword: string): Promise<boolean>;
}
export const schema = new mongoose.Schema({
name: String,
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
}
}, { timestamps: { createdAt: "created_at", updatedAt: "updated_at" } });
schema.pre("save", function (next) {
bcrypt.hash(this.password, 10, (err, hash) => {
this.password = hash;
next();
});
});
schema.pre("update", function (next) {
bcrypt.hash(this.password, 10, (err, hash) => {
this.password = hash;
next();
});
});
schema.methods.comparePassword = function (candidatePassword: string): Promise<boolean> {
let password = this.password;
return new Promise((resolve, reject) => {
bcrypt.compare(candidatePassword, password, (err, success) => {
if (err) return reject(err);
return resolve(success);
});
});
};
export const model = mongoose.model<IUser>("User", schema);
export const cleanCollection = () => model.remove({}).exec();
export default model;
完整示例:https://jonathas.com/token-based-authentication-in-nodejs-with-passport-jwt-and-bcrypt/
答案 1 :(得分:0)
老实说,我看不到您的代码有什么问题。...
我假设您还基于findOne函数使用猫鼬。我所做的几乎和您所做的完全一样,但是我在模型中处理哈希,而不是将哈希值传递给模型。您可以这样做:
用户模型
password:
set: function(v) {
return bcrypt.hashSync(v, 10);
}
我不能保证这对您有用,因为我不确定100%是否使用Mongoose。不过值得一试。
祝你好运!