diff options
| author | mo khan <mo@mokhan.ca> | 2015-02-20 21:47:20 -0700 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2015-02-20 21:47:20 -0700 |
| commit | fe7e28edee40691d8b1189769a9b1b9939686d77 (patch) | |
| tree | a8a57e33369da7f4d6b5267c082fd6644974686f /week-7/Final4/blog/users.js | |
| parent | bd663082a8b29b02a98b52fe384cfbde18bedf73 (diff) | |
add final 3 and 4 validation scripts.
Diffstat (limited to 'week-7/Final4/blog/users.js')
| -rw-r--r-- | week-7/Final4/blog/users.js | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/week-7/Final4/blog/users.js b/week-7/Final4/blog/users.js new file mode 100644 index 0000000..5960dbd --- /dev/null +++ b/week-7/Final4/blog/users.js @@ -0,0 +1,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; |
