Created
April 6, 2016 14:12
-
-
Save edesilets/4955d530b49578f0cac2b008db8482d8 to your computer and use it in GitHub Desktop.
Current Code express/app/models/user.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// express/app/models/user.js | |
'use strict'; | |
const bcrypt = require('bcrypt'); | |
const Knex = require("knex")({ | |
client: "pg", | |
connection: { | |
host: "localhost", | |
user: "pi", | |
password: "password", | |
database: "homestatus" | |
} | |
}); | |
const bookshelf = require("bookshelf")(Knex); | |
exports.up = function(knex, Promise) { | |
return knex.schema.createTableIfNotExists('users', function(table) { | |
table.increments('id').notNullable().primary(); | |
table.string('email').notNullable().unique(); | |
table.string('token').unique(); | |
table.string('passwordDigest').notNullable(); | |
table.timestamps(); | |
}).createTableIfNotExists('temperatures', function(table) { | |
table.increments('id').notNullable().primary(); | |
table.string('main_topic'); | |
table.string('data_topic'); | |
table.float('data'); | |
table.timestamps(); | |
}); | |
}; | |
exports.up(Knex) | |
.then(() => { | |
console.log('Table created sucessfully'); | |
}) | |
.catch((err) => { console.log('opps little error keep going.');}); | |
let User = bookshelf.Model.extend({ | |
tableName: 'users', | |
initialize: function() { | |
this.on('creating', this.setPassword, this); | |
//this.on('updating', this.setPassword, this); | |
}, | |
setPassword: function (password) { | |
var _this = this; | |
return new Promise((resolve, reject) => | |
bcrypt.genSalt(null, (err, salt) => | |
err ? reject(err) : resolve(salt)) | |
) | |
.then((salt) => | |
new Promise((resolve, reject) => | |
bcrypt.hash(password.attributes.password, salt, (err, data) => | |
err ? reject(err) : resolve(data))) | |
) | |
.then((digest) => { | |
_this.attributes.passwordDigest = digest; | |
delete _this.attributes.password; | |
console.log('setPassword Save: \n ',_this); | |
return _this.attributes; | |
}); | |
}, | |
comparePassword: function (password) { | |
var _this = this; | |
return new Promise((resolve, reject) => | |
bcrypt.genSalt(null, (err, salt) => | |
err ? reject(err) : resolve(salt)) | |
).then((salt) => | |
new Promise((resolve, reject) => | |
bcrypt.hash(password, salt, (err, data) => | |
err ? reject(err) : resolve(data))) | |
).then((digest) => { | |
_this.attributes.passwordDigest = digest; | |
console.log('Compare Password this: \n', this , '\n'); | |
return _this.attributes; | |
}); | |
}, | |
}); | |
module.exports = User; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment