Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display passport.js authentication error message in view

I have a new Sails.js project using Passport.js to authenticate users. I have the basic authentication working (meaning a user can sign up and successfully log in), but would like to display the appropriate error message in the login view if they don't enter the correct credentials. I can't figure out how to print any error messages in the view.

Here's my setup. I have config/passport.js, which contains the following:

var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
bcrypt = require('bcrypt');

passport.serializeUser(function(user, done) {
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    User.findOne({ id: id } , function (err, user) {
        done(err, user);
    });
});

passport.use(new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback : true
},
function(req, email, password, done) {

    User.findOne({ email: email }, function (err, user) {
      if (err) { return done(err); }
      if (!user) {
         return done(null, false, { message: 'Please enter a valid email address.' });
      }

      if (!req.body.username) {
        return done(null, false, { message: 'Please enter your username.' });
      }

      bcrypt.compare(password, user.password, function (err, res) {
          if (!res) {
            return done(null, false, {
              message: 'Invalid Password'
            });
          }

          var returnUser = {
            username: user.username,
            email: user.email,
            createdAt: user.createdAt,
            id: user.id
          };

          return done(null, returnUser, {
            message: 'Logged In Successfully'
          });

        });
    });
    }
    ));

Then I have api/controllers/AuthController.js, which contains the following:

var passport = require('passport');

  module.exports = {

   _config: {
     actions: false,
     shortcuts: false,
     rest: false
   },

   login: passport.authenticate('local', { successRedirect: '/',
                            failureRedirect: '/login',
                            failureFlash: true
   }),

   logout: function(req, res) {
     req.logout();
     res.redirect('/login');
   }
 };

Again, this is working properly if the user fills in their correct credentials. I'm using Handlebars as my templating engine, and would like to display the error message in the login view like so:

<div class="alert">{{ message }}</div>

So far I've tried {{ failureMessage }} {{ message }} {{ req.flash.failureMessage }} {{ req.flash.err }} {{ req.flash.message }} to no avail. So all this to say, how do I display the appropriate error message in my view? And better yet, how would I highlight the errant field in my view?

like image 407
Brad Frost Avatar asked Sep 22 '15 00:09

Brad Frost


People also ask

What does Passport authenticate () do?

In this route, passport. authenticate() is middleware which will authenticate the request. By default, when authentication succeeds, the req. user property is set to the authenticated user, a login session is established, and the next function in the stack is called.

How does Passport js handle authorization?

Authorization is performed by calling passport. authorize() . If authorization is granted, the result provided by the strategy's verify callback will be assigned to req.account . The existing login session and req.

Should I use Passport js for authentication?

Passport is a popular, modular authentication middleware for Node. js applications. With it, authentication can be easily integrated into any Node- and Express-based app. The Passport library provides more than 500 authentication mechanisms, including OAuth, JWT, and simple username and password based authentication.


1 Answers

At first glance, looks like sails is using Express 3.0. Per the Passport docs (http://passportjs.org/docs), you will need to explicitly add middleware to support flash (they recommend https://github.com/jaredhanson/connect-flash).

like image 85
Joe P Avatar answered Sep 25 '22 11:09

Joe P