Nodejs and PassportJs: Redirect middleware after passport.authenticate not being called if authentication fails

前端 未结 4 1088
被撕碎了的回忆
被撕碎了的回忆 2020-12-14 11:53

I have no login page but rather I have a login form that appears on every page. I want to redirect user back to the same page they were on regardless of whether authenticati

4条回答
  •  不思量自难忘°
    2020-12-14 11:59

    Full answer, including:

    • Middleware to set redirectUrl
    • Flash messages
    • Not returning values that won't be used

    Just create a redirectTo value in your loginRequired middleware:

    var loginRequired = function(req, res, next) {
        if ( req.isAuthenticated() ) {
            next();
            return
        }
        // Redirect here if logged in successfully
        req.session.redirectTo = req.path;
        res.redirect('/login')
    }
    

    And then in your login POST:

    router.post('/login', function(req, res, next) {
        passport.authenticate('local', function(err, user, info) {
            if ( err ) {
                next(err);
                return
            }
            // User does not exist
            if ( ! user ) {
                req.flash('error', 'Invalid email or password');
                res.redirect('/login');
                return
            }
            req.logIn(user, function(err) {
                // Invalid password
                if ( err ) {
                    req.flash('error', 'Invalid email or password');
                    next(err);
                    return
                }
                res.redirect(req.session.redirectTo || '/orders');
                return
            });
        })(req, res, next);
    });
    

提交回复
热议问题