Skip to main content

Node Authentication using passport.js - Part 2

In this article, we will see how to integrate login using passport authentication.

Firstly, add the login template in views folder. create a file login.handlebars in views folder

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="/login" method="POST" class="ui large form">
18 <div class="ui stacked segment">
19 <div class="field">
20 <div class="ui left icon input">
21 <i class="user icon"></i>
22 <input type="text" name="email" placeholder="Enter Email Address"/>
23 </div>
24 </div>
25 <div class="field">
26 <div class="ui left icon input">
27 <i class="lock icon"></i>
28 <input type="password" name="password" placeholder="Enter Password"/>
29 </div>
30 </div>
31 <input type="submit" class="ui fluid large teal submit button" value="Login"> </div>
32 </form>
33 <div class="ui message">
34 New Here?
35 <a href="/signup">Sign Up</a>
36 </div>
37 </div>
38 </div>

After that, we add the login routes in the routes folder. So, add the following code in routes/index.js

1app.get("/login", (req, res) => {
2 res.render("login")
3})
4
5app.post(
6 "/login",
7 passport.authenticate("local-login", {
8 successRedirect: "/",
9 failureRedirect: "/login",
10 failureFlash: true,
11 })
12)

In the above code, passport is a middleware that uses the strategy called local-login in the config/passport.js

Therefore, add the following code in config/passport.js

1passport.use(
2 "local-login",
3 new LocalStrategy(
4 {
5 // by default, local strategy uses username and password, we will override with email
6 usernameField: "email",
7 passwordField: "password",
8 passReqToCallback: true, // allows us to pass back the entire request to the callback
9 },
10 function(req, email, password, done) {
11 // callback with email and password from our form
12
13 // find a user whose email is the same as the forms email
14 // we are checking to see if the user trying to login already exists
15 User.findOne({ email: email }, function(err, user) {
16 // if there are any errors, return the error before anything else
17 if (err) return done(err)
18 console.log("user", user)
19 console.log("password", password)
20 // if no user is found, return the message
21 if (!user)
22 return done(null, false, req.flash("loginMessage", "No user found.")) // req.flash is the way to set flashdata using connect-flash
23
24 // if the user is found but the password is wrong
25 if (!user.validPassword(password))
26 return done(
27 null,
28 false,
29 req.flash("loginMessage", "Oops! Wrong password.")
30 ) // create the loginMessage and save it to session as flashdata
31
32 // all is well, return successful user
33 return done(null, user)
34 })
35 }
36 )
37)

Mainly, it checks whether the email is exists in the database and check the passport. as a result, it will return the success of the login to the route.

In conclusion, we can run the application using 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...