Search code examples
node.jsexpresspassport.jspassport-facebook

Node: Accessing req.db in a function where I don't have access to req


I'm trying at add facebook authentication to my app using passport - this works okay, but I need to access the database within passport.use().

Here is my code in routes/auth.js:

var express = require('express');
var router = express.Router();
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;

[...]

passport.use(new FacebookStrategy({
        clientID: REDACTED,
        clientSecret: REDACTED,
        callbackURL: REDACTED,
        profileFields: ['id', 'displayName', 'email']
    },
    function(accessToken, refreshToken, profile, cb) {
        var db = need to access db here;
        db.users.insertOne({ 'facebookId': profile.id, 'name': profile.displayName, 'email': profile.email }, function(err, user) {
            return cb(err, user);
        });
    }
));

module.exports = router;

In app.js, I have the following code:

// make our db accessible to the router
app.use(function(req,res,next) {
    req.db = db;
    next();
});

How can I access req.db in auth.js in the location marked?


Solution

  • If the db is in the req object, you can configue FacebookStrategy to pass the req object to the verify function.

    See:

    passport.use(new FacebookStrategy({
            clientID: REDACTED,
            clientSecret: REDACTED,
            callbackURL: REDACTED,
            profileFields: ['id', 'displayName', 'email'],
            passReqToCallback: true
        },
        function(req, accessToken, refreshToken, profile, cb) {
            var db = req.db; // need to access db here;
            db.users.insertOne({ 'facebookId': profile.id, 'name': profile.displayName, 'email': profile.email }, function(err, user) {
                return cb(err, user);
            });
        }
    ));
    

    Hope it works.