Search code examples
javascriptexpresspassport.jsgoogle-oauth

Redirecting users if they aren't using specific domain


I'm trying to redirect users to a route using res.redirect, or send a file using res.send if they attempt to login using a domain other than the one specified. The condition checking is working, but I'm trying to use res.sendFile/res.redirect but it doesn't seem to be working within the scope of this function. It's clear that there isn't a res in this function, but that's all that I've come up with. Had a really good search online but I'm yet to resolve the problem.

Any help is appreciated.

passport.use(
  new GoogleStrategy({
    callbackURL: '/google/redirect',
    clientID: keys.google.clientID,
    clientSecret: keys.google.clientSecret
}, function (accessToken, refreshToken, profile, done){
  if (profile._json.hd === "HIDDEN-DOMAIN.COM") {
    User.findOne({googleId : profile.id})
  .then(function(currentUser){
    if(currentUser){
      console.log('User with ID' + currentUser.googleId +' already exists. No new entry was made');
      done(null, currentUser);
    } else {
      new User({
        username: profile.displayName,
        googleId: profile.id
      })
      .save()
      .then(function(newUser){
        console.log('New user created: ' + newUser);
        done(null, newUser);
      });
    }
  })
} else {
  console.log(__dirname);
  res.sendFile('../login.html');
};
}));

Solution

  • Use a middleware to perform the check, and next() if it passes. Checkout: https://expressjs.com/en/guide/using-middleware.html

    This example shows a middleware function mounted on the / path. The function is executed for any type of HTTP request on the / path.

    This example shows a route and its handler function (middleware system). The function handles GET requests.

    app.use('/', function (req, res, next) {
      // Check 1
      console.log('Request URL:', req.originalUrl)
      next()
    }, function (req, res, next) {
      // Check 2: Pass first check
      console.log('Request Type:', req.method)
      next()
    })
    app.get('/', (req, res) => {
       // Final Route
    });
    

    Example:

    app.use('/first', function (req, res, next) {
        passport.use(
            new GoogleStrategy({
                callbackURL: '/google/redirect',
                clientID: keys.google.clientID,
                clientSecret: keys.google.clientSecret
            }, function (accessToken, refreshToken, profile, done){
                if (profile._json.hd === "HIDDEN-DOMAIN.COM") {
                    User.findOne({googleId : profile.id})
                        .then(function(currentUser){
                            if(currentUser){
                                console.log('User with ID' + currentUser.googleId +' already exists. No new entry was made');
                                done(null, currentUser);
                            } else {
                                new User({
                                    username: profile.displayName,
                                    googleId: profile.id
                                })
                                    .save()
                                    .then(function(newUser){
                                        console.log('New user created: ' + newUser);
                                        done(null, newUser);
                                        next(); // next();
                                    });
                            }
                        })
                } else {
                    console.log(__dirname);
                    next(); // next();
                }
            }));
    
    }, function (req, res, next) {
        // More checks
        next()
    });
    
    app('/', (req, res) => {
        // final route here
        res.sendFile('../login.html');
    })