如何使用 Passport.js 获取当前会话的用户名?

How do I get current session's username using Passport.js?

如何在我已经可以通过 routes.js 访问的路由 users.js 中使用 Passport 的 {user} 参数?

情况是我需要访问多个新路由文件中的 Passport 参数,因此我不必将用户 routes.js 作为包含我所有应用程序路由的唯一文件。

app.js - 我只隔离感兴趣的部分

const express = require('express')
const session = require('express-session')
const cookieParser = require('cookie-parser')
const bodyParser = require('body-parser')
const passport = require('passport')
const flash = require('connect-flash')

const app = express()

app.use(session({
    secret: 'Whosebug',
    resave: true,
    saveUninitialized: true,
})) 
app.use(passport.initialize())
app.use(passport.session()) 
app.use(flash()) 

const index = require('./routes/index')
const users = require('./routes/users')

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

// I believe that (app, passport) enables the routes.js to have access to {user} parameter
require('./routes/routes.js')(app, passport) 
// load  routes and pass in our app and fully configured passport

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

module.exports = app;

functions.js - 我的全局函数文件

const express = require('express')
const router = express.Router()
const db = require('../db/Conf')

module.exports.isLoggedIn = function isLoggedIn(req, res, next) {
    if (req.isAuthenticated()) return next()
    res.redirect('/notloggedin')
}

module.exports.fdb = function fdb(mypar, callback) {
    // some stuff for querying
}

routes.js - 这里 {user} 参数输出它的值没有问题

const fcs = require('../routes/functions')
module.exports = (app, passport) => {

    app.get('/login', (req, res) => {
        res.render('login.ejs', { message: req.flash('loginMessage') })
    });

    app.post('/login', passport.authenticate('local-login', {
        //login stuff
    });

    app.get('/profile', fcs.isLoggedIn, ({ user }, res) => {
        res.render('profile.ejs', {user})

        // gets the user out of session and pass to template which is OK
        console.log('User is: ', user.username) 
    });
};

users.js -> 我希望能够使用 Passport 的 {user} 参数的路线,我已经可以在 routes.js

const express = require('express')
const router = express.Router()
const db = require('../db/Conf')
const fcs = require('../routes/functions')

router.get('/', fcs.isLoggedIn, function(req, res, {user}) {
    // some mysql querying stuff using my function fcs.fdb

    res.render('users')

    // Undefined -> Trying to get the {user} value through Passport
    console.log(user.username)

})

module.exports = router

基于https://github.com/RosieCode95/node-express-passport-mysql

尝试const router = express.Router({mergeParams: true});。在 express 中,默认情况下您无法访问父级的路由参数。

您只需使用 req.user.username 而不是 user.username 即可访问当前会话的 Passport.js 用户名值。

此外,您的 router.get 函数(users.js 路由文件)中也不需要 {user} 参数。

router.get('/', fcs.isLoggedIn, function(req, res) {

    res.render('users')
    console.log(req.user.username)

})