<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Thieves Like Us]]></title><description><![CDATA[Opinions and code. But mostly opinions.]]></description><link>http://brianmajewski.com/</link><generator>Ghost 0.6</generator><lastBuildDate>Wed, 08 Apr 2026 04:32:00 GMT</lastBuildDate><atom:link href="http://brianmajewski.com/tag/mongoose/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[(Re)Learning Backbone Part 9]]></title><description><![CDATA[<p><em>(Note: The code for this project at this point in our progress can be downloaded from <a href="https://github.com/bmajewski/relearning-backbone">Github</a> at commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/8a19651c576968b29f143d271147b0b288ca63a7">8a19651c576968b29f143d271147b0b288ca63a7</a>)</em></p>

<p><strong>Authentication and Authorization</strong></p>

<p>In this installment we'll tackle some functionality that I feel many tutorials leave out - authentication. We are going to implement a simple model that will both</p>]]></description><link>http://brianmajewski.com/2015/02/25/relearning-backbone-part-9/</link><guid isPermaLink="false">979665a2-f68d-4037-99ee-83f2e1cec6ab</guid><category><![CDATA[backbone]]></category><category><![CDATA[javascript]]></category><category><![CDATA[mongoose]]></category><category><![CDATA[json web tokens]]></category><category><![CDATA[bcrypt]]></category><dc:creator><![CDATA[Brian Majewski]]></dc:creator><pubDate>Thu, 26 Feb 2015 04:53:11 GMT</pubDate><media:content url="http://brianmajewski.com/content/images/2015/02/risk-based-authentication1.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://brianmajewski.com/content/images/2015/02/risk-based-authentication1.jpg" alt="(Re)Learning Backbone Part 9"><p><em>(Note: The code for this project at this point in our progress can be downloaded from <a href="https://github.com/bmajewski/relearning-backbone">Github</a> at commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/8a19651c576968b29f143d271147b0b288ca63a7">8a19651c576968b29f143d271147b0b288ca63a7</a>)</em></p>

<p><strong>Authentication and Authorization</strong></p>

<p>In this installment we'll tackle some functionality that I feel many tutorials leave out - authentication. We are going to implement a simple model that will both authenticate users and determine whether they are authorized to perform a function.  This implementation is not meant to be bulletproof but to get a basic workflow in place. We'll be identifying a user as an admin with permissions to delete users. In practice, I usually keep all admin type functions out of my main application. Keeping them to themselves in a purpose built app allows you to restrict the audience and enforce other security measures, such as IP whitelisting.</p>

<p>HTTP is a stateless transaction by default. Whether we create a server side session to track user details or not, we need some way to identify an incoming request as being made by a particular user. We will be using <a href="http://jwt.io/">JSON Web Tokens</a> to provide this identification. They will be generated by our server when a user authenticates themselves and stored in the browser's local storage. To demonstrate authorization and personalizing the interface we will also be asking the server for the user information for the currently logged in user and a set of permissions for actions they are allowed to take. We will use these permissions on the client to present a better experience for the user; we won't easily allow them to perform an action they are not authorized to perform. Ultimately, all actions will be verified on the server to prevent users from bypassing our UI restrictions.</p>

<p>Before we get into the code, let's take a look at the workflow of authenticating a user. Let's assume we have a home page accessible to anyone, our users page, accessible to logged in users, and the delete button accessible to anyone with Admin permissions.</p>

<p>We can describe our workflow in two places: the router and application wide AJAX error handling.</p>

<p>Here is the logic workflow we will be implementing in the router and supporting classes:</p>

<p><img src="http://brianmajewski.com/content/images/2015/02/router_flowchart-1.gif" alt="(Re)Learning Backbone Part 9"></p>

<p>Along with these decisions, we will intercept and handle the following HTTP error codes returned by our backend:</p>

<dl>  
<dt>401</dt><dd>The User is not Authenticated - Redirect to Login</dd>  
<dt>403</dt><dd>The User is not Authorized - Redirect to Home</dd>  
<dt>500</dt><dd>Generic Error Handling</dd>  
</dl>

<p>So, in the case that a user has a token, but it has expired, when they go to retrieve their User object, we will return a 401 error, forcing them to login.</p>

<p><strong>Creating An Admin User (The Wrong Way)</strong></p>

<p>We don't want to create a full featured permissions model or management console at this point. We haven't coded any features so trying to write permissions would be premature. It would be helpful for testing and prototyping, however, to indicate that one or more of our users had a specific property. To add these permissions to a user, we are going to cheat. For our POST <code>/api/users</code> and PUT <code>/api/users/:user_id</code> routes, we are going to check the request query parameters. Any parameters that match <code>permission=foo</code> will get added to a permissions block on the user. If there are none, the permissions block will be set to empty. We will also want to update our User schema to return these permissions as part of our normal retrieval functionality.</p>

<p><em>/app/models/user.js</em>  </p>

<pre><code class="language-javascript">var mongoose = require('mongoose');  
var Schema = mongoose.Schema;


var UserSchema = new Schema({  
    name: String,
    email: {type: String, required: true, index: {unique: true}},
    password: {type: String, required: true, select: false},
    permissions: [String]
});

module.exports = mongoose.model('User', UserSchema);  
</code></pre>

<p>Here we simply added an Array of Strings named <em>permissions</em> to the Schema.</p>

<p>And update the POST and PUT blocks in <code>/app/routes/user.js</code> to include  </p>

<pre><code class="language-javascript">user.permissions = req.query.permissions || [];  
</code></pre>

<p>where we set the other user properties. Now, using our Postman utility, create or update an existing user and some permissions to the url. For example:</p>

<pre><code>localhost:1337/api/users/54ea3206488bfd24c5ac7ee8?permissions=admin&amp;permissions=superhero  
</code></pre>

<p>This would then add <code>admin</code> and <code>superhero</code> to our permissions array. If we leave them off, an empty array is used. Again, this is <strong><em>The Wrong Way</em></strong> to do this, but it will serve our purposes.</p>

<p><strong>Changes</strong></p>

<p>So, let's run down the code changes we are going to make</p>

<ul>
<li><p>We are going to modify our backend server code and</p>

<ul><li>create an <code>/api/authenticate</code> endpoint that will accept credentials. If successful, it will return a token.</li>
<li>modify the <code>/api/user(s)</code> endpoints to check for the presence of a valid token before performing any actions. If one is not found, a 401 Unauthenticated error code will be returned.</li>
<li>modify the DELETE <code>/api/users/:user_id</code> endpoint to verify the authenticated user also has admin permissions. If not, a 403 Unauthorized error code will be returned.</li>
<li>update our server to accept requests from other domains. <em>(More on this later)</em>. 
<p></p></li></ul></li>
<li><p>We will create a login screen and</p>

<ul><li>extend the existing single user form view</li>
<li>add some simple client side validation to enforce name and email requirements</li>
<li>call the authentication endpoint</li>
<li>upon successful login we'll store the token received <br>
<p></p></li></ul></li>
<li><p>We will create a logout action in our navigation bar that</p>

<ul><li>will be visible only when logged in</li>
<li>will remove the stored token when activated
<p>  </p></li></ul></li>
<li>We will display information about the logged in user in the navigation bar
<p>  </p></li>
<li><p>We will modify our router to</p>

<ul><li>ensure that we are authenticated before showing the Users view
<p></p></li></ul></li>
<li><p>We will create an application wide object to</p>

<ul><li>perform authentication and logout actions</li>
<li>provide access to our currently logged in user
<p>  </p></li></ul></li>
<li>We will add application wide AJAX error handling</li>
</ul>

<p><strong>Server Updates</strong></p>

<p><em>Authentication Endpoint</em> - Until now, we've been storing our passwords in the database in  cleartext. We should really be encrypting them. Let's grab a <a href="https://www.npmjs.com/package/bcrypt-nodejs">crypto library</a> to handle that, along with the JSON Web Tokens library.</p>

<pre><code>npm install bcrypt-nodejs jsonwebtoken --save  
</code></pre>

<p>In <code>/app/models/user.js</code> let's go ahead and require the crypto library and add some functionality to use it.</p>

<pre><code class="language-javascript">var bcrypt = require('bcrypt-nodejs');

UserSchema.pre('save', function(next){  
    var user = this;
    if (!user.isModified()){
        return next();
    }

    bcrypt.hash(user.password, null, null, function(err,hash){
        if (err) {
            return next(err);
        }
        user.password = hash;
        next();
    })
});

UserSchema.methods.comparePassword = function(password){  
    var user = this;
    return bcrypt.compareSync(password, user.password);
};
</code></pre>

<p>We have two things going on here. First, we've added a hook to the User schema that will get called before any Save operation. If the document has been modified, or is new, we assume the password has been modified and is in cleartext. We convert it to an encrypted form, and then let the normal save function occur.</p>

<p>Secondly, we've added a <code>comparePassword</code> method to the User object. When we authenticate a user, we will use this compare the submitted password to the stored one.</p>

<p>Now let's update our user routes in <code>/app/routes/user.js</code>. First add our dependency:</p>

<pre><code class="language-javascript">var jwt = require('jsonwebtoken');

var superSecret = 'TheAmazingKreskin`;  
</code></pre>

<p>We've also created a "secret word" that we will use when encrypting and decrypting our token. This should probably be stored in a config file or passed in on the command line for better security. </p>

<p>After our default <code>/api/</code> route, let's create our <code>/api/authenticate</code> route</p>

<pre><code class="language-javascript">var userRouter = express.Router();

userRouter.post('/authenticate', function (req, res) {  
    User.findOne({
        email: req.body.email
    }).select('name email password').exec(function (err, user) {
        if (err) throw err;

        if (!user) {
            res.json({success: false, message: 'User not found'});
        } else {
            var validPassword = user.comparePassword(req.body.password);
            if (!validPassword) {
                res.json({success: false, message: 'Wrong password'});
            } else {
                var token = jwt.sign({
                    name: user.name,
                    email: user.email,
                    _id: user._id
                }, superSecret, {
                    expiresInMinutes: 1440
                });

                res.json({
                    success: true,
                    message: 'login ok',
                    token: token,
                    _id: user._id
                });
            }
        }
    });
});

userRouter.get('/', function (req, res) {  
    res.json({message: 'api is loaded'});
});
</code></pre>

<p>When receive the POST request, we lookup the user by the provided email, and select their name and password as well. Remember, by default, our Schema does not return a password. In the event of an error or the user is not found, an error is returned to the user. In this instance, we don't send an error response. We expect that an unsuccessful attempt is a common occurrence, so we will explicitly handle the response. In this way, we could count the number of attempts or provide extra help, rather than just redirecting back to the login page.</p>

<p>If the user is found, we compare the submitted password to the one on record. If successful, we create a token with some user info in it and a timeout of 1440 minutes, or 24 hours. This will force the user to reauthenticate after one day, even if they have a proper token. Encrypting it will prevent the token from being modified by the client.</p>

<p>Using our Postman extension, we can test this endpoint right away. Using our prvious user editing capabilities, change the password on one of the users. This will ensure that the password associated with the user is encrypted in the database. (In fact, you may want to clean out any other users you created since they will need to have their passwords reset. For a production app, we could trap for this condition and handle it gracefully. Let's just delete them and make new ones.)</p>

<p>Make a POST request to <code>/api/authenticate</code> with a body of  </p>

<pre><code>{"email" : "email_value", "password": "password_value"}
</code></pre>

<p>using the values for that user you updated. Remember to set the Content-Type header to <code>application/json</code>. If the passwords match, you should see a response similar to</p>

<pre><code class="language-javascript">{
    "success": true,
    "message": "login ok",
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiQnJpYW4gTSIsIl9pZCI6IjU0ZTZiMTYyZWIyYWM2MWM1NGU5YjgwZiIsImlhdCI6MTQyNDkyNTA4MCwiZXhwIjoxNDI1MDExNDgwfQ.90utguKl1XrpQZHU6tYPzOhskOeSl4k5RTTk6JcbuDo",
    "_id": "54e6b162eb2ac61c54e9b80f"
}
</code></pre>

<p>Even with our authentication endpoint in place, we have no problem accessing our app, even if we provided the wrong password. We'll need to tell the other routes to check for a valid token to be sent with every request.</p>

<p>After our default route, add the following code. Since this is declared <em>after</em> the default route, we will still be able to access it without authentication.</p>

<pre><code class="language-javascript">userRouter.get('/', function (req, res) {  
    res.json({message: 'api is loaded'});
});

userRouter.use(function (req, res, next) {  
    var token = req.body.token || req.params.token || req.headers['x-access-token'];
    if (token) {
        jwt.verify(token, superSecret, function (err, decoded) {
            if (err) {
                return res.status(401).send({success: false, message: 'Failed to authenticate token'});
            } else {
                req.decoded = decoded;
                next();
            }
        })
    } else {
        return res.status(401).send({success: false, message: 'No token provided'});
    }
});
</code></pre>

<p>With the <em>use</em> directive, we are adding some middleware to our route. For every request on routes declared after this we will attempt to find a token value in the body, in the parameters, or even in the headers. If a token is found, we verify it with our secret word. If it is valid, we continue to the <em>next</em> request handler, which will be our standard GET, PUT, POST, etc. calls. If there is no token, or it is invalid, we send a 401 HTTP error with an appropriate message. Our client will know that it needs to reauthenticate when it receives such a message.</p>

<p>Now, if we try to access our users page, we will get an error and nothing will display. </p>

<p><strong>Next Steps</strong></p>

<p>In our next installment, we'll wire up the client to call the authenticate endpoint when needed and send our token on future calls.</p>

<p>(The code at this state in the project can be checked out at commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/dae2b441bf1c718a6000df50679a6b096d70d8c4">dae2b441bf1c718a6000df50679a6b096d70d8c4</a>)</p>]]></content:encoded></item><item><title><![CDATA[(Re)Learning Backbone Part 4]]></title><description><![CDATA[<p><em>(Note: The code for this series is available on <a href="https://github.com/bmajewski/relearning-backbone">Github</a> - To get the code in preparation for this installment, checkout commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/d82adb485a608278b2003415cab536503c40d5d2">d82adb485a608278b2003415cab536503c40d5d2</a>)</em></p>

<p><strong>Database Integration</strong></p>

<p>A lot of tutorials wave their hands at this point and assume you have a database connected. Worse, some will have you write stubs and</p>]]></description><link>http://brianmajewski.com/2015/02/19/relearning-backbone-part-4/</link><guid isPermaLink="false">6735c52a-db17-41c0-a71f-1fe0a8ccfa47</guid><category><![CDATA[javascript]]></category><category><![CDATA[mongodb]]></category><category><![CDATA[node]]></category><category><![CDATA[express]]></category><category><![CDATA[mongoose]]></category><category><![CDATA[postman]]></category><category><![CDATA[crud]]></category><dc:creator><![CDATA[Brian Majewski]]></dc:creator><pubDate>Fri, 20 Feb 2015 04:17:04 GMT</pubDate><media:content url="http://brianmajewski.com/content/images/2015/02/Mongoose_-PSF-.png" medium="image"/><content:encoded><![CDATA[<img src="http://brianmajewski.com/content/images/2015/02/Mongoose_-PSF-.png" alt="(Re)Learning Backbone Part 4"><p><em>(Note: The code for this series is available on <a href="https://github.com/bmajewski/relearning-backbone">Github</a> - To get the code in preparation for this installment, checkout commit: <a href="https://github.com/bmajewski/relearning-backbone/commit/d82adb485a608278b2003415cab536503c40d5d2">d82adb485a608278b2003415cab536503c40d5d2</a>)</em></p>

<p><strong>Database Integration</strong></p>

<p>A lot of tutorials wave their hands at this point and assume you have a database connected. Worse, some will have you write stubs and timeouts to simulate connection delays. If you know what you're doing, these can be a quick way to get a screen or feature running. If you're building from the ground up, you're just delaying the inevitable. Plus, if you've never done it before, figuring out how to wire it in later can be a challenge.</p>

