This package includes plugins useful for authentication for websites:
- Authenticatable - Generates hashed passwords for a user model. Uses
bcrypt
under the hood. - Recoverable - Generates password reset tokens.
npm install objection-auth
// Import the plugin.
const { Authenticatable } = require('objection-auth');
const { Model } = require('objection');
// Mixin the plugin.
const AuthenticatableModel = Authenticatable({
passwordField: 'password',
saltRounds: 12,
})(Model);
// Create your model.
class User extends AuthenticatableModel {
// ...code
}
In your login controller logic:
const user = await User.query().where('id', 1);
if (!user.verifyPassword) {
// throw an error
}
The field to that the hashed password will be stored on. (required, defaults to 'password')
The number of salt rounds as passed to bcrypt
.
// Import the plugin.
const { Recoverable } = require('objection-auth');
const { Model } = require('objection');
// Mixin the plugin.
const RecoverableModel = Recoverable({
tokenField: 'resetPasswordToken',
tokenExpField: 'resetPasswordExp',
expiresIn: 60
})(Model);
// Create your model.
class User extends RecoverableModel {
// ...code
}
In your reset password controller logic:
const user = await User.query().where('id', 1);
await user.generateResetToken();
console.log(user.resetPasswordToken);
//
The field that the reset token is stored on.
The field that the expiration date is stored on.
The expiration time of the token, in minutes.
These plugins can be used together by composing the plugins together:
const { Authenticatable, Recoverable } = require('objection-auth');
const { compose, Model } = require('objection');
const mixins = compose(
Authenticatable({ saltRounds: 10, passwordField: 'pass' }),
Recoverable({
tokenField: 'resetPasswordToken',
tokenExpField: 'resetPasswordExp',
expiresIn: 60
})
);
class User extends mixins(Model) {
// ...
}