我真的遇到了passport
在我的Node.js应用程序中工作的麻烦。我尝试在app.js
中重新排序我的要求,但我仍然无法让它发挥作用。这是我得到的错误:
Not Found
404
Error: Not Found
at /home/salma/Desktop/my-project/app.js:56:13
at Layer.handle [as handle_request] (/home/salma/Desktop/my-project/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/salma/Desktop/my-project/node_modules/express/lib/router/index.js:312:13)
at /home/salma/Desktop/my-project/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/salma/Desktop/my-project/node_modules/express/lib/router/index.js:330:12)
at next (/home/salma/Desktop/my-project/node_modules/express/lib/router/index.js:271:10)
at /home/salma/Desktop/my-project/node_modules/express/lib/router/index.js:618:15
at next (/home/salma/Desktop/my-project/node_modules/express/lib/router/index.js:256:14)
at next (/home/salma/Desktop/my-project/node_modules/express/lib/router/route.js:121:14)
at complete (/home/salma/Desktop/my-project/node_modules/passport/lib/middleware/authenticate.js:250:13)
at /home/salma/Desktop/my-project/node_modules/passport/lib/middleware/authenticate.js:257:15
at pass (/home/salma/Desktop/my-project/node_modules/passport/lib/authenticator.js:421:14)
at Authenticator.transformAuthInfo (/home/salma/Desktop/my-project/node_modules/passport/lib/authenticator.js:443:5)
at /home/salma/Desktop/my-project/node_modules/passport/lib/middleware/authenticate.js:254:22
at /home/salma/Desktop/my-project/node_modules/passport/lib/http/request.js:60:7
at pass (/home/salma/Desktop/my-project/node_modules/passport/lib/authenticator.js:267:43)
at serialized (/home/salma/Desktop/my-project/node_modules/passport/lib/authenticator.js:276:7)
at /home/salma/Desktop/my-project/config/passport.js:9:9
at pass (/home/salma/Desktop/my-project/node_modules/passport/lib/authenticator.js:284:9)
at Authenticator.serializeUser (/home/salma/Desktop/my-project/node_modules/passport/lib/authenticator.js:289:5)
at IncomingMessage.req.login.req.logIn (/home/salma/Desktop/my-project/node_modules/passport/lib/http/request.js:50:29)
at Strategy.strategy.success (/home/salma/Desktop/my-project/node_modules/passport/lib/middleware/authenticate.js:235:13)
这是我的代码:
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 flash = require('connect-flash');
var passport = require('passport');
var session = require('express-session');
var routes = require('./routes/index');
var userRoutes = require('./routes/user');
var adminRoutes = require('./routes/admin');
var config = require('./config/index.js');
var MongoStore = require('connect-mongo')(session);
var app = express();
mongoose.Promise = global.Promise;
var db = mongoose.connect(config.dbUrl, config.dbOpts);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var store = new MongoStore({
mongooseConnection: db.connection
});
app.use(session({
secret: config.sessionSecret,
store: store,
resave: true,
saveUninitialized: true
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);
app.use('/', routes);
app.use('/', userRoutes);
app.use('/admin', adminRoutes);
// 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');
});
mongoose.connection.on('open', function(){
mongoose.connection.db.listCollections(function(error, names) {
if (error) {
throw new Error(error);
} else {
names.map(function(name) {
console.log('found collection %s', name);
});
}
});
});
mongoose.connection.on('error', function(error){
throw new Error(error);
});
module.exports = app;
这是我的登录路线:
routes/user.js:
var express = require('express');
var User = require('../controllers/user');
var passport = require('passport');
var router = express.Router();
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.post('/login', passport.authenticate('local',
{ successFlash: 'Success!',
failureFlash : 'Login failed' }));
这是我处理passport
身份验证策略的文件:
config/passport.js:
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user').model;
var configAuth = require('./auth');
module.exports = function (passport) {
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
passport.use('local', 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, req.flash('loginMessage', 'This email does not exist.'));
if (!user.validPassword)
return done(null, false, req.flash('loginMessage', 'Oops! The password entered is incorrect.'));
return done(null, user);
});
}));
passport.use(new FacebookStrategy({
clientID: configAuth.facebookAuth.clientID,
clientSecret: configAuth.facebookAuth.clientSecret,
callbackURL: configAuth.facebookAuth.callbackURL,
profileFields: ["emails", "displayName", "name"]
}
}
我在同一个路径文件中尝试了其他路由,以确保app.js
看到路由并且它们正常工作。只有这一个没有。有人能说出我做错了吗?
答案 0 :(得分:3)
问题出在路线选项successFlash
和failureFlash
上。 passport.authenticate()
函数期望不同的选项必须以这种方式使用,否则它们不起作用。因此,当我更换选项以完全匹配文档时:
app.post('/login',
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login',
failureFlash: true })
);
或
passport.authenticate('local', function(err, user, info) {
if (err) return res.status(500).send();
if (!user) return res.status(400).json({error:info.message});
req.logIn(user, function(err) {
if (err) return next(err);
return res.status(200).json(info.message);
});
})(req, res, next);
它奏效了。还有其他方法可以调用该函数,它们在此处的文档中列出: http://passportjs.org/docs/authenticate
答案 1 :(得分:2)
从您收到的错误消息中,我猜您在用户serializing
和deserializing
时遇到了问题。
你正在做的这是一个非常简单的错误。
当用户serializing
时,您正在user.id
undefined
(我猜)这就是为什么deserializing
function
,ID
没有获得user
,并且在user._id
集合中找到它时遇到问题。
应该是user.id
而不是passport.serializeUser(function (user, done) {
done(null, user.id);
});
。改变这一点,你应该好好去。
<强>替换强>
passport.serializeUser(function (user, done) {
done(null, user._id);
});
。通过强>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*) index.php?p=$1 [L,QSA]
希望它有所帮助。