简体   繁体   中英

How to flash a user's username after a successful login using Passport.js?

I am trying to flash the message "Welcome back "username here" " to a user once they have successuly logged in to the website.

The problem is that logging in with passport is not a regular request and response, the authentication happens as an argument to the post request. Below you can find my code:

var express = require("express");
var router = express.Router();
var user = require("../models/user");
var passport = require("passport");

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

router.post('/register', (req,res) =>{
    user.register(
        new user({username: req.body.username}),
        req.body.password,
        (err, newUser) => {
            if(err){
                req.flash("error", err.message);
                return res.redirect("/register");
            }
            passport.authenticate("local")(req, res, function(){
                req.flash("success", "Successfully registered, welcome "+user.username.charAt(0).toUpperCase() + user.username.slice(1)+"!");
                res.redirect("/");
            });
        }
    );
});

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

router.post('/login', passport.authenticate("local",{
    successRedirect: "/",
    failureRedirect: "/login",
    failureFlash: true,
    successFlash: 'Welcome back!'//HERE IS WHERE I AM INTERESTED
}), (req,res) =>{
});

router.get('/logout', (req,res) =>{
    req.logout();
    req.flash("success", "Successfully Logged Out")
    res.redirect("/");
});

module.exports = router;

In the second argument to router.post , call passport.authenticate to handle the failureRedirect and failureFlash message. Then, for the third argument, write your callback function with req and res. In the body of this function is where you'll handle the "success" flash message and you'll have access to your username on the request object. And then you can do your res.redirect.

router.post(
    "/login",
    passport.authenticate("local", {
        failureRedirect: "/login",
        failureFlash: true
    }),
    (req,res) => {
       req.flash("success", "Welcome back!"//add your username variable here);
       res.redirect("/home");
    });

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