-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.js
81 lines (65 loc) · 2.35 KB
/
functions.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
81
var bcrypt = require('bcryptjs'),
Q = require('q'),
config = require('./config.js'); //config file contains all tokens and other private info
// MongoDB connection information
var mongodbUrl = 'mongodb://' + config.mongodbHost + ':27017/users';
var MongoClient = require('mongodb').MongoClient
//used in local-signup strategy
exports.localReg = function (username, password) {
var deferred = Q.defer();
MongoClient.connect(mongodbUrl, function (err, db) {
var collection = db.collection('localUsers');
//check if username is already assigned in our database
collection.findOne({'username' : username})
.then(function (result) {
if (null != result) {
console.log("USERNAME ALREADY EXISTS:", result.username);
deferred.resolve(false); // username exists
}
else {
var hash = bcrypt.hashSync(password, 8);
var user = {
"username": username,
"password": hash,
"avatar": "http://placepuppy.it/images/homepage/Beagle_puppy_6_weeks.JPG"
}
console.log("CREATING USER:", username);
collection.insert(user)
.then(function () {
db.close();
deferred.resolve(user);
});
}
});
});
return deferred.promise;
};
//check if user exists
//if user exists check if passwords match (use bcrypt.compareSync(password, hash); // true where 'hash' is password in DB)
//if password matches take into website
//if user doesn't exist or password doesn't match tell them it failed
exports.localAuth = function (username, password) {
var deferred = Q.defer();
MongoClient.connect(mongodbUrl, function (err, db) {
var collection = db.collection('localUsers');
collection.findOne({'username' : username})
.then(function (result) {
if (null == result) {
console.log("USERNAME NOT FOUND:", username);
deferred.resolve(false);
}
else {
var hash = result.password;
console.log("FOUND USER: " + result.username);
if (bcrypt.compareSync(password, hash)) {
deferred.resolve(result);
} else {
console.log("AUTHENTICATION FAILED");
deferred.resolve(false);
}
}
db.close();
});
});
return deferred.promise;
}