Redirecting to previous page after authentication in node.js using passport.js

前端 未结 7 1210
悲&欢浪女
悲&欢浪女 2020-11-30 17:13

I\'m trying to establish a login mechanism using node.js, express and passport.js. The Login itself works quite nice, also sessions are stored nicely with redis but I do hav

7条回答
  •  庸人自扰
    2020-11-30 17:45

    My way of doing things:

    const isAuthenticated = (req, res, next) => {
      if (req.isAuthenticated()) {
        return next()
      }
      res.redirect( `/login?origin=${req.originalUrl}` )
    };
    

    GET /login controller:

    if( req.query.origin )
      req.session.returnTo = req.query.origin
    else
      req.session.returnTo = req.header('Referer')
    
    res.render('account/login')
    

    POST /login controller:

      let returnTo = '/'
      if (req.session.returnTo) {
        returnTo = req.session.returnTo
        delete req.session.returnTo
      }
    
      res.redirect(returnTo);
    

    POST /logout controller (not sure if there is 100% ok, comments are welcome):

    req.logout();
    res.redirect(req.header('Referer') || '/');
    if (req.session.returnTo) {
      delete req.session.returnTo
    }
    

    Clear returnTo middleware (clears returnTo from session on any route except auth routes - for me they are /login and /auth/:provider ):

    String.prototype.startsWith = function(needle)
    {
      return(this.indexOf(needle) == 0)
    }
    
    app.use(function(req, res, next) {
      if ( !(req.path == '/login' || req.path.startsWith('/auth/')) && req.session.returnTo) {
        delete req.session.returnTo
      }
      next()
    })
    

    This approach have two features:

    • you can protect some routes with isAuthenticated middleware;
    • on any page you can simply click on login URL, and after login return to that page;

提交回复
热议问题