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

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...