Sails Backend for Angular2+ Auth

This post is intending to demonstrate securing angular 2+ single page application post here

We are going to use sails to create our quick apis , before we begin, make sure you have node installed.

Our api is going to be using mysql or mongo db any of the database you have installed, you can head over to their respective sites to learn how to get any installed.

Now let’s get to setting up our sails node api backend. Open up your terminal and type the following

npm install sails -g

Yeahhhh sails is installed on our local machine, we move to creating our sails application by typing the below command

sails new server-api — no-frontend

our folder should be cooking with our sails components. After the cooking our server-api folder should be ready, just do

sails lift

which should give us something like this

so our api is working Hurrayyy!!!. Now we need to install dependencies we are going to create our api

npm install bcryptjs — save

That above command is for hashing password. The next is for our json web token based authentication

npm install jsonwebtoken — save

The last one is for handling validation like errors

npm install sails-hook-validation — save

Creating models which is like our database table from mysql view or collections in mongodb, since we are dealing with creating authentication backend we won’t dive much into sails, now we create our user model, easy to do by using the following command

sails generate api user

that should help us create the user model and userController under api/models and api/controllers respectively. We move to our user.js model file to create our fields that the user is going to hold. So it should finally look like this

Now that our user mode is done, we can perform general blueprint actions like post, get, delete and put on it from our frontend. Note you can use policies to block which is required to be public or requires some special authentication. Now we are going to just make it opened.

Now let’s create our api methods for

  • Login: uses the email and password sent through request body to perform login
  • Token: helps to refresh our token from the initial token sent from the request header and return a newer token

Let’s move on to userController.js under the api/controllers folder and create the above logics, it should look like this now

Before we start to consume our service let’s create our policy to handle Authentication checking for our token. Under the api/policies folder create a file called isAuth.js

NB: You can create a services/config.js file to hold our secret key for our jsonwebtoken library.

Let’s make use of this policy now on our user controller edit, delete, update blueprint. Open up config/policies.js and make it like the one below

finally, we need to create our api route for login and token on our config/routes.js like so

Yeaaa we are done, let’s open up postman to test our api. Oh we need to handle which database to use with our api (mysql or mongodb). If you have mysql on your system you can do this below

npm install sails-mysql — save

For mongo db we install this adapter

npm install sails-mongo — save

Open up your config/connection.js and do this

For mysql:

authApiMysql: {
adapter: 'sails-mysql',
host: 'localhost',
user: 'root', //optional
password: 'root', //optional
database: 'testAuthDB'

For mongo:

authApiMongo: {
adapter: 'sails-mongo',
host: 'localhost',
port: 27017,
database: 'testAuthDB'

Now depending on your database open up config/models.js. For mysql

connection: ‘authApiMysql’

For mongo

connection: ‘authApiMongo’

then migrate: ‘alter’

Now sails liftagain, you will see your database has been created with the models created as tables or collections.

If you having this error below

error: Error (E_UNKNOWN) :: Encountered an unexpected error 
: Could not connect to MySQL:
Error: ER_BAD_DB_ERROR: Unknown database ‘testauthdb’

Then goto your database console to create ‘testauthdb’ for mysql users.

Postman we are here, open it up and send a post request to http://localhost:1337/user, passing email, name, password, like so

now we have created our user, next is to try the login now with the created parameters

Let’s test our token api if its creates or refresh our api for us since it expires every 10 mins before 10mins we refresh with the older token using header like so

So we are good to return to our Angular2+ single page authentication post, but before we go one last thing is to checkout for this file config/cors.js when having cors issue connecting to our backend from our frontend server updating the file to be like this should help out

Restart sails and all good to go.

Check releases(tags) for different features added.

Theophilus Omoregbee

Written by

Dev at Field Intelligence

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade