我是NodeJS的新手,我尝试构建一个登录/注册系统.注册工作正常,但我目前无法登录.
我找到了一个使用passport和nodejs的示例应用程序,因此基于此示例,我构建了注册表单和登录表单. http://blog.robertonodi.me/node-authentication-series-email-and-password/
当我尝试登录时,我得到了一个'Unknown authentication strategy "local" error'
.谁能解释我做错了什么?
(编辑:从答案/评论和文件名中添加了一些更改)
app.use(session({ store: new MongoStore({ url: 'mongodb://' + config.url + ':' + config.port + '/' + config.name }), secret: 'secretkey', key: 'skey.sid', resave: false, saveUninitialized: false, cookie : { maxAge: 604800000 //7 days in miliseconds } })); app.use(passport.initialize()); app.use(passport.session()); require(path.join(__dirname, 'auth.config'))(passport); //Load passport config app.use(function(req, res, next) { req.resources = req.resources || {}; // res.locals.app = config.app; res.locals.currentUser = req.user; res.locals._t = function (value) { return value; }; res.locals._s = function (obj) { return JSON.stringify(obj); }; next(); })
var path = require('path'); var passport=require('passport'); var User = require(path.join(__dirname, '..', 'models', 'user.model')); module.exports = function(passport) { passport.serializeUser(function(user, done){ done(null, false); }); passport.deserializeUser(function(id, done){ console.log("deserializeUser called", id); User.findById(id, function (err, user) { done(err, user); }); }); //load strategy files require(path.join(__dirname, 'strategies', 'local-strategy')); //TODO: Facebook //TODO: Twitter //TODO: Google }
var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var mongoose = require('mongoose'); var User = mongoose.model('User'); module.exports = function () { console.log("LocalStrategy called"); passport.use(new LocalStrategy({ usernameField : 'username', passwordField : 'password' }, function(username, password, done) { User.authenticate(username, password, function(err, user) { if (err) { return done(err); } if(!user) { return done(null, false, {message: 'Invalid username or password'}); } return done(null, user); }) })) }
module.exports.loginUser = function(req,res, next) { console.log("Auth.config", path.join(__dirname, 'strategies', 'local-strategy')) passport.authenticate('local', function (err, user, info) { if (err || !user) { console.log("Error", info); return res.status(400).send(info); } req.logIn(user, function(err) { if (err) { return next(err); // return res.status(404).send("Username or password incorrect"); } }) res.status(200).json(user); })(req, res, next); }
Ravi Shankar.. 23
你忘了在你的导入中导入护照配置文件app.js
.
import
passport config
初始化后passport
.
app.use(passport.initialize()); app.use(passport.session()); // Add the line below, which you're missing: require('./path/to/passport/config/file')(passport);
希望这可以帮助.
你忘了在你的导入中导入护照配置文件app.js
.
import
passport config
初始化后passport
.
app.use(passport.initialize()); app.use(passport.session()); // Add the line below, which you're missing: require('./path/to/passport/config/file')(passport);
希望这可以帮助.