Implement Passport.js authentica

2018-04-24  本文已影响42人  losingle

第一步:安装依赖

在开始之前,我们要确保以下依赖都安装到了Sails.js

npm i --save bcrypt-nodejs
npm i --save passport
npm i --save passport-local
npm i --save jsonwebtoken

第二步:生成用户模型

通过以下命令可以自动生成用户模型 User.js 到api/models目录下

sails generate model user

在User.js文件内,我们这样配置

const bcrypt = require('bcrypt-nodejs');
module.exports = {
attributes: {
    email: {
      type: 'email',
      required: true,
      unique: true
    },
    username: {
      type: 'string',
      required: true,
      unique: true
    },
    password: {
      type: 'string',
      required: true
    }
  },
  customToJSON: function() {
     return _.omit(this, ['password'])
  },
  beforeCreate: function(user, cb){
    bcrypt.genSalt(10, function(err, salt){
      bcrypt.hash(user.password, salt, null, function(err, hash){
        if(err) return cb(err);
        user.password = hash;
        return cb();
      });
    });
  }
};

查看原文:https://medium.com/@greg.hesp/implement-passport-js-authentication-with-sails-js-1-0-50888265fb83

上一篇下一篇

猜你喜欢

热点阅读