【问题标题】:Hashing password with nestjs and mongoose crashes on production使用 nestjs 和 mongoose 哈希密码在生产中崩溃
【发布时间】:2020-11-09 04:04:20
【问题描述】:

在我的 nestjs 应用程序中,我使用 mongoose 的预保存方法来散列密码。 在本地它工作正常。但是在生产/d​​ocker上,它会导致整个嵌套应用程序崩溃。代码如下:

export const UserSchema = new mongoose.Schema({
  email: { type: String, unique: true, lowercase: true, trim: true },
  password: {
    type: String,
    minlength: [8, 'Password must be 8 characters or more.'],
    maxlength: 100,
  },
  username: String,
...
  phone: { type: String, default: '' },
});

UserSchema.pre('save', async function (next: mongoose.HookNextFunction) {
  try {
    if (!this.isModified('password')) {
      return next();
    }
    const saltRounds = 14;
    const hashed = await bcrypt.hash(this['password'], saltRounds);
    this['password'] = hashed;
    return next();
  } catch (err) {
    return next(err);
  }
});

再次,它在本地工作,但在 docker 中,任何用户保存都会导致崩溃(“以代码 0 退出”)。 你发现这段代码有什么问题吗,或者你有更好的方法吗?

【问题讨论】:

  • “崩溃”是什么意思?你有任何错误的日志吗?您可以分享更多信息吗?蒙哥版?至于更好的方法,我更喜欢让我的模式、实体和其他 DAO 对象尽可能纯净,并在服务中保留任何“预”逻辑。

标签: docker mongoose nestjs


【解决方案1】:

天哪!我一直在这上面浪费时间。这是解决方案。 bcrypt 在 nodejs 应用程序上往往会失败(等等,什么?bcrypt?每周下载 487K 的 npm 包?是的。) 一个替代方案是 bcryptjs,一个稍微慢一点的 javascript 版本,但是,嘿,它可以工作!

在离您最近的 npm 商店购买:https://www.npmjs.com/package/bcryptjs

这是我找到它的地方:https://github.com/kelektiv/node.bcrypt.js/issues/432

【讨论】:

    猜你喜欢
    • 2020-04-19
    • 2020-09-15
    • 2019-06-23
    • 2015-05-12
    • 2014-05-26
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    相关资源
    最近更新 更多