2017-03-17 73 views
0

我在護照創建認證系統的NodeJS以下this教程護照未知的身份驗證策略

目前,我試圖使註冊表格的工作,但它給這個錯誤:

Error: Unknown authentication strategy "local-signup" 
    at attempt (/home/jarno/0__projects/nodejs/EasyOrders_2.3.0/node_modules/passport/lib/middleware/authenticate.js:173:37) 
    at authenticate (/home/jarno/0__projects/nodejs/EasyOrders_2.3.0/node_modules/passport/lib/middleware/authenticate.js:349:7) 
    at Layer.handle [as handle_request] (/home/jarno/0__projects/nodejs/EasyOrders_2.3.0/node_modules/express/lib/router/layer.js:95:5) 
    at next (/home/jarno/0__projects/nodejs/EasyOrders_2.3.0/node_modules... 

我非常確定config/passport.js文件不是由routes/users.js文件看到的,但是因爲我是初學者,所以似乎無法找到解決我的問題的方法。

/routes/users.js

var express = require('express'); 
var router = express.Router(); 
var passport = require('passport'); 
require('../config/passport'); 


/* GET users listing. */ 
router.get('/login', function(req, res){ 
    res.render('login', { 
    title: 'Login' 
    }); 
}); 

router.get('/signup', function(req, res){ 
    res.render('signup', { 
    title: 'signup' 
    }); 
}); 

router.get('/logout', function(req, res){ 
    res.logout(); 
    res.redirect('/users/login') 
}); 

/* POST users listing */ 
router.post('/signup', passport.authenticate('local-signup', { 
    successRedirect : '/profile', // redirect to the secure profile section 
    failureRedirect : '/signup', // redirect back to the signup page if there is an error 
    failureFlash : true // allow flash messages 
})); 


/* functions */ 
function isLoggedIn(req, res, next) { 

    if (req.isAuthenticated()) 
    return next(); 

    res.redirect('/users/login'); 
} 



module.exports = router; 

/config/passport.js

// config/passport.js 
var passport = require('passport'); 
// load all the things we need 
var LocalStrategy = require('passport-local').Strategy; 

// load up the user model 
var User   = require('../models/user'); 

// expose this function to our app using module.exports 
module.exports = function(passport) { 

    // ========================================================================= 
    // passport session setup ================================================== 
    // ========================================================================= 
    // required for persistent login sessions 
    // passport needs ability to serialize and unserialize users out of session 

    // used to serialize the user for the session 
    passport.serializeUser(function(user, done) { 
     done(null, user.id); 
    }); 

    // used to deserialize the user 
    passport.deserializeUser(function(id, done) { 
     User.findById(id, function(err, user) { 
      done(err, user); 
     }); 
    }); 

    // ========================================================================= 
    // LOCAL SIGNUP ============================================================ 
    // ========================================================================= 
    // we are using named strategies since we have one for login and one for signup 
    // by default, if there was no name, it would just be called 'local' 

    passport.use('local-signup', 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) { 

      // asynchronous 
      // User.findOne wont fire unless data is sent back 
      process.nextTick(function() { 

      // 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({ 'local.email' : email }, function(err, user) { 
       // if there are any errors, return the error 
       if (err) 
        return done(err); 

       // check to see if theres already a user with that email 
       if (user) { 
        return done(null, false, req.flash('signupMessage', 'That email is already taken.')); 
       } else { 

        // if there is no user with that email 
        // create the user 
        var newUser   = new User(); 

        // set the user's local credentials 
        newUser.local.email = email; 
        newUser.local.password = newUser.generateHash(password); 

        // save the user 
        newUser.save(function(err) { 
         if (err) 
          throw err; 
         return done(null, newUser); 
        }); 
       } 

      }); 

      }); 

     })); 

}; 

/app.js

var express = require('express'); 
var path = require('path'); 
var favicon = require('serve-favicon'); 
var logger = require('morgan'); 
var cookieParser = require('cookie-parser'); 
var bodyParser = require('body-parser'); 



var mongoose = require('mongoose'); 
var passport = require('passport'); 
var flash = require('connect-flash'); 
var morgan = require('morgan'); 
var session = require('express-session'); 

var configDB = require('./config/database.js'); 

mongoose.connect(configDB.url); 
require('./config/passport'); 

// init app 
var app = express(); 
var index = require('./routes/index'); 
var users = require('./routes/users'); 

// view engine setup 
app.set('views', path.join(__dirname, 'views')); 
app.set('view engine', 'jade'); 

// uncomment after placing your favicon in /public 
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); 
app.use(logger('dev')); 
app.use(morgan('dev')); 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: false })); 
app.use(cookieParser()); 
app.use(require('stylus').middleware(path.join(__dirname, 'public'))); 
app.use(express.static(path.join(__dirname, 'public'))); 


app.use(session({ secret: 'godaddy420' })); // session secret 
app.use(passport.initialize()); 
app.use(passport.session()); // persistent login sessions 
app.use(flash()); // use connect-flash for flash messages stored in session 


app.use(function (req, res, next) { 
    res.locals.path = req.path; 
    next(); 
}); 




app.use('/', index); 
app.use('/users', users); 

// catch 404 and forward to error handler 
app.use(function(req, res, next) { 
    var err = new Error('Not Found'); 
    err.status = 404; 
    next(err); 
}); 

// error handler 
app.use(function(err, req, res, next) { 
    // set locals, only providing error in development 
    res.locals.message = err.message; 
    res.locals.error = req.app.get('env') === 'development' ? err : {}; 

    // render the error page 
    res.status(err.status || 500); 
    res.render('error'); 
}); 

module.exports = app; 

回答

1

config/password.js導出一個函數,但你永遠不會調用這個函數。在app.js,你應該有這樣的事情:

require('./config/passport')(passport); 
1

)你^ h ave在app.use()方法之後用passport設置路由並將passport作爲參數發送。所以:

var express = require('express'); 
var path = require('path'); 
var favicon = require('serve-favicon'); 
var logger = require('morgan'); 
var cookieParser = require('cookie-parser'); 
var bodyParser = require('body-parser'); 

var mongoose = require('mongoose'); 
var passport = require('passport'); 
var flash = require('connect-flash'); 
var morgan = require('morgan'); 
var session = require('express-session'); 

var configDB = require('./config/database.js'); 

mongoose.connect(configDB.url); 
require('./config/passport'); 

// init app 
var app = express(); 

// view engine setup 
app.set('views', path.join(__dirname, 'views')); 
app.set('view engine', 'jade'); 

// uncomment after placing your favicon in /public 
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); 
app.use(logger('dev')); 
app.use(morgan('dev')); 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: false })); 
app.use(cookieParser()); 
app.use(require('stylus').middleware(path.join(__dirname, 'public'))); 
app.use(express.static(path.join(__dirname, 'public'))); 


app.use(session({ secret: 'godaddy420' })); // session secret 
app.use(passport.initialize()); 
app.use(passport.session()); // persistent login sessions 
app.use(flash()); // use connect-flash for flash messages stored in session 


app.use(function (req, res, next) { 
    res.locals.path = req.path; 
    next(); 
}); 
// require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport 

var index = require('./routes/index')(app, passport); 
var users = require('./routes/users')(app, passport); 

app.use('/', index); 
app.use('/users', users); 

// catch 404 and forward to error handler 
app.use(function(req, res, next) { 
    var err = new Error('Not Found'); 
    err.status = 404; 
    next(err); 
}); 

// error handler 
app.use(function(err, req, res, next) { 
    // set locals, only providing error in development 
    res.locals.message = err.message; 
    res.locals.error = req.app.get('env') === 'development' ? err : {}; 

    // render the error page 
    res.status(err.status || 500); 
    res.render('error'); 
}); 

module.exports = app; 

「索引」和「用戶」內部使用您發送的護照作爲參數。