Another flexible authentication solution for mongoosejs.
Node >8.0.0
.
Mongoose >5.0.0
.
Standard installation of the plugin:
const mongoose = require('mongoose')
const devise = require('mongoose-devise')
// or
// const { devise } = require('mongoose-devise')
const UserSchema = new mongoose.Schema({})
UserSchema.plugin(devise)
mongoose.model('User', UserSchema)
IMPORTANT
- only the most common methods are documented. For more information check the tests
- in all cases, the
opts
parameter will be used to pass some configuration to thesendNotification
method.
module that allows you to register an access account or, disable a registered account.
a static method used to register credentials. It will return the registered user or the corresponding errors of the registration attempt.
const faker = require('faker')
User.register({
email: faker.internet.email(),
password: faker.internet.password()
})
.then(user)
.catch(error)
an instance method that lets you unregister (destroy a user). It receives two callbacks the parameter, one that executes before and the other after the save the object.
user.unregister(
function () {
// something before..
},
function () {
// something later
}
)
// #=> true
NOTE The implementation currently assigns the value of unregisteredAt
to the current date.
TIP identifiable by the flag account_confirmation
.
module that verifies whether an account has already been confirmed or conveys instructions for confirmation.
this static method receives a valid validationToken
string to be able to confirm the unconfirmed record. Returns a user or the errors.
User.confirm('confirmation-token-valid')
.then(user)
.catch(error)
instance method that confirms the account registration. Returns a boolean or errors in the process.
user.confirm()
.then(isConfirmed)
.catch(error)
verifies whether a user is confirmed or not.
user.isConfirmed()
// #=> true
authenticatable module, responsible for hashing the password and validating the authenticity of a user while signing in.
authenticates the user's instance from a password passed by parameter. If no errors are processed, a boolean will be returned.
user.authenticate('secret')
.then(isAuthenticated)
.catch(error)
a static method which takes in credentials in the format:
const faker = require('faker')
const credentials = {
email: faker.internet.email(),
password: faker.internet.password()
}
where a valid email
and password
corresponding to a database user must be reported. At the end,
the user of the provided credentials will be returned, otherwise the corresponding errors.
User.authenticate(credentials)
.then(user)
.catch(error)
an instance method which takes in a plain string password and compare with the instance hashed password to see if they match.
user.validPassword('secret')
// #=> true
TIP identifiable by the flag password_recovery
.
module that establishes user password reset and sends resetting instructions.
a static method used to retrieve an account bound to a recoverToken
string. It receives two parameters, the first is the token and the second the new recovery password. Returns the linked user or any errors that occur.
User.recover('recovery-token-valid', 'new-password')
.then(user)
.catch(error)
a model static method which is used to request account password recovery. Returns the user or any errors that occur.
User.requestRecover({ email })
.then(user)
.catch(error)
TIP identifiable by the flag account_recovery
.
provide a means of locking an account after a specified number of failed sign-in attempts (defaults to 3 attempts)
.
NOTE user can unlock account via unlock instructions issued.
an instance method that is used to lock an account. When invoked, it will check if the number of
failedAttempts
is greater than the configured maximum allowed login attempts
,
if so the account will get locked by setting lockedAt
to the current timestamp.
user.lock()
.then(isLocked)
.catch(error)
verifies whether a user is locked or not.
user.isLocked()
// #=> true
a static method that unlocks a locked account with the provided unlockToken
string.
- If the token expires, the new
unlockToken
will be generated. - If the token is valid, the locked account will be unlocked and the
unlockedAt
attribute will be set to the current date and time.failedAttempts
will be set to 0.
User.unlock('unlock-token-valid')
.then(user)
.catch(error)
provide a means of tracking user signin activities.
this is the instance method that will update the tracking details. Optionally receives a valid ip string.
user.track()
the default implementation of mongoose-devise
to send notifications is simple. This is because there are different use case(s) when it comes on sending notifications.
due to that reason, mongoose-devise
requires that your model implements sendNotification method
which accept record
, action
, done
as its argurments.
refer to the current user model instance.
refer to the type of notifcation to be sent. There are just three types which
are account_confirmation
, account_recovery
and password_recovery
which are sent
when new account is registered, when an account is locked and need to be unlocked and when account is requesting
to recover the password respectively.
is the callback that you must call after finishing sending the notification. By default this callback will update the notification send details based on the usage.
- all the methods that accept the
opts
parameter, pass this parameter to the callbackdone
const UserSchema = new Schema({})
// override send method i.e your notification sending: email, sms, etc
schema.methods.sendNotification = function (record, action, done) {
done(opts => {
// const host = isObject(opts) && (isObject(opts.req) && opts.req.isSecure())
// ? 'https'
// : 'http' + '://' + uri
switch (action) {
// if we send `confirmation email`
case 'account_confirmation':
console.log('Action type: %s.\nRecord: %s \n', action, JSON.stringify(record))
break
// if we send `account recovery`
case 'password_recovery':
console.log('Action type: %s.\nRecord: %s \n', action, JSON.stringify(record))
break
// if we send `account locked` information
case 'account_recovery':
console.log('Action type: %s.\nRecord: %s \n', action, JSON.stringify(record))
break
default:
console.log('mailer', 'Template not found')
}
})
}
It is recommended to use job queue like kue or bull when implementing your send to reduce your API response time.
mongoose-devise
uses messages to customize your application, you can configure the message definition variables manually
It is recommended to use an internalizer such as i18nex or node-i18n when implementing the support layer to the language.
// custom to pt-BR, default is en-US.
userSchema.plugin(devise, {
authenticationFieldMessage: 'Endereço de email inválido',
// authenticable
authenticatorError: 'O {{field}} não foi informada',
passwordError: 'Senha não informada',
authenticatorNotExistError: 'Esse email não existe',
credentialsNotExistError: 'Credênciais incorretas',
// confirmable
invalidConfirmationTokenError: 'Token de confirmação inválido',
confirmationTokenExpiredError: 'Token de confirmação expirou',
accountNotConfirmedError: 'Conta não confirmada',
// registerable
definitionsNotFoundError: 'Dados básicos não encontrados',
// lockable
accountLockedError: 'Conta bloqueada. Verifique as instruções de desbloqueio enviadas para o seu email',
invalidUnlockTokenError: 'Token de desbloqueio inválido',
unlockTokenExpiredError: 'Token de desbloqueio expirado',
// recoverable
accountWithoutAssociationError: 'Não existe conta associada a esse email',
invalidRecoveryTokenError: 'Token de recuperação recusado',
recoveryTokenExpiredError: 'Token de recuperação expirado'
})
See complete MVC solution based on Restify engines;
Inspired by irina.
- Install all development dependencies
npm install
- Then run test
npm test
Copyright (c) 2018-present