<p><strong>MongoDB and mongoose</strong></p>

<p>Earlier in this series we installed <a href="http://www.mongodb.org/">MongoDB</a>. Ensure that you have a running copy before continuing. For a GUI front end, I like using <a href="https://github.com/jeromelebel/MongoHub-Mac">MongoHub</a>. <a href="http://mongoosejs.com/">Mongoose</a> is an object modeling solution that lets you write simple schema based objects to work between your Node server and your Mongo database. It has hooks for validation, query building and more, and with a healthy plugin ecosystem can do nearly anything you throw at it. We'll only scratch the surface of its feature set.</p>

<p>To install mongoose, run:</p>

<pre><code>npm install mongoose --save  
</code></pre>

<p>We'll need to tell our app how to connect to MongoDB. In our <code>server.js</code> file, add  </p>

<pre><code>var mongoose = require('mongoose');  
</code></pre>

<p>to the dependencies section at the top. Then underneath that, add  </p>

<pre><code>mongoose.connect('mongodb://localhost:27017/rlbb');  
</code></pre>

<p>If you configured MongoDB to run on another port, edit the above the string. <code>rlbb</code> is the name of our database and will be created if not present. Here is also where we would add things like database username, password, and the like if we had them.</p>

<p>Now, let's create a User model. Under <code>app/models</code>, create <code>user.js</code></p>

<pre><code class="language-javascript">var mongoose = require('mongoose');  
var Schema = mongoose.Schema;

var UserSchema = new Schema({  
    name: String,
    email: {type: String, required: true, index: {unique: true}},
    password: {type: String, required: true, select: false}
});

module.exports = mongoose.model('User', UserSchema);  
</code></pre>

<p>Here, we've pulled in our mongoose dependency and created a User Schema object. Mongoose uses the Schema as representation of a MongoDB collection and the base of its functionality. We've defined a <strong>name</strong>, an <strong>email</strong>, and a <strong>password</strong>. Along with the property names, we've defined their <em>SchemaType</em>, in this case, they are all Strings. For email and password, we've also included some additional properties. <em>required</em> indicates that the field must be present to be valid. Other validators include <em>min</em>, <em>max</em>, <em>match</em>, and custom validators can be created. For email, which we will use as our username, we create an index for it, and put a <em>unique</em> constraint on it. For password, we indicate that normal retrieval of this object from the collection should <em>not</em> include the password field. This prevents it from going across the network. When we add authentication later, we will explicitly ask for the password. Finally, we create a mongoose model from the schema and export it.</p>

<p><strong>Our First REST Endpoints</strong></p>

<p>So, we have a model of our User data. We now need a way to retrieve it from and write it to the database. In this app, all of our API URLs will start with <code>/api/</code> and then follow with the appropriate REST endpoints. For user, we will end up creating:  </p>

<dl>  
    <dt>/api/users</dt>
    <dd>POST - With a POST request, a new user will be created.<br>
    GET - With a GET request, this will return all users.
    </dd>

    <dt>/api/users/:user_id</dt>
    <dd>GET - With a GET request, this will return a single user with an ID that matches <i>:user_id</i>.<br>
    PUT - With a PUT request, the user indicated will be updated.<br>
    DELETE - With a DELETE request, the user indicated will be deleted.</dd>
</dl>

<p>With just two endpoints, and using the HTTP verbs, we can satisfy our basic CRUD requirements. To define these, we will create an Express router and then have Express <em>use</em> it, much like we did with the static assets directory and the catch all request handler.</p>

<p>Under <code>app/routes</code>, create <code>user.js</code> <sup id="fnref:1"><a href="http://brianmajewski.com/2015/02/19/relearning-backbone-part-4/#fn:1" rel="footnote">1</a></sup>.</p>

<pre><code class="language-javascript">var bodyParser = require('body-parser');  
var User = require('../models/user');

module.exports = function (app, express) {  
    var userRouter = express.Router();

    userRouter.get('/', function (req, res) {
        res.json({message: 'api is loaded'});
    });

    userRouter.route('/users')
        .post(function (req, res) {
            var user = new User();
            user.name = req.body.name;
            user.username = req.body.username;
            user.password = req.body.password;

            user.save(function (err) {
                if (err) {
                    if (err.code === 11000) {
                        return res.json({success: false, message: 'Duplicate username.'});
                    } else {
                        return res.send(err);
                    }
                } else {
                    res.json({message: 'user created'});
                }

            });
        })
        .get(function (req, res) {
            User.find(function (err, users) {
                if (err) {
                    res.send(err);
                }
                res.json(users);
            })
        });

    userRouter.route('/users/:user_id')
        .get(function (req, res) {
            User.findById(req.params.user_id, function (err, user) {
                if (err) res.send(err);
                res.json(user);
            })
        })
        .put(function (req, res) {
            User.findById(req.params.user_id, function (err, user) {
                if (err) res.send(err);

                if (req.body.name) user.name = req.body.name;
                if (req.body.email) user.email = req.body.email;
                if (req.body.password) user.password = req.body.password;

                user.save(function (err) {
                    if (err)res.send(err);
                    res.json({message: 'user updated'});
                });
            });
        })
        .delete(function (req, res) {
            User.remove({_id: req.params.user_id}, function (err, user) {
                if (err) res.send(err);
                res.json({message: 'user deleted'});
            })
        });

    return userRouter;
};
</code></pre>

<p>This looks like a lot, but it's fairly straightforward. Let's tackle it a chunk at a time.</p>

<pre><code class="language-javascript">var bodyParser = require('body-parser');  
var User = require('../models/user');  
</code></pre>

<p>Here will pull in our dependencies. We will use <em>body-parser</em> to get the data that comes with the PUT and POST requests and <em>User</em> is the user model we just created.</p>

<pre><code class="language-javascript">    var userRouter = express.Router();

    userRouter.get('/', function (req, res) {
        res.json({message: 'api is loaded'});
    });
</code></pre>

<p>Here we create an instance of an Express router. To give us a way to verify our routes have been initialized properly, we create a default route <code>api/</code> that will respond with a canned message. If there are problems we can use this to see if it is a server or database issue.</p>

<pre><code class="language-javascript">userRouter.route('/users')  
        .post(function (req, res) {
            var user = new User();
            user.name = req.body.name;
            user.email = req.body.email;
            user.password = req.body.password;

            user.save(function (err) {
                if (err) {
                    if (err.code === 11000) {
                        return res.json({success: false, message: 'Duplicate username.'});
                    } else {
                        return res.send(err);
                    }
                } else {
                    res.json({message: 'user created'});
                }

            });
        })
        .get(function (req, res) {
            User.find(function (err, users) {
                if (err) {
                    res.send(err);
                }
                res.json(users);
            })
        });
</code></pre>

<p>Here we create the <code>api/users</code> route and handle both the POST and the GET cases. In the POST block, we create a new User, set the fields with data from the request body, and save it. Mongoose handles the heavy lifting of creating the query and talking to the database. We perform some basic error-handling, and return an appropriate message to the client.</p>

<p>In the GET block, we call a static model method on User to retrieve all the stored users and return them. Once again, mongoose takes care of the details.</p>

<pre><code class="language-javascript">userRouter.route('/users/:user_id')  
        .get(function (req, res) {
            User.findById(req.params.user_id, function (err, user) {
                if (err) res.send(err);
                res.json(user);
            })
        })
        .put(function (req, res) {
            User.findById(req.params.user_id, function (err, user) {
                if (err) res.send(err);

                if (req.body.name) user.name = req.body.name;
                if (req.body.username) user.username = req.body.username;
                if (req.body.password) user.password = req.body.password;

                user.save(function (err) {
                    if (err)res.send(err);
                    res.json({message: 'user updated'});
                });
            });
        })
        .delete(function (req, res) {
            User.remove({_id: req.params.user_id}, function (err, user) {
                if (err) res.send(err);
                res.json({message: 'user deleted'});
            })
        });
</code></pre>

