Skip to content

Instantly share code, notes, and snippets.

@technotim
Created January 5, 2017 04:13
Show Gist options
  • Save technotim/494ef38693e7e2e25f78fcc2e1b15c95 to your computer and use it in GitHub Desktop.
Save technotim/494ef38693e7e2e25f78fcc2e1b15c95 to your computer and use it in GitHub Desktop.
nodejs authentication user-mysql model
// app/models/user-mysql.js
// -----------------------------------------------------------------------
// Original script from RisingStack nodehero-authentication tutorial
// https://blog.risingstack.com/node-hero-node-js-authentication-passport-js/
// Mysql conversion by manjeshpv
// https://gist.github.com/manjeshpv/84446e6aa5b3689e8b84
// My version minimizes changes needed to the original passport.js file
// Revision Date: 1/4/17
// -----------------------------------------------------------------------
// Database connection
var mysql = require('mysql')
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'nodejs',
})
const table = 'passport_users'
// Encryption
var bcrypt = require('bcrypt-nodejs')
// Password functions
exports.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null)
}
exports.validPassword = function(password, userPassword) {
return bcrypt.compareSync(password, userPassword)
}
// Query functions mimics mongoose findById and findOne
// return callback(err, user) to be used by done()
exports.findById = function(id, callback){
connection.query("SELECT * from " + table + " where id = ?", [id], function(err,rows){
if(err)
return callback(err, null)
return callback(null, rows[0])
})
}
exports.findOne = function(field, value, callback){
connection.query("SELECT * from " + table + " where ?? = ?",[field, value], function(err,rows){
if(err){
return callback(err, null)
}
if(rows.length > 0){
return callback(null, rows[0])
}
return callback(null, null)
})
}
// Mimics mongoose save
exports.save = function(obj, callback){
var insertQuery = "INSERT INTO " + table + " ( email, password ) values (?,?)"
connection.query(insertQuery, [obj.email, obj.password], function(err,rows){
obj.id = rows.insertId
return callback(null, obj)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment