So lets start!

First of all, you should make your folder structure as follows:

API folder structure

Don’t worry about the index.js file, it’s empty for now.

Now we need to install a few dependencies, go to your root folder (in my case focus-budget-manager) and do the following:

npm i --save express body-parser mongoose consign cors bcrypt jsonwebtoken morgan passport passport-jwt module-alias

Now I’ll try to explain what each of these dependencies do:

Express

Express is a framework for Node.js, we will use it to facilitate our API developing.

Express is a framework for Node.js, we will use it to facilitate our API developing. Body Parser

Body Parser is a Node.js body parsing middleware, it parses incoming request bodies before our handles so we can access it under req.body property.

Body Parser is a Node.js body parsing middleware, it parses incoming request bodies before our handles so we can access it under req.body property. Mongoose

Mongoose is a MongoDB object modelling tool to work in an asynchronous environment.

Mongoose is a MongoDB object modelling tool to work in an asynchronous environment. Consign

This package is completely optional as it works as an autoload for your scripts.

This package is completely optional as it works as an autoload for your scripts. CORS

This is a package for providing Connect/Express middleware that can be used to enable CORS.

This is a package for providing Connect/Express middleware that can be used to enable CORS. Bcrypt

This package is used to generate salt and hashes.

This package is used to generate salt and hashes. Morgan

An HTTP request logger middleware for Node.js.

An HTTP request logger middleware for Node.js. Module Alias

Allows you to create aliases of directories and register custom module paths in Node.js.

After installing these packages, create a .gitignore file in the root folder if you intend to use git and write:

/node_modules/

Now lets finally do some coding!

Create a file named index.js inside your BudgetAPI/config folder and write the following:

module.exports = {

secret: 'budgetsecret',

session: { session: false },

database: 'mongodb://127.0.0.1:27017/budgetmanager'

}

This file holds our database connection parameters and the secret we’ll use to generate our JWT token.

You can change 127.0.0.1:27017 to localhost or even use a MongoDB that’s located in the cloud such as MLabs.

Next we will create our Users model for our JWT Auth. Go to BudgetManagerAPI/app and create a folder named models which contains a user.js file.

At the top of the file, we will require these packages:

const mongoose = require('mongoose'),

bcrypt = require('bcrypt');

We’ll need mongoose so we can create our User model and Bcrypt to hash our users passwords.

const Schema = mongoose.Schema({

username: {

type: String,

unique: true,

required: true

}, password: {

type: String,

required: true

}, clients: [{}]

});

This will create our User schema, one user will have:

A username

A password

Clients

And each client will have:

An email

A name

A phone

Budgets

Every budget will have a state, a title, items and a price.

// We won't use arrow functions here because of automatic lexical scope binding Schema.pre('save', function (next) {

const user = this; if (this.isModified('password') || this.isNew) {

bcrypt.genSalt(10, (error, salt) => {

if (error) return next(error); bcrypt.hash(user.password, salt, (error, hash) => {

if (error) return next(error); user.password = hash;

next();

});

});

} else {

return next();

}

});

In this function we generate a salt and hash our users passwords.

Now just below this we’ll add a function to compare passwords to check if the login attempt is valid or not:

Schema.methods.comparePassword = function (password, callback) {

bcrypt.compare(password, this.password, (error, matches) => {

if (error) return callback(error);

callback(null, matches);

});

};

And then at the end of the file we will finally create our User model: