const bcrypt = require('bcryptjs')
const knex = require('../database')

module.exports.findOne = (username) => new Promise((resolve, reject) => {
  knex('users').select().where({username})

    // success
    .then(user => {
      if (user) { resolve(user[0]) }
      else { resolve(null) }
    })

    // error
    .catch(err => reject(err))
})

module.exports.comparePasswords = (reqPass, dbPass) => bcrypt.compareSync(reqPass, dbPass)

module.exports.createUser = (user) => new Promise((resolve, reject) => {
  user.password = hashedPassword(user.password)
  knex('users').insert(user).returning('*')
    .then(resolve)
    .catch(reject)
})

function hashedPassword (password) {
  return bcrypt.hashSync(password, 10)
}

module.exports.getAllUsers = () => new Promise((resolve, reject) => {
  knex('users').select()
    .then(resolve)
    .catch(reject)
})
@@ -63,16 +63,52 @@
 tabase')
+%0Aconst jwt = require('jsonwebtoken')
 %0A%0Amodule
@@ -376,31 +376,25 @@
 r))%0A%7D)%0A%0A
-module.exports.
+function 
 compareP
@@ -401,18 +401,16 @@
 asswords
- =
  (reqPas
@@ -420,18 +420,26 @@
 dbPass) 
-=%3E
+%7B%0A  return
  bcrypt.
@@ -466,16 +466,19 @@
  dbPass)
+ %0A%7D
 %0A%0Amodule
@@ -753,24 +753,113 @@
 ord, 10)%0A%7D%0A%0A
+function generateToken (payload) %7B%0A  return jwt.sign(payload, process.env.JWT_SECRET)%0A%7D%0A%0A
 module.expor
@@ -959,30 +959,601 @@
 resolve)%0A    .catch(reject)%0A
-
 %7D)
+%0A%0Amodule.exports.login = (username, password) =%3E new Promise((resolve, reject) =%3E %7B%0A  knex('users').select().where(%7B username %7D)%0A    .then(user =%3E %7B%0A      if (user.length) %7B%0A        if (comparePasswords(password, user%5B0%5D.password) === true) %7B%0A          return resolve(generateToken(%7B username: user%5B0%5D.username %7D))%0A        %7D else %7B%0A          //invalid password%0A          reject(%7B status: 401 %7D)%0A        %7D%0A      %7D%0A      // user not found%0A      reject(%7B status: 401 %7D)%0A    %7D)%0A%0A    .catch(err =%3E %7B%0A      reject()%0A    %7D)%0A%7D)%0A%0Amodule.exports.comparePasswords = comparePasswords

MOve the login concern to the user model