简体   繁体   中英

Passport - Cannot read property 'isAuthenticated'

I am trying to fix the following error:

/home/ubuntu/workspace/src/util/utils.js:2
  if (req.isAuthenticated()) {
          ^

TypeError: Cannot read property 'isAuthenticated' of undefined
    at Object.isLogged (/home/ubuntu/workspace/src/util/utils.js:2:11)
    at Object.<anonymous> (/home/ubuntu/workspace/src/routes/index.js:6:23)

I am using passport the following in my app:

require('dotenv').config()
const express = require('express')
//...
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()

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

app.use((req, res, next) => {
  res.locals.currentUser = req.user
  next()
})

// routes
app.use('/', auth)
app.use('/', index)

app.listen(port, host, () => {
  console.log(`Listening on ${host}:${port}`)
})

module.exports = app

My passport.js file looks like the following:

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

module.exports = () => {
passport-serialize-deserialize
  passport.serializeUser((user, done) => {
    done(null, user.id)
  })

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

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

When my / gets called I am using the isLogged() function to control if a login is required:

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

The definition of the function can be found in my utils.js file, where the error log above is pointing:

function isLogged(req, res, next) {
  if (req.isAuthenticated()) {
    next()
  } else {
    res.redirect('/')
  }
}

module.exports = {
  isLogged,
}

The full code flow can be found in the following repo: passport example

Any suggestions what I am doing wrong?`

I appreciate your replies!

When you run this code:

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

What happens is that utils.isLogged() is being executed, the the result of this execution is registered as a middleware.
Since you try to execute it without any parameters passed, res is passed as undefined and you get your error.

Now, what you really want to do is pass the function itself, not it's execution, so when express will call it (during request processing), it will pass the parameters to it. So your code should look like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM