Node Authentication using passport.js - Part 2

This is the part two of the passport authentication blog series. if you have missed the part one, please read the Node authentication - part one https://cloudnweb.dev/2019/04/node-authentication-using-passport-js-part-1/

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

complete source code can be found here: https://github.com/ganeshmani/node-travis

To read more about passport : http://www.passportjs.org/docs/

To Read More

Building Nodejs Microservice - A Cl...

This Article explains everything about how to build Nodejs Microservices in clou...

I Accidentally wiped the entire dat...

One of the tragic accident in my job turned out to be good learning for me in re...

List of Docker Container Commands y...

This article covers list of commands that you should know to manage docker conta...