我一直在用Passport,Express 4和Jade创建一个应用程序.我想向用户显示一个在登录时更改的导航栏.
但是,我无法访问req.user以查找除了调用isLoggedIn的配置文件页面之外的任何其他页面:
function isLoggedIn(req,res,next) { // if user is authenticated in the session,carry on if (req.isAuthenticated()) return next() // if they aren't redirect them to the home page res.redirect("/login") }
使用任何其他功能在未登录时不重定向用户会导致req.user未定义.我得到这样的用户:
router.get("/profile",isLoggedIn,function(req,res) { res.render("profile",{ title: 'Gebruikersprofiel van ' + req.user.firstname + " " + req.user.lastname,user: req.user // get the user out of session and pass to template }) })
并且没有调用isLoggedIn(这不起作用):
router.get("/",res) { // serve index.html res.render("index",{ title: 'Home',user: req.user,message: req.flash("message") }) })
isLoggedIn在module.exports = function(passport){/ *所有路由* /}之外,其余的(当然)在其中.
该应用程序的设置如下:
var express = require("express"),bodyParser = require("body-parser"),mongodb = require("mongodb"),mongoose = require("mongoose"),uriUtil = require("mongodb-uri"),morgan = require("morgan"),cookieParser = require("cookie-parser"),session = require("express-session"),passport = require("passport"),flash = require("connect-flash"),ip = "okay",port = process.env.PORT || 80 require("./includes/passport")(passport) require("./includes/subject") require("./includes/user") var app = new express() app.disable("x-powered-by") app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })) app.use(morgan("dev")); // log every request to the console app.use(cookieParser()); // read cookies (needed for auth) // required for passport app.use(session({ secret: "yep" })); // 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.set("view engine","jade") app.use(express.static(__dirname + "/views")) /** * CORS support. */ //skipped //Database setup skipped /** * App setup */ // make our db accessible to our router - globals app.use(function(req,next) { req.db = db next() }) var api = require("./routes/api")(passport),web = require("./routes/web")(passport) // /api for api routes and / for web routes app.use("/api",api) app.use("/",web) //Error handling skipped // fire in the hole! app.listen(port,ip,function() { console.log("Listening on port " + port) })
我尝试了各种各样的东西,包括在app.js中添加中间件以将用户添加到res.locals.user,但到目前为止还没有一个对我有用.
我究竟做错了什么?
编辑:我没有看到很多人提到它,但StormPath可能是一个更好的解决方案吗?
编辑2:我现在正在使用Stormpath,但如果有人有任何建议,我仍然会很乐意接受如何解决这个问题的建议.
编辑3:我收到了许多要求查看(de)serializeUser函数的请求.它们如下:
// 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); }); });