本文介绍了Passport.js和Express 4无法访问req.user的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在创建一个带有护照,Express 4和Jade的应用程序。我想向用户显示登录时更改的导航栏。



但是,我无法访问req.user,用于任何其他页面,而不是配置文件页面isLoggedIn:

  function isLoggedIn(req,res,next){
//如果用户在会话中进行身份验证,继续
如果(req.isAuthenticated())
return next()

//如果他们没有将它们重定向到主页
res.redirect (/ login)
}

使用任何其他功能不重定向用户没有登录到req.user中的结果是 undefined 。我得到这样的用户:

  router.get(/ profile,isLoggedIn,function(req,res){
res.render(profile,{
title:'Gebruikersprofiel van'+ req.user.firstname ++ req.user.lastname,
user:req.user // get用户退出会话并传递给模板
})
})

没有调用isLoggedIn(这不工作):

  router.get(/,function(req, res){
// serve index.html
res.render(index,{
title:'Home',
user:req.user,
消息:req.flash(message)
})
})

isLoggedIn 之外module.exports =功能(护照){/ *所有路线* /} ,其余的(当然)在其中。



应用程序的安装如下:

  var express = require(express),
bodyParser = require(body-parser),
mongodb = require(mongodb),
mongoose = require(mongoose),
uriUtil = require(mongodb-uri),
morgan = morgan),
cookieParser = require(cookie-parser),
session = require(express-session),
护照=需要(护照),
flash = require(connect-flash),
ip =okay,
port = process.env.PORT || 80

要求(./包含/护照)(护照)
要求(./ includes / subject)
require(./ includes / user)

var app = new express()
app.disable(x-powered-by)
app.use(bodyParser.json())
应用程序.use(bodyParser.urlencoded({
extended:true
}))

app.use(morgan(dev)); //将每个请求记录到控制台
app.use(cookieParser()); //读取cookie(需要auth)

//护照需要
app.use(session({secret:yep})); // session secret
app.use(passport.initialize());
app.use(passport.session()); //持续登录会话
app.use(flash()); //使用connect-flash存储在会话中的闪存消息


app.set(view engine,jade)
app.use(express.static(__ dirname +/ views))

/ **
* CORS支持。
* /
// skipped

//跳过数据库设置

/ **
*应用设置
* /
//使我们的数据库可以访问我们的路由器 - 全局变量
app.use(function(req,res,next){
req.db = db
next()

$ b var api = require(./ routes / api)(护照),
web = require(./ routes / web)(护照)

// api路由和/或web路由
app.use(/ api,api)
app.use(/,web)

//错误处理跳过

//在洞里发火!
app.listen(port,ip,function(){
console.log(Listening on port+ port)
})
/ pre>

我已经尝试过各种各样的东西,包括在app.js中添加中间件以将用户添加到res.locals.user,但是没有一个为我工作,到目前为止



我做错了什么?



修改:我没有看到很多人提到它,但可能是一个更好的解决方案? p>

编辑2 :我现在正在使用Stormpath,但是如果有人有任何的话,仍然会乐意提出如何解决这个问题的建议。 >

编辑3 :我已经收到了许多请求来查看(de)serializeUser函数。它们如下:

  //用于序列化会话的用户
passport.serializeUser(function(user ,done){
done(null,user._id);
});

//用于反序列化用户
passport.deserializeUser(function(id,done){
User.findById(id,function(err,user){
done(err,user);
});
});


解决方案

我已经解决了这个问题。这是我的链接页面,我的网站,这使它开始一个新的会话从配置文件页面到网站的其余部分。



答案可以是在这里找到:


I've been creating an app with Passport, Express 4 and Jade. I would like to show the user a navbar that changes when they log in.

However, I cannot access req.user for any other page than the profile page, which calls 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")
}

Using any other function to not redirect the user when not logged in results in req.user being undefined. I get the user like this:

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
    })
})

And without the call to isLoggedIn (this doesn't work):

router.get("/", function(req, res) {
    // serve index.html
    res.render("index", {
        title: 'Home',
        user: req.user,
        message: req.flash("message")
    })
})

isLoggedIn is outside module.exports = function(passport) { /* all routes */ }, the rest is (of course) in it.

Setup of the app is as follows:

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, res, 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)
})

I have tried various things, including adding middleware in app.js to add the user to res.locals.user, but none have worked for me, so far.

What am I doing wrong?

Edit: I've not seen many people mention it, but would StormPath maybe be a better solution?

Edit 2: I am using Stormpath for now, but would still happily take suggestion on how to solve this, if anyone has any.

Edit 3: I have gotten a number of requests to see the (de)serializeUser functions. They are as follows:

// 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);
    });
});
解决方案

I have solved the issue. It was in the way I linked the pages of my site, which made it start a new session from the profile page onto the rest of the site.

The answer can be found here:https://stackoverflow.com/a/27314240/1218007

这篇关于Passport.js和Express 4无法访问req.user的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 03:21