Search code examples
node.jsexpresspassport.jsreq

Access req and res inside Passport JS strategy


I'm working on an app and I want my users to be able to connect using their Spotify accounts. I've managed to do this using the Passport JS Spotify strategy. The problem now is that I also want to provide a functionality for users to be able to register and log in via email. After they are logged in, they should be able to link their Spotify account to the brand new email-based account.

I have this code to use the Spotify strategy.

passport.use(
    new SpotifyStrategy(
        {
            clientID: process.env.SPOTIFY_CLIENTID,
            clientSecret: process.env.SPOTIFY_SECRET,
            callbackURL: '/auth/spotify/callback',
            scope: ['user-read-email']
        },
        async function (_accessToken, _refreshToken, _expires_in, profile, cb) {
            return await passportSocialLogin(profile, cb)
        }
    )
)

Here I have that function call (passportSocialLogin). Here I add the data from Spotify to my database. It would be really nice to be able to pass req as an argument of passportSocialLogin. This would help me to find the logged in user via the session object and then to link his account with the Spotify one.

Do you have any ideas for this? Thank you! Have a nice day!


Solution

  • I've found a solution here: https://www.passportjs.org/concepts/delegated-authorization/
    As you can see, you can use passReqToCallback inside the strategy, and the req object will be available as the first argument of the verify callback.
    In my case the solution was:

    passport.use(
        new SpotifyStrategy(
            {
                clientID: process.env.SPOTIFY_CLIENTID,
                clientSecret: process.env.SPOTIFY_SECRET,
                callbackURL: '/auth/spotify/callback',
                scope: ['user-read-email'],
                passReqToCallback: true
            },
            async function (req, _accessToken, _refreshToken, _expires_in, profile, cb) {
                return await passportSocialLogin(profile, req, cb)
            }
        )
    )