Passport.authenticate 和 logout 方法和 flash 不起作用,直到我们在重定向后路由到新页面

Posted

技术标签:

【中文标题】Passport.authenticate 和 logout 方法和 flash 不起作用,直到我们在重定向后路由到新页面【英文标题】:Passport.authenticate and logout methods and flashes don't work until we route to a new page after the redirect 【发布时间】:2018-12-27 23:16:33 【问题描述】:

我的身份验证中间件有一个奇怪的问题。当我登录时,它会将我重定向到主页作为successRedirect 的一部分,但实际上并没有让我登录(因为导航没有变化)。但是,当我从主页点击另一条路线时,它会让我登录,显示 flash 消息,并且正如预期的那样,导航也发生了变化。我在注销时遇到了完全相同的行为。在注销方法中,我在每一行之后添加了控制台日志,并且看到所有日志都同时记录,但只有在后续单击后才会注销。

编辑:只有当我重定向到主页而不是其他页面时才会发生这种情况。经过更多检查,我发现用户没有在主页的req/ 路由)上发送,因此导航没有更新。如果我将它们重定向到另一个页面(在登录或注销之后),它工作得非常好,并且导航也会更新。所有页面都基于相同的layout.pug,并且导航也在其中定义。

app.js

const express = require(`express`);
const session = require(`express-session`);
const mongoose = require(`mongoose`);
const MongoStore = require(`connect-mongo`)(session);
const path = require(`path`);
const cookieParser = require(`cookie-parser`);
const bodyParser = require(`body-parser`);
const passport = require(`passport`);
const promisify = require(`es6-promisify`);
const flash = require(`connect-flash`);
const expressValidator = require(`express-validator`);
const routes = require(`./routes/index`);
const helpers = require(`./helpers`);
const errorHandlers = require(`./handlers/errorHandlers`);
const helmet = require(`helmet`);
require(`./handlers/passport`);
require(`./handlers/mail`);

// create our Express app
const app = express();
// view engine setup
app.set(`views`, path.join(__dirname, `views`)); // this is the folder where we keep our pug files
app.set(`view engine`, `pug`); // we use the engine pug, mustache or EJS work great too

// serves up static files from the public folder. Anything in public/ will just be served up as the file it is
app.use(express.static(path.join(__dirname, `public`)));

// Use helmet

app.use(helmet());

// Takes the raw requests and turns them into usable properties on req.body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded( extended: true ));

// Exposes a bunch of methods for validating data. Used heavily on userController.validateRegister
app.use(expressValidator());

// populates req.cookies with any cookies that came along with the request
app.use(cookieParser());

// Sessions allow us to store data on visitors from request to request
// This keeps users logged in and allows us to send flash messages
app.use(session(
    secret: process.env.SECRET,
    key: process.env.KEY,
    resave: false,
    saveUninitialized: false,
    store: new MongoStore( mongooseConnection: mongoose.connection )
));

// // Passport JS is what we use to handle our logins
app.use(passport.initialize());
app.use(passport.session());

// // The flash middleware let's us use req.flash('error', 'Shit!'), which will then pass that message to the next page the user requests
app.use(flash());

// pass variables to our templates + all requests
app.use((req, res, next) => 
    res.locals.h = helpers;
    res.locals.flashes = req.flash();
    res.locals.user = req.user || null;
    res.locals.currentPath = req.path;
    next();
);

// promisify some callback based APIs
app.use((req, res, next) => 
    req.login = promisify(req.login, req);
    next();
);

// After allllll that above middleware, we finally handle our own routes!
app.use(`/`, routes);

// If that above routes didnt work, we 404 them and forward to error handler
app.use(errorHandlers.notFound);

// One of our error handlers will see if these errors are just validation errors
app.use(errorHandlers.flashValidationErrors);

// Otherwise this was a really bad error we didn't expect! Shoot eh
if (app.get(`env`) === `development`) 
    /* Development Error Handler - Prints stack trace */
    app.use(errorHandlers.developmentErrors);


// production error handler
app.use(errorHandlers.productionErrors);

// done! we export it so we can start the site in start.js
module.exports = app;

路由/index.js

const express = require(`express`);
const router = express.Router();

const schoolController = require(`../controllers/schoolController`);
const authController = require(`../controllers/authController`);

const  catchErrors  = require(`../handlers/errorHandlers`);

router.get(`/`, (req, res) => 
    res.render(`index`);
);

router.get(`/events`, (req, res) => 
    res.render(`events`);
);

router.get(`/register`, authController.isNotLoggedIn, schoolController.registerForm);
router.post(`/register`, schoolController.validateRegister, catchErrors(schoolController.register));

router.get(`/login`, authController.isNotLoggedIn, (req, res) => 
    res.render(`events`);
);

router.post(`/login`, authController.login);

router.get(`/logout`, catchErrors(authController.logout));

module.exports = router;

控制器/authController.js

const passport = require(`passport`);

exports.login = passport.authenticate(`local`, 
    failureRedirect: `/login`,
    failureFlash: `Failed Login!`,
    successRedirect: `/`,
    successFlash: `You are now logged in!`
);

exports.logout = async (req, res) => 
    await req.logout();
    console.log(`Logged out`);
    await req.flash(`success`, `Successfully logged out`);
    console.log(`Flashes sent`);
    await res.redirect(`/`);
    console.log(`Redirected`);
;

exports.isLoggedIn = (req, res, next) => 
    if (req.isAuthenticated()) 
        next();
        return;
    

    req.flash(`error`, `You must be logged in to do that !!`);
    res.redirect(`/login`);
;


exports.isNotLoggedIn = (req, res, next) => 
    if (!req.isAuthenticated()) 
        next();
        return;
    

    req.flash(`error`, `You are already logged in !!`);
    res.redirect(`/login`);
;

handlers/passport.js

const passport = require(`passport`);
const mongoose = require(`mongoose`);
const SchoolUser = mongoose.model(`SchoolUser`);

passport.use(SchoolUser.createStrategy());

passport.serializeUser(SchoolUser.serializeUser());
passport.deserializeUser(SchoolUser.deserializeUser());

可能是什么问题?

【问题讨论】:

【参考方案1】:

您的静态文件夹中可能有一个index.html 文件,express.static 将在/ 公开该文件。

缓解方法:

    删除/重命名index.html文件。

    将静态路由更改为其他路径,如下所示:

    app.use('/public', express.static(path.join(__dirname, public)));

现在您的所有静态内容都将在“/public”而不是“/”中提供。

【讨论】:

以上是关于Passport.authenticate 和 logout 方法和 flash 不起作用,直到我们在重定向后路由到新页面的主要内容,如果未能解决你的问题,请参考以下文章

对passport.use(strategy) done 功能及其与passport.authenticate 的关系感到困惑

Passport.authenticate 和 logout 方法和 flash 不起作用,直到我们在重定向后路由到新页面

Nodejs和PassportJs:如果身份验证失败,则不会调用passport.authenticate后重定向中间件

Facebook护照身份验证,导出passport.authenticate方法

在发布路线上使用 nodemailer 发送电子邮件并使用 passport.authenticate 将用户保存到 mongodb

如何从sails action2调用Passport Authenticate函数