gpt4 book ai didi

node.js - Passport Strategy 如何在幕后运作

转载 作者:搜寻专家 更新时间:2023-10-31 22:44:23 24 4
gpt4 key购买 nike

我试图理解通行证策略是如何运作的。

考虑我用来进行身份验证的这些 api 路由。

  router.get("/google",  passport.authenticate('google', { scope: ['profile', 'email'] }));
router.get("/google/callback", passport.authenticate('google'), (req, res) => {
res.redirect("http://localhost:3000/")
})

这是通行证策略

const passport = require('passport')
const GoogleStratergy = require('passport-google-oauth20')
const keys = require("./key.js")
const User = require("../models/user-model.js")

passport.serializeUser((user, done) => {
done(null, user.id)
})

passport.deserializeUser((id, done) => {
User.findById(id).then((user) => {
done(null, user) //pass it in req of our routes
})
})

passport.use(
new GoogleStratergy({
//Options for the stratergy
callbackURL: "/auth/google/callback",
clientID: keys.google.clientID,
clientSecret: keys.google.clientSecret
}, (accessToken, refreshToken, profile, done) => {


User.findOne({userId: profile.id }).then((currentUser) => {
if (currentUser) {
done(null, currentUser)
} else {
//Changing Image String
let oldURL= profile.photos[0]["value"]
let newURL = oldURL.substr(0, oldURL.length-2);
newURL = newURL + "250"
//Creating Mongoose Database
new User({
username: profile.displayName,
userId: profile.id,
image: newURL,
email: profile.emails[0]["value"]
}).save().then((newUser) => {
console.log("new user created", newUser)
done(null, newUser)
})
}

})

})
)

现在,我想我明白这里发生了什么,但我无法理解的一件事是..

怎么样

passport.use(
new GoogleStratergy({
//Options for the stratergy

被叫到这里?我的意思是我没有看到任何导出语句,那么它是如何与 Node App 链接的呢?或者 passport 如何在幕后知道我们的 google 策略的位置 **

此外,只是确认一下,在我们通过 passport.use 之后完成了吗?它去序列化?

最佳答案

当您require passport 时,您会得到一个单例实例,即它是在您第一次require passport 时构建的,并且在require< 时随处重复使用d 随后。

因此您不需要在模块之间共享实例,即不需要导出。您在实例上所做的任何配置在您需要的任何地方都是可见的。

NodeJS 中还有其他对象以相同的方式工作,一个突出的例子是 express 应用程序实例。

这是 source code对于 Passport ,您可以在其中验证这一点。

关于node.js - Passport Strategy 如何在幕后运作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53678779/

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