How to know if user is logged in with passport.js?

后端 未结 6 1028
日久生厌
日久生厌 2020-12-02 05:01

I\'ve been reading passport.js info and samples for two days, but I\'m not sure after that I did all the process of authenticating.

How do I know if I\

6条回答
  •  心在旅途
    2020-12-02 05:23

    It is not explicitly documented but there is a isAuthenticated() method which is inserted into req by passport.
    Can be used as follows,

    req.isAuthenticated() // returns true if auth, false if not
    

    // auth.js
    module.exports = {
      ensureAuthenticated: (req, res, next) => {
        if (req.isAuthenticated()) {
          return next()
        }
        res.redirect('/login') // if not auth
      },
    
      forwardAuthenticated: (req, res, next) => {
        if (!req.isAuthenticated()) {
          return next()
        }
        res.redirect('/dashboard');  // if auth    
      }
    }
    

    // app.js
    app.get('/dashboard', ensureAuthenticated, (req, res) => res.render('dashboard'))
    app.get('/login', forwardAuthenticated, (req, res) => res.render('login'))
    app.get('/register', forwardAuthenticated, (req, res) => res.render('register'))
    

提交回复
热议问题