JAVASCRIPT

TOKEN BASED AUTHENTICATION FOR MEAN STACK APPS – PART 2


Let’s populate our user model. This is a mongoose schema that represents a collection in our Mongo Database.

user.server.model.js

Now, that we have a user model, it’s time to write a user controller that will manipulate the models.

user.server.controller.js

Let’s review our authenticateUserByEmailAndPassword function:

It accepts the request and response objects

We get the user’s email from the request body.

This is where our token is generated for the user.

jwt.sign(payload, secretOrPrivateKey, options)

payload  – can be a string, object or buffer

secretOrPrivateKey – is a string containing a unique secret or private key

options – various options for token expiry time, audience, issuer and others but we are concerned with only the expiry time here.

So, secrets.sessionSecret refers to ‘meanprosper’ from our .env file. Remember? :)

and we want the token to expire in 24hrs.

The next line indicates that the user collection in the database is been searched if the email exists. If it doesn’t,  an “Authentication failed. User not found” response is given Otherwise if it does exist, it goes ahead to compare passwords if they match. If it matches, the user details is returned as an array of one object.

We want just the _id and fullname of the user so we employ the help of lodash’s _.pick() to extract and store them in currUser variable.

NOTE: I know you are already itching to see it work, but keep calm and take a cup of juice :smile: , let’s quickly set up our routes

routes.js

Time to test what we’ve doing all along with POSTMAN

Postman helps to efficiently build, test and work with APIs. Let’s make a request to our login route.

Screen Shot 2015-07-03 at 10.09.21 AM

Aha!, the response is expected because we don’t have any user present in our database.

Let’s add some users. I use Robomongo ( Nice GUI for interacting with MongoDB ).

Go into the auth-mean database and into the users collection.

Screen Shot 2015-07-03 at 10.30.09 AM

password is actually “busayo” , the one on the image is bcrypt-encrypted

password is actually “goodness” ,the one on the image is bcrypt-encrypted

password is actually “amani” ; the one on the image is bcrypt-encrypted

Now, let’s test with a user in the database.

Yaaaagaaaah!!!!, it authenticated successfully and returned the user’s detail along with a token.

Now, let’s try to access all users route “/api/users”

Anybody can access that route,..we don’t want that, we want only authenticated users to be able to do that.

Let’s go back to routes.js

We had

now let’s add a middleware

This checks every request made to /api/users and ensures a valid token is present to access that route.

We already have a file named tokenMiddleware.js in our config folder. You remember?

In there, we have

Then it checks the headers if there is any token present,..if there is a token, it verifies whether we have the right token or not.

Now, let’s take  the token generated for busayo@gmail.com which is our user account and put them in the headers and try to access the route.

Yaggah!!!, we accessed the route successfully

Now, let’s remove the token in the header and see what happens:

😥

Let’s put back the token and replace some of the characters with some random ones.

Screen Shot 2015-07-03 at 11.59.41 AM

Aha!..Gotcha! .Someone is trying to hack our app but it detected and prevented it  :smile:

That’s all for now, We have a functional backend API. We’re going to cover consuming our API with AngularJs and bringing Life to all that we’ve been doing  in Part 3.

 

PROSPER OTEMUYIWA

About PROSPER OTEMUYIWA

Food Ninja, Code Slinger, Technical Trainer, Accidental Writer, Open Source Advocate and Developer Evangelist.