Reputation: 11880
I was trying to comprehend how passport strategy is working.
Consider these api routes which I am using to authenticate.
router.get("/google", passport.authenticate('google', { scope: ['profile', 'email'] }));
router.get("/google/callback", passport.authenticate('google'), (req, res) => {
res.redirect("http://localhost:3000/")
})
And this is the passport strategy
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)
})
}
})
})
)
Now, I think I understand what is happening here, but one thing I am unable to comprehend here is..
How is
passport.use(
new GoogleStratergy({
//Options for the stratergy
being called here? I mean I don't see any export statements, so how is it linked with out Node App? or how does passport knows behind the scene about the location of our google strategy **
Also, Just to confirm, after we pass done from our passport.use? it goes to serialize?
Upvotes: 4
Views: 746
Reputation: 4956
When you require
passport, you get a singleton instance i.e. it's constructed the first time you require
passport, and is reused every time and everywhere it's require
d subsequently.
So you don't need to share the instance between modules i.e. no need for export. Any configuration you do on the instance is visible everywhere you require it.
There are other objects in NodeJS that work the same way, one prominent example is the express
app instance.
Here is the source code for passport where you can verify this.
Upvotes: 5