在 Sapper 路由或 sapper 中间件中使用 passportjs passport.authenticate()
using passportjs passport.authenticate() in Sapper route or sapper middleware
我过去将 passportjs 与 expressjs 一起使用,目前我正在尝试将它与 Sapper 应用程序合并,但我无法弄清楚如何在我的路线中包含 passport.authenticate() 因为它是工兵路线不是快速路线。此外,如果我尝试 运行 我的 server.js 文件中的所有内容,我 运行 会遇到如何将它与 sapper 中间件集成的问题。
passport.authenticate() in/with Sapper middleware or sapper routes js files (which is front not server routes) 怎么使用?
我的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 只是一个中间件,所以如果我想对用户进行身份验证并将其发送到 front/sapper,我需要弄清楚如何 运行 passport.authenticate() 在中间件函数里面,对吧?
如果我想在 sapper front 路由的路由 JS 文件中使用 passport:
//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 });
}
有什么想法吗?如果有人可以提供帮助,将不胜感激。
您不需要 运行 passport.authenticate() 在 sapper.middleware 中。您需要先添加 passport-local 策略,然后执行 serializeUser 和 deserializeUser,然后创建路由以执行 passport.authenticate 和
在 sapper.middleware 中捕获 req.session.passport 对象之后。我不使用 passport-local 策略,但这是我使用 passport-github 策略的 server.js。
//server.js
import sirv from 'sirv';
import express from 'express';
import passport from 'passport';
import { Strategy } from 'passport-github';
import bodyParser from 'body-parser';
import session from 'express-session';
import sessionFileStore from 'session-file-store';
import compression from 'compression';
import * as sapper from '@sapper/server';
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
const FileStore = sessionFileStore(session);
passport.use(new Strategy({
clientID: 'someClientID',
clientSecret: 'someClientSecret',
callbackURL: 'http://localhost:3000/auth/callback',
}, (accessToken, refreshToken, profile, cb) => {
// console.log('success');
return cb(null, profile);
}));
passport.serializeUser(function (user, cb) {
cb(null, user);
});
passport.deserializeUser(function (obj, cb) {
cb(null, obj);
});
const expressServer = express()
.use(passport.initialize())
.use(bodyParser.json())
.use(session({
secret: 'conduit',
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 31536000
},
store: new FileStore({
path: `.sessions`
})
}))
.get('/auth/login',
passport.authenticate('github'))
.get('/auth/callback',
passport.authenticate('github', { failureRedirect: '/auth/login' }),
(req, res) => {
res.redirect('/');
//console.log(req.user.username);
})
.get('/auth/logout', (req, res) => {
req.logout();
req.session.destroy( function (err) {
res.redirect('/');
});
})
.use(
compression({ threshold: 0 }),
sirv('static', { dev }),
sapper.middleware({
session: req => {
const user = req.session.passport ? req.session.passport.user.username : null;
// console.log(req.session.passport.user.username);
return { user };
}
})
)
if (dev) {
expressServer.listen(PORT, err => {
if (err) console.log('error', err);
});
}
export { expressServer }
在此之后,您可以在客户端中捕获此 { user } 对象
sapper 使用 const { session } = stores(); console.log($session)
通过商店路由组件,或者您可以通过特殊的 preload
函数获取它以在页面呈现之前应用,例如 index.svelte
<script context="module">
export function preload(page, { user }) {
return { user };
}
</script>
<script>
import { stores } from "@sapper/app";
import { onMount } from "svelte";
const { session } = stores();
export let user;
onMount(() => {
console.log($session);
});
</script>
<div>
{#if !user}
<p>Not logged in</p>
{:else}
<p>Logged in!</p>
{/if}
</div>
这里我同时使用了两种方法,但大多数时候就足够了
使用preload
,无需直接访问商店中的会话。
希望这会帮助你。祝你好运!
我使用 DioXine 的答案来实现 Google Auth.
cookie 现在也只有 http。
import sirv from "sirv";
import express from "express";
import bodyParser from "body-parser";
import session from "express-session";
import sessionFileStore from "session-file-store";
import compression from "compression";
import * as sapper from "@sapper/server";
import passport from "passport";
import { Strategy as GoogleStrategy } from "passport-google-oauth20";
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === "development";
passport.use(
new GoogleStrategy(
{
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/callback",
},
function (accessToken, refreshToken, profile, cb) {
// User.findOrCreate({ googleId: profile.id }, function (err, user) {
// return cb(err, user);
// });
return cb(null, profile);
}
)
);
passport.serializeUser(function (user, cb) {
cb(null, user);
});
passport.deserializeUser(function (obj, cb) {
cb(null, obj);
});
const FileStore = sessionFileStore(session);
const sessionConfig = {
secret: "sefmvks4Fgblolf4sdJHBd",
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
maxAge: 31536000,
},
//TODO: redis
store: new FileStore({
path: `.sessions`,
}),
};
express()
.use(passport.initialize())
.use(bodyParser.json())
.use(session(sessionConfig))
.get("/auth/google", passport.authenticate("google", { scope: ["profile"] }))
.get(
"/auth/google/callback",
passport.authenticate("google", { failureRedirect: "/auth/login" }),
(req, res) => {
res.redirect("/");
}
)
.get("/auth/logout", (req, res) => {
req.logout();
req.session.destroy(function (err) {
res.redirect("/");
});
})
.use(
compression({ threshold: 0 }),
sirv("static", { dev }),
sapper.middleware({
session: (req) => {
const user = req.session.passport ? req.session.passport.user.id : null;
return { user };
},
})
)
.listen(PORT, (err) => {
if (err) console.log("error", err);
});
这没有改变:
<script context="module">
export function preload(page, { user }) {
return { user };
}
</script>
<script>
import { stores } from "@sapper/app";
import { onMount } from "svelte";
const { session } = stores();
export let user;
onMount(() => {
console.log($session);
});
</script>
<div>
{#if !user}
<p>Not logged in</p>
{:else}
<p>Logged in!</p>
{/if}
</div>
如果它仅在刷新后有效,请检查:
https://github.com/sveltejs/sapper/issues/567#issuecomment-542788270
我过去将 passportjs 与 expressjs 一起使用,目前我正在尝试将它与 Sapper 应用程序合并,但我无法弄清楚如何在我的路线中包含 passport.authenticate() 因为它是工兵路线不是快速路线。此外,如果我尝试 运行 我的 server.js 文件中的所有内容,我 运行 会遇到如何将它与 sapper 中间件集成的问题。 passport.authenticate() in/with Sapper middleware or sapper routes js files (which is front not server routes) 怎么使用?
我的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 只是一个中间件,所以如果我想对用户进行身份验证并将其发送到 front/sapper,我需要弄清楚如何 运行 passport.authenticate() 在中间件函数里面,对吧?
如果我想在 sapper front 路由的路由 JS 文件中使用 passport:
//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 });
}
有什么想法吗?如果有人可以提供帮助,将不胜感激。
您不需要 运行 passport.authenticate() 在 sapper.middleware 中。您需要先添加 passport-local 策略,然后执行 serializeUser 和 deserializeUser,然后创建路由以执行 passport.authenticate 和 在 sapper.middleware 中捕获 req.session.passport 对象之后。我不使用 passport-local 策略,但这是我使用 passport-github 策略的 server.js。
//server.js
import sirv from 'sirv';
import express from 'express';
import passport from 'passport';
import { Strategy } from 'passport-github';
import bodyParser from 'body-parser';
import session from 'express-session';
import sessionFileStore from 'session-file-store';
import compression from 'compression';
import * as sapper from '@sapper/server';
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
const FileStore = sessionFileStore(session);
passport.use(new Strategy({
clientID: 'someClientID',
clientSecret: 'someClientSecret',
callbackURL: 'http://localhost:3000/auth/callback',
}, (accessToken, refreshToken, profile, cb) => {
// console.log('success');
return cb(null, profile);
}));
passport.serializeUser(function (user, cb) {
cb(null, user);
});
passport.deserializeUser(function (obj, cb) {
cb(null, obj);
});
const expressServer = express()
.use(passport.initialize())
.use(bodyParser.json())
.use(session({
secret: 'conduit',
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 31536000
},
store: new FileStore({
path: `.sessions`
})
}))
.get('/auth/login',
passport.authenticate('github'))
.get('/auth/callback',
passport.authenticate('github', { failureRedirect: '/auth/login' }),
(req, res) => {
res.redirect('/');
//console.log(req.user.username);
})
.get('/auth/logout', (req, res) => {
req.logout();
req.session.destroy( function (err) {
res.redirect('/');
});
})
.use(
compression({ threshold: 0 }),
sirv('static', { dev }),
sapper.middleware({
session: req => {
const user = req.session.passport ? req.session.passport.user.username : null;
// console.log(req.session.passport.user.username);
return { user };
}
})
)
if (dev) {
expressServer.listen(PORT, err => {
if (err) console.log('error', err);
});
}
export { expressServer }
在此之后,您可以在客户端中捕获此 { user } 对象
sapper 使用 const { session } = stores(); console.log($session)
通过商店路由组件,或者您可以通过特殊的 preload
函数获取它以在页面呈现之前应用,例如 index.svelte
<script context="module">
export function preload(page, { user }) {
return { user };
}
</script>
<script>
import { stores } from "@sapper/app";
import { onMount } from "svelte";
const { session } = stores();
export let user;
onMount(() => {
console.log($session);
});
</script>
<div>
{#if !user}
<p>Not logged in</p>
{:else}
<p>Logged in!</p>
{/if}
</div>
这里我同时使用了两种方法,但大多数时候就足够了
使用preload
,无需直接访问商店中的会话。
希望这会帮助你。祝你好运!
我使用 DioXine 的答案来实现 Google Auth.
cookie 现在也只有 http。
import sirv from "sirv";
import express from "express";
import bodyParser from "body-parser";
import session from "express-session";
import sessionFileStore from "session-file-store";
import compression from "compression";
import * as sapper from "@sapper/server";
import passport from "passport";
import { Strategy as GoogleStrategy } from "passport-google-oauth20";
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === "development";
passport.use(
new GoogleStrategy(
{
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/callback",
},
function (accessToken, refreshToken, profile, cb) {
// User.findOrCreate({ googleId: profile.id }, function (err, user) {
// return cb(err, user);
// });
return cb(null, profile);
}
)
);
passport.serializeUser(function (user, cb) {
cb(null, user);
});
passport.deserializeUser(function (obj, cb) {
cb(null, obj);
});
const FileStore = sessionFileStore(session);
const sessionConfig = {
secret: "sefmvks4Fgblolf4sdJHBd",
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
maxAge: 31536000,
},
//TODO: redis
store: new FileStore({
path: `.sessions`,
}),
};
express()
.use(passport.initialize())
.use(bodyParser.json())
.use(session(sessionConfig))
.get("/auth/google", passport.authenticate("google", { scope: ["profile"] }))
.get(
"/auth/google/callback",
passport.authenticate("google", { failureRedirect: "/auth/login" }),
(req, res) => {
res.redirect("/");
}
)
.get("/auth/logout", (req, res) => {
req.logout();
req.session.destroy(function (err) {
res.redirect("/");
});
})
.use(
compression({ threshold: 0 }),
sirv("static", { dev }),
sapper.middleware({
session: (req) => {
const user = req.session.passport ? req.session.passport.user.id : null;
return { user };
},
})
)
.listen(PORT, (err) => {
if (err) console.log("error", err);
});
这没有改变:
<script context="module">
export function preload(page, { user }) {
return { user };
}
</script>
<script>
import { stores } from "@sapper/app";
import { onMount } from "svelte";
const { session } = stores();
export let user;
onMount(() => {
console.log($session);
});
</script>
<div>
{#if !user}
<p>Not logged in</p>
{:else}
<p>Logged in!</p>
{/if}
</div>
如果它仅在刷新后有效,请检查: https://github.com/sveltejs/sapper/issues/567#issuecomment-542788270