2017-11-11 125 views
0

正確isAuthenticated我想在我的快遞應用程序使用passportpassport-local加載文件

在我的主要應用程序,我加載了以下內容:

const session = require('express-session') 
const passport = require('passport') 
// configure passport 
// require('./config/passport')(passport) 
const auth = require('./routes/auth') 
const index = require('./routes/index') 

const app = express() 

// view engine setup 
app.set('views', path.join(__dirname, 'views')) 
app.set('view engine', 'pug') 
app.use(logger(process.env.LOG_ENV)) 
app.use(bodyParser.json()) 
app.use(bodyParser.urlencoded({ 
    extended: false, 
})) 
app.use(express.static(path.join(__dirname, '/../public'))) 
app.use(cookieParser()) 

app.use(session({ 
    secret: 'super-mega-hyper-secret', 
    resave: false, 
    saveUninitialized: true, 
})) 
app.use(passport.initialize()) 
app.use(passport.session()) 

passport.js配置文件看起來相當典型:

const passport = require('passport') 
const LocalStrategy = require('passport-local').Strategy 
const serviceAuth = require('../service/auth') 

    passport.serializeUser((user, done) => { 
    done(null, user.id) 
    }) 

    passport.deserializeUser(async (id, done) => { 
    const user = await serviceAuth.findById(id) 
    done(null, user) 
    }) 

    passport.use('local', new LocalStrategy({ 
    usernameField: 'username', 
    }, async(username, password, done) => { 
    const user = await serviceAuth.signin(username, password) 
    done(null, user) 
    })) 

在我的路線,我想避開哪些路線需要身份驗證:

const express = require('express') 

const router = express.Router() 
const utils = require('../util/utils') 

router.get('/', utils.isLogged(), (req, res) => { 
    res.render('dashboard') 
}) 

module.exports = router 

utils/utils.js文件夾我有中間件來引導,哪個用戶通過身份驗證。

const passportConfig = require('../config/passport') 

function isLogged(req, res, next) { 
    const auth = this.passportConfig.isAuthenticated() 
    if (req.auth) { 
    next() 
    } else { 
    res.redirect('/') 
    } 
} 

module.exports = { 
    isLogged, 
} 

不過,在這裏我得到以下錯誤:

const auth = this.passportConfig.isAuthenticated() 
           ^

TypeError: Cannot read property 'isAuthenticated' of undefined 

任何建議如何正確加載護照我utils/utils.js文件夾?

我很感謝你的回覆!

更新

請查找以下github repo,這表明最小的可行例子。

回答

0

在你isLogged()功能,this關鍵字指function本身,因此this.passportConfigundefined。你應該做的只是使用:

const auth = passportConfig.isAuthenticated(); 

沒有this關鍵字。