简体   繁体   中英

Passport.js throwing “undefined is not a function” with LocalStrategy

I am implementing local authentication using Passport.js. I have already implemented Github Oauth, which is fine but for some reason the local strategy is failing with the above error. I cannot find any source of the issue so far. I have read other posts but the usual answer is that you should change the require statement to:

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

However, I have already done this. Any help would be much appreciated. Here are my files as it stands. I have omitted the github strategy code to focus on the problem strategy:

signin.html:

  <div class="signin-bg">
 <!-- <div class="modal fade" id="login-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;"> -->
<div class="modal-dialog">
   <div class="loginmodal-container">
      <h1>Login using Github</h1><br>
      <a href="/auth/github"><i class="icon-github-sign"></i></a>
      <h3>Or Use your Email</h3>
      <form action="/signin" method="post">
        <input type="text" name="username" placeholder="Email">
        <input type="password" name="password" placeholder="Password">
        <input type="submit" name="login" class="login loginmodal-submit" value="Login">
      </form>
      <div class="login-help">
      <a href="/auth/github">Register</a> - <a href="#">Forgot Password</a>
      </div>
  </div>
</div>

routes.js:

var User = require('./models/userModel');
var passport = require('passport');
var authStore = require('./config/authStore');


module.exports = function(app){

app.get('/signin', function(req, res, next){
  res.render('signin', { message: req.flash('signinMessage') });
});
app.post('/signin', passport.authenticate('local', {
 successRedirect: '/storyBoard',
 failureRedirect: '/signin',
 failureFlash: true
}));

app.get('/signup', function(req, res){
 res.render('signup', { message: req.flash('signupMessage') });
});
app.post('/signup', passport.authenticate('local', {
 successRedirect: '/signin',
 failureRedirect: '/signup',
 failureFlash: true
}));


function isLoggedIn(req, res, next) {
 if(req.isAuthenticated()){
 return next();
}

 res.redirect('/#/signin');
}

};

passport.js

var User = require('../models/userModel.js');
var passport = require('passport');
var GithubStrategy = require('passport-github').Strategy;
var LocalStrategy = require('passport-local').Strategy;
var bcrypt = require('bcrypt');

module.exports = function(passport) {

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

  passport.deserializeUser(function(id, done) {

    User.findUserByGithubId(id, function(err, user) {

      user ? done(null, user) : done(err, null);
    });
  });

  passport.use('local', new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true
  },
  function(req, email, password, done){
    process.nextTick(function(){
      User.findLocalUser(req.email, function(err, user){
        if(err)
          return done(err);
        if(!user)
          return done(null, false, req.flash('signinMessage', 'No user found'));
        if(!User.generateHash(password)){
          return done(null, false, req.flash('signinMessage', 'Invalid password'));
        }
        return done(null, user);
      });
    });
  }
  ));

Well, i'm not sure what you are doing wrong exactly since you not paste all your code, but here is a express silly working sample with passport and connect flash, good luck.

var express = require('express');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var flash = require('connect-flash');
// You need session to use connect flash
var session = require('express-session');
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.urlencoded({extended: true}));

app.use( session({
  saveUninitialized : true,
  secret : 'Some Secret' ,
  resave : true,
}));
app.use( passport.initialize());
app.use( passport.session());
app.use(flash());


// Authentication
passport.use(
  new LocalStrategy(
    {},
    function(username, password, done) {

      // Fake user definition, just a sample.
      var user = {name: 'fake', password: 'fake'};

      // Here you can put your async authentication method from db
      if(user.name === username && user.password === password) {
        return done(null, {
          username: username
        });
      }
      else {
        return done(null, false,{});
      }
    })
);

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

passport.deserializeUser( function(user, done) {
  return done(null, user);
});


app.get('/', function(req, res) {

  var htmlToSend = '';

  var error = req.flash('error')[0];

  if(error)
    htmlToSend += '<div style="background-color:red; width:30%;">' + error + '</div>';

  htmlToSend += '<form action="/login" method="post"> \
    <input name="username"/> \
    <input type="password" name="password"/> \
    <button> send \
  </form>';

  res.send(htmlToSend);
});


app.post('/login', passport.authenticate('local', {
  failureRedirect: '/',
  successFlash: 'Welcome!',
  failureFlash: 'User/Password Invalid!'
}),
function(req, res) {
  res.send('Loged In as '+ req.user.username);
});


app.listen(3000, function() {
  console.log('started');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM