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
|
var bcrypt = require('bcrypt-nodejs');
/* The UsersDAO must be constructed with a connected database object */
function UsersDAO(db) {
"use strict";
/* If this constructor is called without the "new" operator, "this" points
* to the global object. Log a warning and call it correctly. */
if (false === (this instanceof UsersDAO)) {
console.log('Warning: UsersDAO constructor called without "new" operator');
return new UsersDAO(db);
}
var users = db.collection("users");
this.addUser = function(username, password, email, callback) {
"use strict";
// Generate password hash
var salt = bcrypt.genSaltSync();
var password_hash = bcrypt.hashSync(password, salt);
// Create user document
var user = {'_id': username, 'password': password_hash};
// Add email if set
if (email != "") {
user['email'] = email;
}
users.insert(user, function (err, result) {
"use strict";
if (!err) {
console.log("Inserted new user");
return callback(null, result[0]);
}
return callback(err, null);
});
}
this.validateLogin = function(username, password, callback) {
"use strict";
// Callback to pass to MongoDB that validates a user document
function validateUserDoc(err, user) {
"use strict";
if (err) return callback(err, null);
if (user) {
if (bcrypt.compareSync(password, user.password)) {
callback(null, user);
}
else {
var invalid_password_error = new Error("Invalid password");
// Set an extra field so we can distinguish this from a db error
invalid_password_error.invalid_password = true;
callback(invalid_password_error, null);
}
}
else {
var no_such_user_error = new Error("User: " + user + " does not exist");
// Set an extra field so we can distinguish this from a db error
no_such_user_error.no_such_user = true;
callback(no_such_user_error, null);
}
}
users.findOne({ '_id' : username }, validateUserDoc);
}
}
module.exports.UsersDAO = UsersDAO;
|