users.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. const knex = require('../models/database');
  2. var bcrypt = require('bcrypt');
  3. const saltRounds = 10;
  4. var register = function(data){
  5. var username = data.username;
  6. var email = data.email;
  7. var password = data.password;
  8. return knex.table('Users').where({email}).select('*').
  9. then((data) => {
  10. //console.log('going here');
  11. if(data.length > 0) {
  12. throw Error('Email exists.');
  13. }
  14. return true;
  15. }).
  16. then(() => bcrypt.hash(password, saltRounds)).
  17. then((hash) => {
  18. // console.log("now here");
  19. data.password = hash;
  20. return knex.table('Users').insert(data);
  21. });
  22. }
  23. var login = function(data){
  24. var email= data.email;
  25. var password = data.password;
  26. var hash, Token;
  27. //console.log("here");
  28. return knex.table('Users').where({email}).select('*').
  29. then((data) => {
  30. if(data.length == 0){
  31. throw Error('The email you entered doesnt exists');
  32. }
  33. return data;
  34. }).
  35. then((data) =>
  36. bcrypt.compare(password,data[0].password)
  37. ).
  38. then((isPassCorrect) => {
  39. if(!isPassCorrect)
  40. throw Error('Wrong password');
  41. return bcrypt.genSaltSync(saltRounds);
  42. }).
  43. then((token) => {
  44. Token = token;
  45. return knex.table('Users').where({email}).update({token});
  46. }).
  47. then(() => Token);
  48. }
  49. module.exports = {
  50. Login:login,
  51. Register:register
  52. }