Tarkeshwar Singh
Tarkeshwar Singh

Reputation: 3

Passport.Js doesn't let me create two different authentication routes

I am trying to use two different basic authentication conditions for two different apis. But the moment I add the second authentication condition in my project, Passport.Js doesn't let me authenticate at all. It keeps saying wrong password. Below is the code: Can anybody suggest what's wrong with it? I am sorry if this is a noob question. I have just begun working with node so the entire framework is new to me.

// Load required packages
var passport = require('passport');
var passport2= require('passport');
var BasicStrategy = require('passport-http').BasicStrategy;
var BasicStrategy2 = require('passport-http').BasicStrategy;
var User = require('../models/useridentity');
var User2 = require('../models/useridentity');


passport.use(new BasicStrategy(
  function(username, password, callback) {
   User.findOne({ username: username }, function (err, user) {
   if (err) { return callback(err); }

  // No user found with that username
  if (!user) { return callback(null, false); }

  // Make sure the password is correct
  user.verifyPassword(password, function(err, isMatch) {
    if (err) { return callback(err); }

    // Password did not match
    if (!isMatch) { return callback(null, false); }

    // Success
    return callback(null, user);
  });
});
}
));

passport2.use(new BasicStrategy2(
 function(user, pass, callback) {
  User2.findOne({ useremail: user }, function (err, user) {
  if (err) { return callback(err); }

  // No user found with that username
  if (!user) { return callback(null, false); }

  // Make sure the password is correct
  user.verifyPassword(pass, function(err, isMatch) {
    if (err) { return callback(err); }

    // Password did not match
    if (!isMatch) { return callback(null, false); }

    // Success
    return callback(null, user);
  });
});
}
));

exports.isAuthenticated = passport.authenticate('basic', { session : false });
exports.isAuthenticated2 = passport2.authenticate('basic',{session:false});

Upvotes: 0

Views: 188

Answers (1)

vesse
vesse

Reputation: 5078

Requiring same modules multiple times makes no sense - due to module caching you are likely receiving the same object. You can name the strategies in use which enables using same strategy with different configuration:

var passport      = require('passport'),
    BasicStrategy = require('passport-http').BasicStrategy;

passport.use('auth1', new BasicStrategy(...));
passport.use('auth2', new BasicStrategy(...));

app.post('/api1', passport.authenticate('auth1'), function(req, res) { ... });
app.post('/api2', passport.authenticate('auth2'), function(req, res) { ... });

Upvotes: 1

Related Questions