PassportJs刷新会话变量?

时间:2018-03-17 19:39:42

标签: node.js express passport.js passport-local

我正在使用带有节点的PassportJS来处理身份验证。 如果身份验证失败,我希望临时保存输入,以便我可以在网页上重新加载它们并显示某种错误消息:

Passport登录策略:

const localLogin = new LocalStrategy(
    {
        passReqToCallback: true,
        usernameField: 'email',
        passwordField: 'password'
    },
    async (req, email, password, done) => {
        try {
            const user = await User.findOneByEmail(email);
            if (user) {
                const passwordsMatch = await PasswordHash.compare(password, user.password);
                if (passwordsMatch) {
                    return done(null, user);
                }
            }

            console.log('Sending inputs back to the user : ' + req.sessionID);
            req.session.inputs = {
                email: email,
                . . . 
            }
            return done(null, false);

        } catch (err) {
            console.log(err);
            return done(err);
        }
    });

帐户登录路由器:Express中的URL结构('/ accounts / *'):

accountsRouter.get('/login', async (req, res) => {
    res.render('accounts/login.ejs', 
    { 
        inputs: req.session.inputs
    });

    console.log("BEFORE DELETE: " + req.session.inputs);
    delete req.session.inputs;
    console.log("AFTER DELETE: " + req.session.inputs);
});

我希望它能够存储输入并在登录失败后将其显示给用户。如果用户在Chrome上进行刷新(GET / accounts / login)而不是再次单击登录按钮(POST / accounts / login),则req.session.inputs变量应为空。但是,由于某种原因,变量在刷新浏览器时保持其值,即使控制台显示该变量已被删除。

以下是我得到的输出:

# Getting the login page (blank fields)
BEFORE DELETE: undefined
AFTER DELETE:  undefined
GET /accounts/login 200 7.042 ms - 2327

# Click the login button
Sending inputs back to the user : Km2o9VFTWkvQxsz28Tt7Tx9mzL2NS14f
POST /accounts/login 302 31.850 ms - 74

# Login fails, displaying inputs back to user. Delete variable on render
BEFORE DELETE: [object Object]
AFTER DELETE: undefined
GET /accounts/login 200 3.919 ms - 2338

# Hits Chrome refresh on login page, req.session.inputs should be undefined here but it's not?
BEFORE DELETE: [object Object]
AFTER DELETE: undefined
GET /accounts/login 200 2.404 ms - 2338

如果有人能指出我正确的方向,我将非常感激!

2 个答案:

答案 0 :(得分:0)

我怀疑浏览器正在缓存输入值。

当您渲染视图时,显式设置输入值如下:

<input type="text" name="textfield" value="">

答案 1 :(得分:0)

确定它不仅仅在Passport中,而且通常用于Express Session。发现您必须致电await req.session.save();或任何更改仅在本地进行,不会保存在会话存储中。