Search code examples
javascriptnode.jspassport.jspassport-facebook

Get subdomain inside passport FacebookTokenStrategy and GoogleStrategy


I am building a node.js application with wildcard subdomains. Each subdomain will be a separate part of the app which will have separate authentication for users based on the subdomain.

For example, lets say my app will have subdomains abc.domain.com and xyz.domain.com and the below users

User1@gmail.com signs up for abc.domain.com
User2@yahoo.com signs up for xyz.domain.com 
User3@msn.com signs up for both abc.domain.com and xyz.domain.com

Each user should only have access to the subdomain they signed up for. So User1@gmail.com should be able to log in to abc.domain.com but should be rejected at xyz.domain.com

Normally I would get the subdomain by using req.get('host') and then extract the subdomain from there but as far as I know, passport.js does not have a req parameter. Is there anyway for me to get the subdomain name of the current site the user is trying to log in? Below is the passport-facebook-token code copied from https://github.com/drudge/passport-facebook-token

var FacebookTokenStrategy = require('passport-facebook-token');

passport.use(new FacebookTokenStrategy({
        clientID: FACEBOOK_APP_ID,
        clientSecret: FACEBOOK_APP_SECRET
    }, function(accessToken, refreshToken, profile, done) {
        // SQL statement will go here that will check whether a user is signed up for the subdomain they are logging into. It will also check if the user exists in the database
    });
  }
));

Solution

  • I found the solution so answering my own question in case anyone will need to know how to get req to show up in any strategy using passport.js, All you need to do is set passReqToCallBack to true.

    Below is the updated code

    passport.use(new FacebookTokenStrategy({
            clientID: FACEBOOK_APP_ID,
            clientSecret: FACEBOOK_APP_SECRET,
            passReqToCallback: true   // Added for req to show in callback
        }, function(req, accessToken, refreshToken, profile, done) {
            // SQL statement will go here that will check whether a user is signed up for the subdomain they are logging into. It will also check if the user exists in the database
        });
      }
    ));