【发布时间】:2019-05-09 18:23:01
【问题描述】:
我试图了解护照策略的工作原理。
考虑一下我用来进行身份验证的这些 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策略的位置**
另外,只是为了确认一下,在我们通过护照完成后。使用?它要序列化吗?
【问题讨论】:
标签: node.js passport.js