Login and SignUp API’s

Adhikansh Mittal
Code To Express
Published in
6 min readJun 19, 2019

In this blog, I’ll explain the continuation of the series “Learning Backend Development through Node Js and Express Js”. Lets start with the Integration of Database with the APIs. So for this purpose, we can make a SignUp and Login API with NoSql Database, which is nothing but MongoDB.

So let's start step by step:-

First, let's start by npm init and fill all the required information there. After that install all the required dependencies.

npm init // fill required fields
npm install express
npm install mongoose

Now lets start →

  1. Make a server listening on Port 3000(or any it’s all your choice)
// index.jsvar express = require('express')
var app = express();
var port = process.env.PORT || 3000;
app.get('/',(req,res)=>{
res.status(200).send(`Hi Welcome to the Login and Signup API`);
});
app.listen(port,()=>{
console.log(`Server is listening on port ${port}`)
});

2. Now we have to make a mongoose Model in which we define our parameters that we are going to take from the User for SignUp. For this purpose, make a directory named models and make a file User.js

// models/User.jsvar mongoose = require('mongoose');
const UserSchema = mongoose.Schema({
name:{
type:String,
require:true
},
password:{
type:String,
require:true
}
});
module.exports = User = mongoose.model('UserSchema',UserSchema);

3. Lets import this User Schema into our main file i.e. index.js

// index.jsvar express = require('express')
var app = express();
var port = process.env.PORT || 3000;
var User = require('/models/User');
app.get('/',(req,res)=>{
res.status(200).send(`Hi Welcome to the Login and Signup API`);
});
app.listen(port,()=>{
console.log(`Server is listening on port ${port}`)
});

4. After which, we have to connect to a Database. So for making a database setup, we create a new directory (mysetup). This is because if you want to change your database, you can do it very easily. For now, I’ll only take local database (MongoDB). You can install MongoDB in your system from the official website https://www.mongodb.com/download-center/community

// mysetup/myurl.jsmodule.exports = {
myurl: 'mongodb://localhost:27017/Users',
secret: 'mysecretkey' //going to be used later on for key token
}

Here I’ve made a database called User and exported this file.

5. Now we have to import this URL and make the connection to the Database.

6. Lets now make a Signup route for the user i.e. ‘/signup’ for which we’ll take inputs from the user.

I’ll now explain everything that we did in the ‘/signup’ route. Firstly, this route is POST route as we can see we call post method by app.post. After that we make an object newUser from the model of User. We import his from user schema existing in model/User.js. After that, we save it into the database by .save() method and for Error handling, we use then and catch block. If there is any error then it would display in the catch block and if everything is fine, it would return back that object to use. All of this would come under callback function having request and response as parameters and in Node.js we’d do the asynchronous flow of process through a pipeline. This explains why we use await and async keywords.

7. Now, to log in we make a POST route on ‘/login’

Here, we first take input from the user and store it into an object then we search it into the database. The database would return a response which we store in the profile and check whether it exists or not. If it exists, it would return that User document from the database. Now let's check the password on the basis of which we can verify whether the user is authenticated or unauthenticated.

8. A fault occurs in the signup route when someone registers with the same name twice. So it will store it twice and we don’t take anything unique in the database. Generally, we consider email id but as for now, we take the name as unique. So go back into ‘/signup’ route add a new condition.

9. Now everything works fine and let's test our APIs. For this purpose, we have to install a software postman. This would help us with testing.

Signup route

Be careful while selecting the method to be sure it is POST. Select body and x-www-form-urlencoded. Then give a key-value pair.

login route

10. Now if we check in our database, we can see that the password we store is not encrypted. We need to encrypt our password and for that, we need to install an npm package bcrypt. You can read it’s documentation from official website https://www.npmjs.com/package/bcrypt.

npm install bcrypt

You’d require

var bcrypt = require('bcrypt')
var saltRouds = 10
signup route
login route

Now everything is up and running. The password is encrypted while it's saved in the database.

Now when we login, we get authenticated and we can render to the home screen but there is a session created for us that is done at the time of login. It would create a token which we can pass to the other pages so that it can authenticate us. This is also known as a private access route.

12. For this, we are going to use the npm packages which are jsonwebtoken, passport and passport-jwt. Firstly, let's make a directory strategies a file jsonwtStrategy.js which will have all our Strategies.

Now we are required to configure as per the documentation of dependencies.

// index.js//Passport middleware
app.use(passport.initialize());
//Config for JWT strategy
require("./strategies/jsonwtStrategy")(passport);

In variable payload, everything that we want to pass to another page loads. key.secret can be anything, you just require a string. We can also set the time up to which that token can be active.

Now let's see how to use this token which was generated at the time of login.

We want a route which is private and can be accessed after the user is login into the system. So we add the middleware passport into that route to authenticate as shown below.

Let's test the first login with the help of postman

Now copy this token and pass into the route of login as shown below

Now, the final step is to make the project understandable for others and for ourselves too.

12. So for that, we take all the routes into a new directory route and make a file User.js. We export it from there to the index.js file.

var expres = require('express');
var route = express.Router();
route.post('/signup',(req,res)=>{

....
.... // same code
....

});
module.exports = route;

Finally, we did it.

( If you want to download this Project. Please refer to this link https://github.com/HrithikMittal/SignUp-and-Login-API )

--

--