Search code examples
reactjsoauthpassport.jsexpress-session

In React, how can I determine when an oauth login was successful?


I'm learning react at the moment and have what I think is an easy question for the pros here. In a react component, I have a simple anchor tag that routes to my google oauth route:

<a href='/auth/google'>Sign In</a>

The express server handles this with passport and express-session, but the way I've done this I don't get a response from the server that I can use to setState if the login was completed. Instead, a successful login just redirects to the home page.

The user is logged in, but my UI has no idea.

My thought would be that I need some function in the component, e.g.:

login(e) {
  fetch('/auth/google')
    .then((response) => this.setState({isLoggedIn:...})
}

But this would just get that page, rather then route the user to it. Do I need to make a function that queries the server to see if the session exists every time the component loads?

Edit for clarity:

When oauth is successful, this is the boilerplate code that redirects the user home:

router.get('/google/callback', 
  passport.authenticate('google', { prompt: 'consent', failureRedirect: '/login', }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
});

While that redirect works fine, I don't know how to listen for session information/data on that response? The UI fired a GET from the anchor tag, so how do I setState on the response?


Solution

  • As far as I see you are using passport to authenticate user on your server, not client.

    If you already have sessions attached, than maybe your / client code could issue ajax get to server /isAuthenticated which would then return true, or false, or local set of credentials to be used further more.

    When response to ajax call gets to your client, you would remember it in your state, and application would then re-render as in logged state.

    Or if you do not need server side google authentication, you could use Google client library for javascript from your react App, and then when you get credentials from Google send them via ajax call to server, and possibly exchange them for local credentials to be used when talking to your server further more.