我过去将passportjs与expressjs一起使用,目前我正在尝试将它与Sapper应用程序合并,但我无法弄清楚如何在我的路线中包含passport.authenticate(),因为它是sapper路线而不是快速路线。此外,如果我尝试运行 server.js 文件中的所有内容,我会遇到如何将其与 sapper 中间件集成的问题。您如何在 Sapper 中间件或 sapper 路由 js 文件中使用 passport.authenticate()(这是前端而不是服务器路由)?
我的 server.js 是典型的:
const sirv = require('sirv');
import express from 'express';
var cookieParser = require('cookie-parser');
import * as sapper from '@sapper/server';
const session = require('express-session');
var passport = require('passport');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/passport', {
useNewUrlParser: true });
const MongoStore = require('connect-mongo')(session);
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
store: new MongoStore({ url: 'mongodb://localhost/passport' }),
cookie: { secure: false, maxAge: 1000 * 60 * 60 * 24 * 7 }
}));
app.use(passport.initialize());
app.use(passport.session());
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
const assets = sirv('static', {
maxAge: 31536000, // 1Y
immutable: true
});
app.use(assets, sapper.middleware({
session: req => ({
user: req.session && req.session.user
})})).listen(process.env.PORT, err => { if (err) console.log('error', err); });
正如你所看到的,Sapper 只是一个中间件,所以如果我想验证一个用户并将其发送到前端/sapper,我需要弄清楚如何在中间件函数中运行 passport.authenticate(),对吧?
如果我想在路由 JS 文件中使用护照,这是 sapper front route:
//How to import passport.js here to make passport.authenticate() middleware available?
import passport from './passport';
import User from './mongoso';
export async function post(req, res, next) {
res.setHeader('Content-Type', 'application/json');
/* Retrieve the data */
var data = req.body;
req.session.user = data.email;
console.log("Here's the posted data:", data);
console.log("information in the session is:", req.session);
/* Returns the result */
return res.end(JSON.stringify({ Email: req.session.user }));
//return res.json({ data: data });
}
有任何想法吗?如果有人可以提供帮助,我们将不胜感激。