gpt4 book ai didi

node.js - Passport 使用 NextJs 和 Express 对每个请求调用 deserializeUser

转载 作者:太空宇宙 更新时间:2023-11-03 23:54:13 26 4
gpt4 key购买 nike

我正在使用 Passport Local、Express、Next.js 和 MongoSession 存储为我的 Node 应用程序实现一个简单的登录。

一切正常,除了我的应用程序为每个请求运行 deserializeUser 。这导致我的数据库在任何应用交互中都会被点击 10 次以上

基于这篇文章https://github.com/jaredhanson/passport/issues/14#issuecomment-4863459我知道我对静态 Assets 的请求正在影响中间件堆栈。

大多数请求都是针对路径/_next/static*

我尝试过实现express.static,但失败了,如上面的示例所示。请帮助我弄清楚如何避免在每个请求上调用 deserializeUser。

谢谢!

这是我的代码:

app.js

const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(async () => {
const server = express();
server.use(helmet());
server.use(express.static(path.join(__dirname, '_next', 'static')));
server.use(express.json());

auth({ ROOT_URL, server });
api(server);

routesWithSlug({ server, app });
sitemapAndRobots({ server });

server.get('*', (req, res) => {
const url = URL_MAP[req.path];
if (url) {
app.render(req, res, url);
} else {
handle(req, res);
}
});

server.listen(port, (err) => {
if (err) throw err;
logger.info(`> Ready on ${ROOT_URL}`);
});
});

module.exports = { app };

auth.js

function auth({ ROOT_URL, server }) {
const dev = process.env.NODE_ENV !== 'production';


const MongoStore = mongoSessionStore(session);

const sess = {
name: 'builderbook.sid',
secret: process.env.sessSecret,
store: new MongoStore({
mongooseConnection: mongoose.connection,
ttl: 14 * 24 * 60 * 60, // expires in 14 days
}),
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
maxAge: 14 * 24 * 60 * 60 * 1000, // expires in 14 days
},
};

if (!dev) {
server.set('trust proxy', 1);
sess.cookie.secure = true;
}

server.use(session(sess));
server.use(passport.initialize());
server.use(passport.session());
server.use(bodyParser.urlencoded({ extended: false }));

passport.serializeUser((user, done) => {
console.log('serializeUser');
done(null, user.id);
});

passport.deserializeUser((id, done) => {
console.log(`deserializeUser, id: ${id}`);
User.findById(id, User.publicFields(), (err, user) => {
done(err, user);
});
});

const verifyLocal = async (req, email, password, done) => {
console.log({ email, password, req });
const { firstName, lastName } = req.body;
try {
// signInOrSign up the user to MongoDb
const user = await User.signInOrSignUp({
email,
password,
firstName,
lastName,
});
console.log(user);

if (!user) {
return done(null, false);
}

if (!User.verifyPassword(email, password)) {
return done(null, false);
}
return done(null, user);
} catch (err) {
console.log(err); // eslint-disable-line
return done(err);
}
};


passport.use(
new LocalStrategy(
{
usernameField: 'email',
passReqToCallback: true,
},
verifyLocal,
),
);
}

module.exports = auth;

authroutes.js

router.post('/login', passport.authenticate('local', { failureRedirect: '/fail' }), (req, res) => {
res.redirect('/');
});

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

module.exports = router;

最佳答案

这段代码似乎解决了问题。感谢 Builderbook 上的 Tima!

https://github.com/builderbook/builderbook/issues/229

server.get('/_next*', (req, res) => {
handle(req, res);
});

server.get('/static/*', (req, res) => {
handle(req, res);
});

关于node.js - Passport 使用 NextJs 和 Express 对每个请求调用 deserializeUser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58070101/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com