首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Sails.js -加密密码

Sails.js -加密密码
EN

Stack Overflow用户
提问于 2017-05-12 16:52:50
回答 3查看 3.2K关注 0票数 1

对于一个项目,我需要有用户,我想在数据库中存储一个加密的密码。

所以我需要你的帮助,因为我在添加用户时需要加密密码,但当我启动sails lift时,我在终端中遇到错误

代码语言:javascript
复制
In model `user`:
The `toJSON` instance method is no longer supported.
Instead, please use the `customToJSON` model setting.

配置:

我使用的是Sails 1.0 BetaBcrypt 1.0.2

模型User.js

代码语言:javascript
复制
/**
* User.js
*
* @description :: A model definition.  Represents a database 
table/collection/etc.
* @docs        :: https://sailsjs.com/docs/concepts/models-and-
orm/models
*/

var bcrypt = require('bcrypt');


module.exports = {


attributes: {
    firstname: {
        type: 'string'
    },
    lastname: {
        type: 'string'
    },
    password: {
        type: 'string'
    },
    email: {
        type: 'string',
        unique: true
    },
    code: {
        type: 'string',
        unique: true
    },
    referring: {
        type: 'string'
    },
    comment: {
        type: 'text'
    },
    // Add reference to Profil
    profil: {
        model: 'profil'
    },
    toJSON: function() {
        var obj = this.toObject();
        delete obj.password;
        return obj;
    }
},
beforeCreate: function(user, cb) {
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(user.password, salt, function(err, hash) {
            if (err) {
                console.log(err);
                cb(err);
            } else {
                user.password = hash;
                cb();
            }
        });
    });
}
};

我想我正在使用一种旧的方法来加密密码,但是我不知道或者找不到另一种方法来做这件事。

提前感谢

EN

回答 3

Stack Overflow用户

发布于 2018-05-05 23:10:25

我认为您应该执行以下操作,并记住将此customToJSON函数放在attributes:{...},之后

代码语言:javascript
复制
attributes:{...},

customToJSON: function() {
  // Return a shallow copy of this record with the password and ssn removed.
  return _.omit(this, ['password'])
}

Chek out from this link

票数 2
EN

Stack Overflow用户

发布于 2017-10-18 01:52:10

我知道这个问题很老了,但希望这能给我们带来一些启发。

从Sails 1.0开始,不再支持实例方法。文档建议您应该改用customToJSON,但是它并没有说明您应该在属性之外使用它。

customToJSON允许您在发送数据之前使用自定义函数对数据进行字符串处理。在您的示例中,您将希望省略密码。使用customToJSON,您可以使用this关键字来访问返回的对象。建议不要修改这个对象,而是创建一个副本。

因此,对于您的示例,您将使用:

代码语言:javascript
复制
module.exports = {

  attributes: {...},

  customToJSON: function() {
    return _.omit(this, ['password'])
  },

  beforeCreate: function(user, cb) {...}

};
票数 1
EN

Stack Overflow用户

发布于 2017-05-13 23:35:39

您看到的错误与加密无关。查看您的模型并注意toJSON函数。如错误消息所示,这是一个实例方法,不再受支持。因此,请按照建议进行操作:使用customToJSON模型设置。我相信你会在文档中找到它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43933409

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档