简体   繁体   中英

'TypeError: Cannot read property 'isAuthenticated' of undefined' after requiring passport.js

I want to check that a user is authenticated before they can access the route user/profile . For this I used isAuthenticated() from passport.

But when I ran npm start the terminal responded with TypeError: Cannot read property 'isAuthenticated' of undefined . What's the problem here?

My user route users.js :

var express = require('express');
var router = express.Router();
var csrf = require("csurf");
var passport = require("passport");

const {check, validationResult} = require('express-validator');

var csrfProtection = csrf();
router.use(csrfProtection);

// User Signup
router.get("/signup", (req, res, next) => {
    var messages = req.flash("error");
    res.render("user/signup", {csrfToken: req.csrfToken(), messages: messages, hasErrors: messages.length > 0});
  });

  router.post("/signup",
  [
    check('email', 'Your email is not valid').not().isEmpty().isEmail().normalizeEmail(),
    check('password', 'Your password must be at least 5 characters').not().isEmpty().isLength({min: 5})
  ],
  function (req, res) {
    const errors = validationResult(req);
    console.log(req.body);

    if (!errors.isEmpty()) {
      return res.status(422).jsonp(errors.array())
    } else {
      passport.authenticate("local.signup", {
        successRedirect: "/user/profile",
        failureRedirect: "/user/signup",
        failureFlash: true
      })(req, res);
    }
  });

  // User signin
  router.get("/signin", (req, res, next) => {
    var messages = req.flash("error");
    res.render("user/signin", {csrfToken: req.csrfToken(), messages: messages, hasErrors: messages.length > 0});
  });

  router.post("/signin",
  [
    check('email', 'Your email is not valid').not().isEmpty().isEmail().normalizeEmail(),
    check('password', 'Your password must be at least 5 characters').not().isEmpty()
  ],
  function (req, res) {
    const errors = validationResult(req);
    console.log(req.body);

    if (!errors.isEmpty()) {
      return res.status(422).jsonp(errors.array())
    } else {
      passport.authenticate("local.signin", {
        successRedirect: "/user/profile",
        failureRedirect: "/user/signin",
        failureFlash: true
      })(req, res);
    }
  });

function isLoggedIn(req, res, next) {
    if (req.isAuthenticated()) {
    return next();
  }
    res.redirect("/");
}

// User profile
router.get("/profile", isLoggedIn(), (req, res, next) => {
    res.render("user/profile");
});

router.get("/logout", function(req, res, next) {
    req.logout();
    res.redirect("/");
});

  module.exports = router;

Error message:

/mnt/e/CODING/Templates/leaftunehoney/SC2/routes/users.js:64
    if (req.isAuthenticated()) {
            ^

TypeError: Cannot read property 'isAuthenticated' of undefined
    at isLoggedIn (/mnt/e/CODING/Templates/leaftunehoney/SC2/routes/users.js:64:13)
    at Object.<anonymous> (/mnt/e/CODING/Templates/leaftunehoney/SC2/routes/users.js:71:24)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/mnt/e/CODING/Templates/leaftunehoney/SC2/app.js:15:18)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)

isLoggedIn is a function. From where do the req,res are coming in function definition?

It is a function call, that is why inside the function, req is undefined because no parameter is being passed to the function and therefore the line where you used : if (req.isAuthenticated())

the error is coming : Cannot read property 'isAuthenticated' of undefined.

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