add user db model

This commit is contained in:
Shannon Sterz 2016-02-23 17:45:43 +01:00
parent ad14a07114
commit 8016a62c99

58
nodejs/models/users.js Normal file
View file

@ -0,0 +1,58 @@
var mysql = require('mysql');
var config = require('../config');
var crypto = require('crypto');
var jwt = require('jsonwebtoken');
var connection = mysql.createConnection({
host: config.mysql_host,
user: config.mysql_user,
password: config.mysql_secret,
database: config.mysql_database
});
connection.connect();
var Users = function () {
connection.query('CREATE TABLE IF NOT EXISTS users ( id INT(12) NOT NULL AUTO_INCREMENT, name VARCHAR(200) NOT NULL, salt VARCHAR(32) NOT NULL, hash VARCHAR(128) NOT NULL, UNIQUE (name), PRIMARY KEY (id) )'
, function(err, rows, fields) {
if (err) throw err;
});
}
Users.prototype.findById = function(id, callback) {
connection.query('SELECT * FROM users WHERE id = ?', [id], callback);
}
Users.prototype.findByName = function(name, callback) {
connection.query('SELECT * FROM users WHERE name = ?', [name.toLowerCase()], callback);
}
Users.prototype.validPassword = function (password, result) {
return result.hash === crypto.pbkdf2Sync(password, result.salt, 1000, 64).toString('hex');
};
Users.prototype.add = function(name, password, callback) {
var u = {
name: name.toLowerCase()
};
u.salt = crypto.randomBytes(16).toString('hex');
u.hash = crypto.pbkdf2Sync(password, u.salt, 1000, 64).toString('hex');
connection.query('INSERT INTO users SET ?', u, callback);
}
Users.prototype.generateJWT = function (id, username) {
var today = new Date();
var exp = new Date(today);
exp.setDate(today.getDate() + 60);
return jwt.sign({
_id: id,
username: username,
exp: parseInt(exp.getTime() / 1000),
}, config.crypto_secret);
};
module.exports = Users;