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

时间:2017-12-10 10:23:26

标签: javascript node.js routes passport.js passport-local

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

案例是我需要在多个新路由文件中访问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: 'stackoverflow',
    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

2 个答案:

答案 0 :(得分:1)

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

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

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

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

})

答案 1 :(得分:0)

试试int a = 5; int test[] = {1,2,3,4}; int b = 5; test[-1] = 11; test[4] = 11; cout << b << endl; // 11 cout << a << endl; // 5 。在Express中,默认情况下无法访问父级的路径参数。