最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to detect if initial page load was from a redirect - Stack Overflow

programmeradmin1浏览0评论

I have a reactjs app which is using firebase to authenticate a user and also link with various auth provider accounts by using the firebase xxxWithRedirect() methods. For example, the following is invoked from the /users/settings page.

var user = this.props.fb.auth().currentUser;
if (user !== null) {
  var provider = new firebase.auth.GoogleAuthProvider();
  user.linkWithRedirect(provider).then(function () {
      console.log('Successfully linked with Google account');
    },
    function (error) {
      console.log('Failed to link with Google account:  code=' + error.code + ' message=' + error.message);
    });
}
else {
  console.log('user is null');
}

After the authentication is plete, the auth provider redirects back to the app page that originated the redirect. For example:

Navigated to http://localhost:3000/users/settings

In the app route handling, I would like to be able to determine if the initial page load was from a redirect or not. This is so that I can determine whether I should take the user back to the /users/settings page in the case of redirect from auth provider or the / page if the user has not yet been authenticated and is a not an auth redirect page load.

        <Switch>
          <Route exact path="/" ponent={Home}/>
          <Route exact path="/users/profile" render={() => (isLoggedIn() ? <UserProfile fb={fb}/> : <Redirect to="/"/>)}/>
          <Route exact path="/users/settings" render={() => (isLoggedIn() ? <UserSettings fb={fb}/> : <Redirect to="/"/>)}/>
          <Route ponent={NoMatch}/>
        </Switch>

Is there a way to tell if a reactjs matching route path is from a redirect?

I have a reactjs app which is using firebase to authenticate a user and also link with various auth provider accounts by using the firebase xxxWithRedirect() methods. For example, the following is invoked from the /users/settings page.

var user = this.props.fb.auth().currentUser;
if (user !== null) {
  var provider = new firebase.auth.GoogleAuthProvider();
  user.linkWithRedirect(provider).then(function () {
      console.log('Successfully linked with Google account');
    },
    function (error) {
      console.log('Failed to link with Google account:  code=' + error.code + ' message=' + error.message);
    });
}
else {
  console.log('user is null');
}

After the authentication is plete, the auth provider redirects back to the app page that originated the redirect. For example:

Navigated to http://localhost:3000/users/settings

In the app route handling, I would like to be able to determine if the initial page load was from a redirect or not. This is so that I can determine whether I should take the user back to the /users/settings page in the case of redirect from auth provider or the / page if the user has not yet been authenticated and is a not an auth redirect page load.

        <Switch>
          <Route exact path="/" ponent={Home}/>
          <Route exact path="/users/profile" render={() => (isLoggedIn() ? <UserProfile fb={fb}/> : <Redirect to="/"/>)}/>
          <Route exact path="/users/settings" render={() => (isLoggedIn() ? <UserSettings fb={fb}/> : <Redirect to="/"/>)}/>
          <Route ponent={NoMatch}/>
        </Switch>

Is there a way to tell if a reactjs matching route path is from a redirect?

Share Improve this question edited Dec 2, 2017 at 16:58 user2800837 asked Dec 2, 2017 at 3:39 user2800837user2800837 3211 gold badge3 silver badges9 bronze badges 2
  • can't you tell firebase auth to redirect to a specific page? – André Werlang Commented Dec 2, 2017 at 17:17
  • @AndréWerlang - Firebase auth is actually doing what I want, it tries to redirect back to the /users/settings page which is where the auth request originated from. Unfortunately though, the navigation to this path happens before the user authentication has been pleted, i.e. the firebase user has not been set yet as this happens asynchronously in firebase.auth().onAuthStateChanged(). I don't want to navigate to this /users/settings page unless a firebase user is logged in. So it's really a timing thing. I'd like to get them to /users/settings after the user is logged in. – user2800837 Commented Dec 2, 2017 at 17:31
Add a ment  | 

3 Answers 3

Reset to default 4

@AndreWerlang I was able to solve my problem by making use of the operationType provided in the firebase.auth().getRedirectResult() method. In this particular case I wanted to take the user back to the /user/settings page because that is where the user can link other auth provider accounts. By checking if the operationType was an attempt to "link" another account, I simply redirect again to the /user/settings page since the firebase user was not intact when the first redirect to /users/settings was received from the auth provider. This is the code.

ponentDidMount = () => {
    firebase.auth().getRedirectResult().then(function(userCredential) {
        console.log('Successfully redirected');
        var operationType = userCredential.operationType;
        if (operationType) {
            console.log('Redirect operationType = ' + operationType);
            switch (operationType) {
                case 'signIn':
                   break;
                case 'link':
                   this.setState({redirectToUserSettings: true});
                   break;
                case 'reauthenticate':
                   break;
                default:
            }
        }
    }.bind(this), function(error) {}
}

render() {
    return (
        <div className="App">
            <Router history={history}>
                <div>
                    {this.state.redirectToUserSettings && <Redirect to="/users/settings" />}
                </div>
             </Router>
        </div>
    );
}

If there's a timing issue, Firebase Auth returning to your page before a user object is populated, there needs to be a method to wait/retrieve this information when ready.

From https://firebase.google./docs/auth/web/google-signin#redirect-mode:

firebase.auth().getRedirectResult().then(function(result) {
  if (result.credential) {
    // This gives you a Google Access Token. You can use it to access the Google API.
    var token = result.credential.accessToken;
    // ...
  }
  // The signed-in user info.
  var user = result.user;
}).catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  // The email of the user's account used.
  var email = error.email;
  // The firebase.auth.AuthCredential type that was used.
  var credential = error.credential;
  // ...
});

From https://firebase.google./docs/reference/js/firebase.auth.Auth#getRedirectResult:

If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an error. If no redirect operation was called, returns a UserCredential with a null User.

So at this point you would know when user is authenticated or not and deal with it.

Either:1) find a way to provide a custom url to the thing that redirects (if possible), and put something like "?redirect=true" on it, or else 2) Use a server session variable to hold a flag that says it will be expecting to get a redirect.

发布评论

评论列表(0)

  1. 暂无评论