Tuesday 6 June 2017

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?



via Virtual Anomaly

No comments:

Post a Comment