<p>Here we create the <code>api/users/:user_id</code> route. Express will take the value in the request that maps to the <code>:user_id</code> section and create a request parameter that we can use. In the GET block, we use mongoose's <em>findById</em> method to retrieve a specific user. In the PUT block, we again retrieve the requested user, update its information with data from the request body, then save it. Finally, in the DELETE block, we use mongoose's <em>remove</em> function to delete the specified user.</p>

<p>Now it's time to wire the router into the server. In <code>server.js</code>, <strong>after</strong> the static directory declaration, add the following</p>

<pre><code class="language-javascript">// already in our file
app.use(express.static(__dirname + '/public'));

// ADD THESE TWO LINES
var userRoutes = require('./app/routes/user')(app, express);  
app.use('/api', userRoutes);

// already in our file
app.get('*', function(req,res){  
    res.sendFile(path.join(__dirname + '/public/index.html'));
});
</code></pre>

<p>First we create the routes, by requiring the file and passing it the two needed fields, app and express. (Go back and look at how we declared our router definition and you will see we have these two params listed). Then, we tell our server to <em>use</em> the routes. Remember, order is important. First our static files, then our API routes, and finally the catch all to serve up our home page. If we added our routes after the catch all, they would never be hit.</p>

<p>If we were to run our server now, with <code>nodemon server.js</code> we would be able to get and set users via HTTP. But... we don't have any users yet, and we don't have screens to input data. Any easy solution is to use something like <a href="https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm/related?hl=en">Postman - REST Client for Chrome</a> (all the browsers have similar tools). In the URL field, enter <code>localhost:1337/api</code> and make sure GET is selected in the dropdown. When you hit send, you should see our test message returned in JSON format. </p>

<p>We can do a similar task to add a user. Set the URL to <code>localhost:1337/api/users</code>, the method to POST, select <code>raw</code> for our input data and add</p>

<pre><code>{ "email" : "hireme@brianmajewski.com", name: "Brian M", password: "123456Secure!"}
</code></pre>

<p>These are the fields we defined on our User model.</p>

<p>We also need to set our content type, so select Headers, and for name put <code>Content-Type</code> and value put <code>application/json</code>. If we're configured right, you should get a response back saying user created. To see our new user, hit the same URL, with GET, and you should receive a response similar to</p>

<pre><code>[
    {
        "_id": "54e6b162eb2ac61c54e9b80f",
        "email": "hireme@brianmajewski.com",
        "name": "Brian M",
        "__v": 0
    }
]
</code></pre>

<p>Notice: Our password is not returned, as we specified in our schema. Experiment with the other routes and verify that you can update and delete users as well.</p>

<p>So there you have the basics for all CRUD operations for your app. Whether you are storing Widgets, Gizmos, Comments, or Reviews, you will follow the same basic pattern. Later, when we add authentication, you'll see how we can enhance mongoose's standard methods to perform extra functionality, such as encrypting the password, before saving the user.</p>

<p>To get the code with these updates checkout commit <a href="https://github.com/bmajewski/relearning-backbone/commit/18b0d51ee45d966abf9293be9a5fe25c6af8c6a6">18b0d51ee45d966abf9293be9a5fe25c6af8c6a6</a></p>

<p><strong>Next Steps</strong></p>

<p>With a functional backend in place, we will begin to create our front end web application. We'll look at using Bower to manage dependencies and RequireJS to load modules.</p>

<p>(<strong>UPDATE</strong>: There was a bug in the PUT block of the /users/:user_id route - <em>username</em> should have been <em>email</em> - This bug was fixed in the Chapter 7 version of the code on Github and in the text above)</p>

<div class="footnotes"><ol>  
    <li class="footnote" id="fn:1">
        <p>Some people prefer to include the function in the name, such as userModel.js and userRoute.js. I go back and forth on this. They are namespaced by their directory structure, so if there is no chance I am going to get them confused, I'll shorten them like I did here. You can name them mickey, pluto, and goofy if that floats your boat. I prefer frameworks without magic naming conventions.<a href="http://brianmajewski.com/2015/02/19/relearning-backbone-part-4/#fnref:1" title="return to article"> ↩</a></p><p>
    </p></li>
    </ol></div>]]></content:encoded></item></channel></rss>