Apr 19, 2019· 5 mins to read

Node Authentication using passport.js - Part 2


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

{{#if message}}
  <div class="ui negative message transition hidden">
    <i class="close icon"></i>
    <div class="header">
      {{message}}
    </div>
  </div>
{{/if}}
<div class="ui middle aligned center aligned grid container">
  <div class="column">
    <h2 class="ui teal image header">
      <img src="/images/favicon.png" alt="cloudnweb" class="image" />
      <div class="content">
        Cloudnweb.dev
      </div>
    </h2>
    <form action="/login" method="POST" class="ui large form">
      <div class="ui stacked segment">
        <div class="field">
          <div class="ui left icon input">
            <i class="user icon"></i>
            <input type="text" name="email" placeholder="Enter Email Address" />
          </div>
        </div>
        <div class="field">
          <div class="ui left icon input">
            <i class="lock icon"></i>
            <input
              type="password"
              name="password"
              placeholder="Enter Password"
            />
          </div>
        </div>
        <input
          type="submit"
          class="ui fluid large teal submit button"
          value="Login"
        />
      </div>
    </form>
    <div class="ui message">
      New Here?
      <a href="/signup">Sign Up</a>
    </div>
  </div>
</div>

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

app.get("/login", (req, res) => {
  res.render("login");
});

app.post(
  "/login",
  passport.authenticate("local-login", {
    successRedirect: "/",
    failureRedirect: "/login",
    failureFlash: true,
  })
);

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

passport.use(
  "local-login",
  new LocalStrategy(
    {
      // by default, local strategy uses username and password, we will override with email
      usernameField: "email",
      passwordField: "password",
      passReqToCallback: true, // allows us to pass back the entire request to the callback
    },
    function (req, email, password, done) {
      // callback with email and password from our form

      // find a user whose email is the same as the forms email
      // we are checking to see if the user trying to login already exists
      User.findOne({ email: email }, function (err, user) {
        // if there are any errors, return the error before anything else
        if (err) return done(err);
        console.log("user", user);
        console.log("password", password);
        // if no user is found, return the message
        if (!user)
          return done(null, false, req.flash("loginMessage", "No user found.")); // req.flash is the way to set flashdata using connect-flash

        // if the user is found but the password is wrong
        if (!user.validPassword(password))
          return done(
            null,
            false,
            req.flash("loginMessage", "Oops! Wrong password.")
          ); // create the loginMessage and save it to session as flashdata

        // all is well, return successful user
        return done(null, user);
      });
    }
  )
);

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/

Copyright © Cloudnweb. All rights reserved.