The solution Homework 2.3 M101JS: MongoDB for Node.js Developers

You should see four files in the ‘blog’ directory: app.js, users.js, posts.js, and sessions.js. There is also a ‘views’ directory which contains the templates for the project and a ‘routes’ directory which contains our express routes.

If everything is working properly, you should be able to start the blog by typing:

npm install
node app.js

Note that this requires Node.js to be correctly installed on your computer.
After you run the blog, you should see the message:

Express server listening on port 8082

If you go to http://localhost:8082 you should see the front page of the blog. Here are some URLs that must work when you are done.

http://localhost:8082/signup
http://localhost:8082/login
http://localhost:8082/logout

When you login or sign-up, the blog will redirect to http://localhost:8082/welcome and that must work properly, welcoming the user by username.

We have removed parts of the code that uses the Node.js driver to query MongoDB from users.js and marked the area where you need to work with “TODO: hw2.3”. You should not need to touch any other code. The database calls that you are going to add will add a new user upon sign-up and validate a login by retrieving the right user document.

The blog stores its data in the blog database in two collections, users and sessions. Here are two example docs for a username search with password salty. You can insert these if you like, but you don’t need to.

> use blog
switched to db blog
> db.users.find()
{ "_id" : "sverch", "password" : "$2a$10$wl4bNB/5CqwWx4bB66PoQ.lmYvxUHigM1ehljyWQBupen3uCcldoW" }
> db.sessions.find()
{ "username" : "sverch", "_id" : "8d25917b27e4dc170d32491c6247aabba7598533" }
>

Once you have the the project working, the following steps should work:

go to http://localhost:8082/signup
create a user

It should redirect you to the welcome page and say: welcome username, where username is the user you signed up with. Now:

    Goto http://localhost:8082/logout
    Now login http://localhost:8082/login

Ok, now it’s time to validate you got it all working.

From the top of this page, there was one additional program that should have been downloaded:mongoProc.

With it, you can test your code and look at the Feedback section. When it says “user creation successful” and “user login successful”, you can Turn in your assignment.

Solution:

  • Open user.js
  • See changes below //TODO HW 2.3. Changes are done in two places.
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;
        }
        // TODO: hw2.3
        users.insert(user, function (err, result) {
            "use strict";
            callback(err, result[0]);
        });
        //callback(Error("addUser Not Yet Implemented!"), 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);
            }
        }
        // TODO: hw2.3
        users.findOne({ '_id' : username}, function(err, user){
            if(err) throw err;
            validateUserDoc(err, user);
        });
       // callback(Error("validateLogin Not Yet Implemented!"), null);
    }
}
module.exports.UsersDAO = UsersDAO;
  • Save and run node js and perform signup and login in the browser if all are OK then open mongoProc and perform “Test” and if all seems OK then “Turn in”. While turning in I see the following screenshot.
m101js-homework_2.3

Let me know if get any problem so that we can solve each other help. As well as if you got any easy way to do it then please let me know.

Previous articleThe solution HW 2.2 M101JS: MongoDB for Node.js Developers
Next articleFinal: Question 1 M101JS: MongoDB for Node.js Developers

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here