This repository has been archived by the owner on Dec 6, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
database.js
80 lines (72 loc) · 2.05 KB
/
database.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
var pg = require('pg')
var bcrypt = require('bcrypt')
var Database = module.exports = function(connectionString) {
if(!connectionString) {
connectionString = 'posgres://postgres@pg/postgres'
}
this.connectionString = connectionString
}
var comparePassword = function(password, hash, callback) {
bcrypt.compare(password, hash, function(err, isPasswordMatch) {
if (err) {
return callback(err);
}
console.log(err, isPasswordMatch)
return callback(null, isPasswordMatch);
});
}
Database.prototype.findUserByEmailAndPassword = function(email, password, callback) {
this.query('SELECT users.* FROM users WHERE email=$1', [email],
function(err, result) {
var user = result.rows[0]
if (!user) {
return callback("User not found");
}
comparePassword(password, user.password, function(err, isPasswordMatch) {
if (isPasswordMatch) {
callback(err, user)
} else {
callback(err)
}
})
});
}
var cryptPassword = function(password, callback ) {
bcrypt.genSalt(10, function(err, salt) {
if (err)
return callback(err)
bcrypt.hash(password, salt, function(err, hash) {
return callback(err, hash)
})
})
}
Database.prototype.createUser = function(email, password, callback) {
var self = this
cryptPassword(password, function(err, hashedPassword) {
if (err) {
callback(err)
} else {
self.query("INSERT INTO users(id, email, password) VALUES (uuid_generate_v4(), $1, $2)", [email, hashedPassword], function(err, result) {
if (err) {
callback(err)
} else {
callback(err, result.rows)
}
});
}
})
}
Database.prototype.query = function(query, variables, callback) {
pg.connect(this.connectionString, function(err, client, done) {
if(err) {
return console.error('error fetching client from pool', err);
}
client.query(query, variables, function(err, result) {
done();
if(err) {
console.error('error running query', err);
}
callback(err, result);
})
})
}