Advertisement
Guest User

Untitled

a guest
Apr 7th, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. // express/app/models/user.js
  2. 'use strict';
  3.  
  4. const bcrypt = require('bcrypt');
  5. const Knex = require("knex")({
  6. client: "pg",
  7. connection: {
  8. host: "localhost",
  9. user: "pi",
  10. password: "password",
  11. database: "homestatus"
  12. }
  13. });
  14. const bookshelf = require("bookshelf")(Knex);
  15.  
  16. exports.up = function(knex, Promise) {
  17. return knex.schema.createTableIfNotExists('users', function(table) {
  18. table.increments('id').notNullable().primary();
  19. table.string('email').notNullable().unique();
  20. table.string('token').unique();
  21. table.string('passwordDigest').notNullable();
  22. table.timestamps();
  23. }).createTableIfNotExists('temperatures', function(table) {
  24. table.increments('id').notNullable().primary();
  25. table.string('main_topic');
  26. table.string('data_topic');
  27. table.float('data');
  28. table.timestamps();
  29. });
  30. };
  31.  
  32. exports.up(Knex)
  33. .then(() => {
  34. console.log('Table created sucessfully');
  35. })
  36. .catch((err) => { console.log('opps little error keep going.');});
  37.  
  38. let User = bookshelf.Model.extend({
  39. tableName: 'users',
  40. initialize: function() {
  41. this.on('creating', this.setPassword, this);
  42. //this.on('updating', this.setPassword, this);
  43. },
  44. setPassword: function (password) {
  45. var _this = this;
  46. return new Promise((resolve, reject) =>
  47. bcrypt.genSalt(null, (err, salt) =>
  48. err ? reject(err) : resolve(salt))
  49. )
  50. .then((salt) =>
  51. new Promise((resolve, reject) =>
  52. bcrypt.hash(password.attributes.password, salt, (err, data) =>
  53. err ? reject(err) : resolve(data)))
  54. )
  55. .then((digest) => {
  56. _this.attributes.passwordDigest = digest;
  57. delete _this.attributes.password;
  58. console.log('setPassword Save: \n ',_this);
  59. return _this.attributes;
  60. });
  61. },
  62. comparePassword: function (password) {
  63. var _this = this;
  64.  
  65. return new Promise((resolve, reject) =>
  66. bcrypt.genSalt(null, (err, salt) =>
  67. err ? reject(err) : resolve(salt))
  68. ).then((salt) =>
  69. new Promise((resolve, reject) =>
  70. bcrypt.hash(password, salt, (err, data) =>
  71. err ? reject(err) : resolve(data)))
  72. ).then((digest) => {
  73. _this.attributes.passwordDigest = digest;
  74. console.log('Compare Password this: \n', this , '\n');
  75. return _this.attributes;
  76. });
  77. },
  78. });
  79.  
  80. module.exports = User;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement