Skip to main content

Node Authentication using passport.js - Part 1

What is Passport?

passport is an authentication middleware for node application. passport provides different set of strategies using a username and password, Facebook and Twitter.

The article is separated as two parts for better understanding of the passport authentication concepts

we can use different ways to login in a web application such as Facebook,Twitter, Google and local(username and password)

In this article, we will use local strategy for the web application and folder structure will looks like:

Project Structure :

Screen Shot 2019 04 19 at 12 25 37 PM

Firstly, we are going to install all the dependencies needed for an application. Therefore, we install the packages needed for an application

1"dependencies": {
2 "bcrypt-nodejs": "0.0.3",
3 "body-parser": "^1.18.3",
4 "connect-flash": "^0.1.1",
5 "cookie-parser": "^1.4.4",
6 "cors": "^2.8.5",
7 "express": "^4.16.4",
8 "express-handlebars": "^3.0.2",
9 "express-session": "^1.16.1",
10 "method-override": "^3.0.0",
11 "mongoose": "^5.5.2",
12 "morgan": "^1.9.1",
13 "passport": "^0.4.0",
14 "passport-local": "^1.0.0"
15 },

Most importantly, passport and passport-local are the packages are used for passport authentication.

on the other hand, we need to create models which is nothing but Schema for user. create a file called user.schema.js

1const mongoose = require("mongoose")
2const bcrypt = require("bcrypt-nodejs")
3const Schema = mongoose.Schema
4
5let userschema = new Schema({
6 email: String,
7 password: String,
8})
9
10userschema.methods.generateHash = function(password) {
11 return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null)
12}
13
14// checking if password is valid
15userschema.methods.validPassword = function(password) {
16 return bcrypt.compareSync(password, this.password)
17}
18
19let User = mongoose.model("User", userschema)
20
21module.exports = User

we need to create a file called passportwhere we need to setup the passport strategy. that is to say, create a file called config/passport.js .

Firstly, we will see how to setup the signup using passport authentication.Therefore, add the following code in the config/passport.js

1const LocalStrategy = require("passport-local").Strategy
2
3let User = require("../models/user.schema")
4
5module.exports = function(passport) {
6 // used to serialize the user for the session
7 passport.serializeUser(function(user, done) {
8 done(null, user.id)
9 })
10
11 // used to deserialize the user
12 passport.deserializeUser(function(id, done) {
13 User.findById(id, function(err, user) {
14 done(err, user)
15 })
16 })
17
18 passport.use(
19 "local-signup",
20 new LocalStrategy(
21 {
22 // by default, local strategy uses username and password, we will override with email
23 usernameField: "email",
24 passwordField: "password",
25 passReqToCallback: true, // allows us to pass back the entire request to the callback
26 },
27 function(req, email, password, done) {
28 // asynchronous
29 // User.findOne wont fire unless data is sent back
30 process.nextTick(function() {
31 // find a user whose email is the same as the forms email
32 // we are checking to see if the user trying to login already exists
33 User.findOne({ email: email }, function(err, user) {
34 // if there are any errors, return the error
35 if (err) return done(err)
36
37 // check to see if theres already a user with that email
38 if (user) {
39 return done(
40 null,
41 false,
42 req.flash("signupMessage", "That email is already taken.")
43 )
44 } else {
45 // if there is no user with that email
46 // create the user
47 var newUser = new User()
48
49 // set the user's local credentials
50
51 newUser.email = email
52 newUser.password = newUser.generateHash(password)
53
54 // save the user
55 newUser.save(function(err) {
56 if (err) throw err
57 return done(null, newUser)
58 })
59 }
60 })
61 })
62 }
63 )
64 )
65}

In the above file, we setup the passport local strategy for signup and insert the user into the database.

After that, we need to create a route file where we need to handle the signup url.So,create a file called routes/index.js

1module.exports = function(app, passport) {
2 app.get("/", isLoggedIn, (req, res) => {
3 console.log("req user", req.user)
4 res.render("home", {
5 user: req.user,
6 })
7 })
8
9 app.get("/signup", (req, res) => {
10 res.render("signup")
11 })
12
13 app.post(
14 "/signup",
15 passport.authenticate("local-signup", {
16 successRedirect: "/", // redirect to the secure profile section
17 failureRedirect: "/signup", // redirect back to the signup page if there is an error
18 failureFlash: true, // allow flash messages
19 })
20 )
21
22 app.get("/logout", function(req, res) {
23 req.logout()
24 res.redirect("/")
25 })
26
27 // route middleware to make sure a user is logged in
28 function isLoggedIn(req, res, next) {
29 // if user is authenticated in the session, carry on
30 if (req.isAuthenticated()) return next()
31
32 // if they aren't redirect them to the home page
33 res.redirect("/login")
34 }
35}

So far, we added the route for signup and after successful signup, we redirect them to home page. So, we need to create view files for signup and home page.

create a folder called views and add the the following files

1- views
2 - layouts
3 ------ main.handlebars <!-- show our home page with
4 ------ home.handlebars <!-- show our home -->
5 ------ login.handlebars <!-- show our login form -->

that is to say, main.hanldebars should looks like

1<!DOCTYPE html>
2<html>
3 <head>
4 <meta charset="utf-8" />
5 <title>Worker App</title>
6 <link rel="icon" href="/images/favicon.png" />
7 <link
8 rel="stylesheet"
9 href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css"
10 />
11 </head>
12 <body>
13 {{{body}}}
14 </body>
15</html>

signup.handlebars should looks like

1{{#if message }}
2 <div class="ui negative message transition hidden">
3 <i class="close icon"></i>
4 <div class="header">
5 {{message}}
6 </div>
7 </div>
8 {{/if}}
9 <div class="ui middle aligned center aligned grid container">
10 <div class="column">
11 <h2 class="ui teal image header">
12 <img src="/images/favicon.png" class="image"/>
13 <div class="content">
14 Cloudnweb.dev
15 </div>
16 </h2>
17 <form action="/signup" method="POST" class="ui large form">
18 <div class="ui stacked segment">
19
20
21 <div class="field">
22 <div class="ui left icon input">
23 <i class="user icon"></i>
24 <input type="text" name="email" placeholder="Enter Email Address"/>
25 </div>
26 </div>
27 <div class="field">
28 <div class="ui left icon input">
29 <i class="lock icon"></i>
30 <input type="password" name="password" placeholder="Enter Password"/>
31 </div>
32 </div>
33 <input type="submit" class="ui fluid large teal submit button" value="Sign Up"> </div>
34 </form>
35
36 </div>
37 </div>

home.handlebars should look like

1<div class="ui small menu">
2 <a class="active item">
3 Home
4 </a>
5 <div class="right menu">
6 <div class="item">
7 <h4>{{user.email}}</h4>
8 </div>
9 <div class="item">
10 <a href="/logout" class="ui primary button">Log Out</a>
11 </div>
12 </div>
13</div>

Finally, add the following code in the app.js

1const express = require("express")
2const exphbs = require("express-handlebars")
3const mongoose = require("mongoose")
4const app = express()
5const passport = require("passport")
6const flash = require("connect-flash")
7const morgan = require("morgan")
8const cookieParser = require("cookie-parser")
9const bodyParser = require("body-parser")
10const session = require("express-session")
11
12require("dotenv").config()
13
14app.engine("handlebars", exphbs({ defaultLayout: "main" }))
15app.set("view engine", "handlebars")
16
17app.use(morgan("dev"))
18app.use(cookieParser())
19app.use(bodyParser.urlencoded({ extended: true }))
20app.use(bodyParser.json())
21
22const MONGODB_URI = process.env.MONGODB_URL
23
24mongoose.connect(MONGODB_URI, { useNewUrlParser: true })
25
26var db = mongoose.connection
27db.on("error", console.error.bind(console, "connection error:"))
28db.once("open", function() {
29 console.log("connected")
30})
31
32app.use(session({ secret: "ilearnnodejs" }))
33app.use(passport.initialize())
34app.use(passport.session())
35app.use(flash())
36
37require("./config/passport")(passport)
38require("./routes/index")(app, passport)
39
40const PORT = process.env.PORT
41
42app.listen(PORT, () => {
43 console.log(`app is listening to port ${PORT}`)
44})

Now, we can run the application in command as node app.js

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...