const jwt      = require('jsonwebtoken')
const config   = require('config')
const bcrypt   = require('bcrypt')
const _        = require('lodash')
const User     = require('./../models/user')
const Messages = require('./../../config/messages')

const Authenticate = (user) => {
  return new Promise((resolve, reject) => {
    User.findOne({ 'where': { 'email': user.email } })
      .then((record) => {
        if (!record) {
          return reject({ 'errors': {
            'user': { 'not_found': Messages.errors.user.not_found }
          }})
        }

        record = record.get({ plain: true })

        bcrypt.compare(user.password, record.password)
          .then((result) => {
            if (result) {
              return jwt.sign(_.omit(record, ['password']), config.get('secret'), { expiresIn: '1d' }, (error, token) => {
                if (error) {
                  console.error('[JWT ERROR] ' + error)
                  return reject({ 'errors': {
                    'token': { 'unavailable': Messages.errors.token.unavailable }
                  }})
                }

                return resolve(Object.assign({}, _.omit(record, ['password']), { token }));
              })
            }

            return reject({ 'errors': {
              'user': { 'password': Messages.errors.user.password }
            }})
          })
      })
  })
}

module.exports = Authenticate

@@ -458,42 +458,77 @@
 s': 
-%7B%0A            'user': %7B 'not_found
+%5B%0A            %7B%0A              'path': 'email',%0A              'message
 ': M
@@ -556,16 +556,28 @@
 ot_found
+%0A           
  %7D%0A     
@@ -573,33 +573,33 @@
     %7D%0A          
-%7D
+%5D
 %7D)%0A        %7D%0A%0A  
@@ -996,32 +996,54 @@
 ject(%7B 'errors':
+ %5B%0A                   
  %7B%0A             
@@ -1053,18 +1053,17 @@
     
-'token': %7B
+  'path':
  'un
@@ -1072,16 +1072,49 @@
 ailable'
+,%0A                      'message'
 : Messag
@@ -1140,16 +1140,36 @@
 vailable
+%0A                   
  %7D%0A     
@@ -1173,33 +1173,33 @@
                 
-%7D
+%5D
 %7D)%0A             
@@ -1365,16 +1365,32 @@
 errors':
+ %5B%0A             
  %7B%0A     
@@ -1402,17 +1402,15 @@
     
-'user': %7B
+  path:
  'pa
@@ -1416,16 +1416,41 @@
 assword'
+,%0A                message
 : Messag
@@ -1472,16 +1472,30 @@
 password
+%0A             
  %7D%0A     
@@ -1505,11 +1505,12 @@
     
-%7D
+%5D
 %7D)
+;
 %0A   

Standardize authentication errors with sequelize format