Skip to content

Instantly share code, notes, and snippets.

@nukosuke
Last active May 26, 2016 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nukosuke/9d162f796724e46546d0d4558cd08cc2 to your computer and use it in GitHub Desktop.
Save nukosuke/9d162f796724e46546d0d4558cd08cc2 to your computer and use it in GitHub Desktop.
Sequelize + bcrypt でパスワード認証を実装する ref: http://qiita.com/nukosuke/items/ab492a425b0611abf788
$ npm i sequelize --save
$ npm i bcrypt --save
$ npm i sequelize-cli -D
$ ./node_modules/.bin/sequelize model:create \
--name User \
--attributes 'name:string, email:string, password_hash:string'
password_hash: {
type: DataTypes.STRING,
},
password: {
type: DataTypes.VIRTUAL,
validate: {
min: 8,
max: 32,
},
},
var hashPasswordHook = function(user, options, callback) {
bcrypt.hash(user.get('password'), 10, function(err, hash) {
if (err) {
return callback(err);
}
user.set('password_hash', hash);
return callback(null, options);
});
};
var User = sequelize.define('User',
{
//attributes...
},
{
hooks: {
beforeCreate: hashPasswordHook,
beforeUpdate: hashPasswordHook,
},
instanceMethods: {
authenticate: function(password, callback) {
bcrypt.compare(password, this.password_hash, function(err, isValid) {
if (err) {
return callback(err);
} else {
return callback(null, isValid);
}
});
},
},
})
auth: function(req, res) {
User.findOne({ where: { email: req.params.email } }).then(function(user) {
if (!user) {
// response
// 404 NOT FOUND
// { user: null }
res.status(404).json({ user });
}
user.authenticate(req.params.password, function(err, isValid) {
if (err) {
res.status(500).json({ err });
}
res.json({ user });
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment