12

In my node.js express app, I integrated the Facebook authentication using passport.js . I can open the Facebook login page in a popup window, then the login takes place. At this stage, the redirection takes place in the popup window . But I need to close the popup window and to make the redirection in the parent window (i.e. the parent window will redirect). I am gonna paste the full code here although I think the main issue is in the template file(.ejs).

And I could not find any solution in the similar questions out there in SO.

// Passport session setup.
passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});


// Use the FacebookStrategy within Passport.
passport.use(new FacebookStrategy({
    clientID: config.facebook_api_key,
    clientSecret:config.facebook_api_secret ,
    callbackURL: config.callback_url
  },

  function(accessToken, refreshToken, profile, done) {

    console.log(" id = "+profile.id);

    process.nextTick(function () {
      //Check whether the User exists or not using profile.id
      //Further DB code.
      profile.user_id="00000444000555";
      return done(null, profile);
    });

  }
));

app.set('views', __dirname + '/views');

app.set('view engine', 'ejs');
//app.set('view engine', 'jade');
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({ secret: 'keyboard cat', key: 'sid'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(__dirname + '/public'));

//Router code
app.get('/', function(req, res){
  res.render('index', { user: req.user });
});

app.get('/account', ensureAuthenticated, function(req, res){

    console.log(req.user);
  res.render('account', { user: req.user });
});

//Passport Router
app.get('/auth/facebook', passport.authenticate('facebook'));
app.get('/auth/facebook/callback',

passport.authenticate('facebook', {
       successRedirect : '/',
       failureRedirect: '/login'
  }),

   function(req, res) {
    res.redirect('/');

  });

app.get('/logout', function(req, res){
  req.logout();
   res.redirect('/');
});

function ensureAuthenticated(req, res, next) {
     if (req.isAuthenticated()) { return next(); }
  res.redirect('/login')
}
app.listen(8000);

And the template file is :

<script type="text/javascript">
    if (window.location.hash && window.location.hash == '#_=_') {
        if (window.history && history.pushState) {
            window.history.pushState("", document.title, window.location.pathname);
        } else {
            // Prevent scrolling by storing the page's current scroll offset
            var scroll = {
                top: document.body.scrollTop,
                left: document.body.scrollLeft
            };
            window.location.hash = '';
            // Restore the scroll offset, should be flicker free
            document.body.scrollTop = scroll.top;
            document.body.scrollLeft = scroll.left;
        }
    }
</script>

<% if (!user) { %>

  <div style="width:500px;height:180px;">
    <h2 style="font-size:40px;">Welcome! Please log in.</h2>
    <a href="javascript:void(0)" onclick=" window.open('/auth/facebook','',' scrollbars=yes,menubar=no,width=500, resizable=yes,toolbar=no,location=no,status=no')"><img src="fb-login.jpg" width="151" height="24"></a>
    </div>

<% } else { %>

<script type="text/javascript">

    window.parent.location.href ="/";
    window.close();
</script>
    <h2>Hello, <%= user.displayName %>.</h2>
<% } %>
2
  • Maybe this helps? webdeveasy.com/single-page-application-authentication Not the same stack, but you may be able to borrow their idea
    – kane
    Mar 13, 2015 at 4:40
  • @kane pretty much spot on, but they are using angular to send back msg to parent window... im now wondering how can i do this without angular... it seems like opening a socket and sending message to myself can work but looks like overkill
    – Max Yari
    Mar 28, 2015 at 1:28

3 Answers 3

21

My comment above was perhaps short of a full answer, so here's my full solution which I do on my site.

In my node backend, I created a route that basically routes to a special page called after-auth.html upon successful authentication like so

app.get('/auth/twitter/callback',
  auth.passport.authenticate('twitter', { failureRedirect: '/failedLogin.html' }),
  function(req, res) {
    res.redirect('/after-auth.html');
});

My after-auth.html page simply has javascript that puts focus back on the parent page and closes itself like so

<script type="text/javascript">
    if (window.opener) {
        window.opener.focus();

      if(window.opener.loginCallBack) {
        window.opener.loginCallBack();
      }
    }
    window.close();
</script>  

You may also notice that I invoke a function called loginCallBack. I use this as a hook so the parent browser knows to update its model/views after successful authentication. For example, in my loginCallBack, I check whether the user is logged in and remove all "sign in" buttons and replace them with the user's profile image e.g.

  var loginCallBack = function() {
    loginCntr.checkLogin();
  }
1
  • Yeah i just figured out yesterday after posting my comment, that I can access parent from modal window, right now i'm implementing the same thing, that you described here, but as I understand there is a problem with IE sometimes telling windows.opener is undefined due some IE policies, but IE supports showModalDialog which is depreciated by Chrome yet can be an alternative to window.open() for IE. And thank you for the answer)
    – Max Yari
    Mar 28, 2015 at 13:45
7

The simplest solution is this:

res.send('<script>window.close()</script>');
2
  • Hahaha well I'm glad you scrolled to the very bottom ¯\_(ツ)_/¯
    – Shruggie
    Sep 4, 2019 at 7:37
  • 1
    Oooh, elegant in its simplicity.
    – CatDadCode
    Nov 30, 2019 at 20:44
2

We've struggled with this ourselves and ended up writing a simple javascript plugin to help us with this https://github.com/enhancv/popup-tools

Using it would go like this on the client:

<button id="button">Facebook Login</button>
<script>
document.getElementById("button").onclick = function () {
    popupTools.popup('/popup-url', "Facebook Connect", {}, function (err, user) {
        if (err) {
            alert(err.message);
        } else {
            // save the returned user in localStorage/cookie
        }
    })
</script>

On the server:

passport.use(new FacebookStrategy({
    clientID: process.env.FACEBOOK_ID,
    clientSecret: process.env.FACEBOOK_SECRET,
    callbackURL: '/calback-url',
}, function (accessToken, refreshToken, profile, done) {
    // process facebook profile into user
}));

app.post('/popup-url', passport.authenticate('facebook'))
app.get('/callback-url', 
    passport.authenticate('facebook'),
    function (req, res) {
        res.end(popupTools.popupResponse(req.user))
    }
);

Hope people will find this useful.

2
  • Super! Hassle free. Just a quick question. Does it work with all the browsers?
    – kittu
    Jan 19, 2017 at 18:33
  • What if I want to show options like fb and google in popup and send a request. I tried it but the response returns as err
    – kittu
    Jan 26, 2017 at 13:20

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.