bookshelf-bcrypt
Automatic password hashing for your bookshelf models
Installation
After installing bookshelf-bcrypt
with npm i --save bookshelf-bcrypt
,
all you need to do is add it as a bookshelf plugin and enable it on your models.
let knex = require('knex')(require('./knexfile.js').development)
let bookshelf = require('bookshelf')(knex)
bookshelf.plugin(require('bookshelf-bcrypt'))
let User = bookshelf.Model.extend({ tableName: 'users', bcrypt: { field: 'password' } })
let User = bookshelf.Model.extend({ tableName: 'users', bcrypt: { field: 'password', allowEmptyPassword: true } })
Usage
Nothing fancy here, just keep using bookshelf as usual.
let user = yield User.forge({ password: 'h4x0r' }).save()
console.log(user.get('password'))
This plugin will also hash the password again if it detects that the field
changed, so you're good to do this:
let user = yield User.forge({ id: 1000 }).fetch()
user.set('password', 'another_pwd')
yield user.save()
yield user.save({ bcrypt: false })
Settings
bookshelf-bcrypt
uses 12 salt rounds by default. By default we don't try and detect
a rehash because a user may use a password that looks like a bcrypt hash. If you
add a detectBcrypt function value and it returns a truthy value, an error will be thrown.
You can also override the onRehash function in settings.
bookshelf.plugin(require('bookshelf-bcrypt'), {
rounds: 10
detectBcrypt: password => password.length > 50,
onRehash: function () {
console.warn(`Rehash detected for ${this.tableName}`)
this.set('need_password_change', true)
}
})
Testing
git clone git@github.com:estate/bookshelf-bcrypt.git
cd bookshelf-bcrypt && npm install && npm test