【问题标题】:Change bcrypt.compareSync to async if better如果更好,将 bcrypt.compareSync 更改为 async
【发布时间】:2019-01-22 06:06:59
【问题描述】:

这是我的身份验证过程:

会话 > Controller.js

const jwt = require("jsonwebtoken");
const repository = require("./repository");

const config = require("../../config");
const logger = require("../../utilities/logger");

exports.login = async (req, res) => {
    if (!req.body.password || !req.body.username) {
        res.preconditionFailed("Credentials required");
        return;
    }

    try {
        const user = await repository.findUser(req.body);
        if (!user || !user.comparePasswords(req.body.password)) {
            res.json({ success: false, message: "Authentication failed." });
            return;
        }

        const token = jwt.sign(user.toObject(), config.secret, { expiresIn: 1440 });
        logger.info("User loged in with success. Login token", token);
        res.json({
            success: true,
            token,
        });
    } catch (err) {
        res.send(err);
    }
};

用户 > Model.js

const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const SALT_WORK_FACTOR = 10;

const Schema = mongoose.Schema;

const userSchema = new Schema({
    id: { type: String, required: true },
    username: { type: String, required: true },
    password: { type: String, required: true },
}, {
    timestamps: true,
});

userSchema.pre('save', function(next) {
    var user = this;

    // only hash the password if it has been modified (or is new)
    if (!user.isModified('password')) return next();

    // generate a salt
    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
        if (err) return next(err);

        // hash the password using our new salt
        bcrypt.hash(user.password, salt, function(err, hash) {
            if (err) return next(err);

            // override the cleartext password with the hashed one
            user.password = hash;
            next();
        });
    });
});

userSchema.methods.comparePasswords = function(candidatePassword) {
    return bcrypt.compareSync(candidatePassword, this.password);
};

module.exports = mongoose.model("User", userSchema);

在用户模型中,我使用的是 bcrypt 方法compareSync。推荐使用异步方法compare(https://www.npmjs.com/package/bcrypt)。

有人能解释一下为什么吗?什么是好的实施?它运行良好,但我想确保我使用的是最佳做法。

【问题讨论】:

    标签: node.js express mongoose bcrypt


    【解决方案1】:

    compareSync 是 CPU 密集型任务。由于 Node.js 事件循环是单线程的,因此除非您完成比较,否则您会阻塞整个应用程序。

    使用 node.js 的主要规则是始终避免同步代码执行。 原因是 event-driven 框架的性质。

    好的详细解释可以找到here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      • 1970-01-01
      • 2014-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多