Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting to a page after Firebase login - Javascript [duplicate]

How can I redirect to a different webpage after the user has signed in?

Currently when a user logs in, data gets retrieved however, it doesn't redirect the user to a different website.

I know I should use 'getRedirectResult', but can someone show me how to use it and how it redirect the user to a different webpage, maintaining the retrieved user data.

My javascript work:

function toggleSignIn() {
  if (!firebase.auth().currentUser) {
    // [START createprovider]
    var provider = new firebase.auth.GoogleAuthProvider();
    // [END createprovider]
    // [START addscopes]
    provider.addScope('https://www.googleapis.com/auth/plus.login');
    // [END addscopes]
    // [START signin]
    firebase.auth().signInWithPopup(provider).then(function(result) {
      // 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;
      // [START_EXCLUDE]
      document.getElementById('quickstart-oauthtoken').textContent = token;
      // [END_EXCLUDE]
    }).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; 
      // [START_EXCLUDE]
      if (errorCode === 'auth/account-exists-with-different-credential') {
        alert("You have already signed up with a different auth provider for that email.");
        // If you are using multiple auth providers on your app you should handle linking
        // the user's accounts here.
      }
  else if (errorCode === 'auth/auth-domain-config-required') {
    alert("An auth domain configuration is required"); 
      }
      else if (errorCode === 'auth/cancelled-popup-request') {
          alert("Popup Google sign in was canceled");
      }
      else if (errorCode === 'auth/operation-not-allowed') {
          alert("Operation is not allowed");
      }
      else if (errorCode === 'auth/operation-not-supported-in-this-environment') {
          alert("Operation is not supported in this environment");
      }
      else if (errorCode === 'auth/popup-blocked') {
          alert("Sign in popup got blocked");
      }
      else if (errorCode === 'auth/popup-closed-by-user') {
          alert("Google sign in popup got cancelled");
      }
      else if (errorCode === 'auth/unauthorized-domain') {
          alert("Unauthorized domain");
      }
       else {
        console.error(error);
      }
      // [END_EXCLUDE]
    });
    // [END signin]
  } else {
    // [START signout]
    firebase.auth().signOut();
    // [END signout]
  }
  // [START_EXCLUDE]
  document.getElementById('quickstart-sign-ing').disabled = false;
  // [END_EXCLUDE]
}
like image 257
mulu gebreselassie Avatar asked Jun 25 '16 22:06

mulu gebreselassie


People also ask

What does Firebase auth () CurrentUser return?

If a user isn't signed in, CurrentUser returns null. Note: CurrentUser might also return null because the auth object has not finished initializing.

Is Firebase authentication OAuth?

A Flutter plugin that makes it easy to perform OAuth sign in flows using FirebaseAuth. It also includes support for Sign in by Apple for Firebase. This plugin supports Android, iOS and Web.


4 Answers

Get the email and password from user and then pass the values to signInWithEmailAndPassword, if some error occurs it will print the message, if not Firebase will successfully sign the user in.

firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    console.log(error.Message);

});

You also need a listener that handles login and logout status. This is where you can redirect users if they have successfully logged in.

To handle login and logout, always use onAuthStateChanged()

//Handle Account Status
firebase.auth().onAuthStateChanged(user => {
  if(user) {
    window.location = 'home.html'; //After successful login, user will be redirected to home.html
  }
});

The moment someone logins, user will be populated with user details and you can use it to redirect to another page.

like image 74
gegobyte Avatar answered Oct 13 '22 10:10

gegobyte


You just need to add two redirects inside initApp() to make this happen. I’m referring to the quickstart git repo https://github.com/firebase/quickstart-js/blob/master/auth/email.html, as I came here via the duplicate question Redirecting to a page after Firebase login - Javascript

1) on line 163, add the page you want logged-in users to be redirected to:

162 //User is signed in.
163 window.location = ‘loggedIn.html’;
164 var displayName = user.displayName;

2) on line 180 (now 181 because of the add above), add a redirect back to the login page:

180 // User is signed out.
181 window.location = ‘index.html’;
182 // [START_EXLUDE]

You need to add the entire script to both the index and the logged in pages - so everything (including the script tags) between lines 37 and 201 from the original git repo (but with the two redirect additions above).

Now, if you try to go directly to loggedIn.html without logging in, the initApp function will check if you are logged in, see that you aren’t, and redirect you to the login page.

The only issue is you get a quick flash of the logged content before the redirect, so to get around this you could set the body of this page to be hidden, and have a script that runs if the user is logged in that removes the hidden class.

Lastly, you’ll want to add a redirect inside the toggleSignIn function, on line 46 of the original repo:

45  firebase.auth().signOut();
46  window.location = ‘index.html’;
47  // [END signout]
like image 35
Sean Doherty Avatar answered Oct 13 '22 10:10

Sean Doherty


If you're building a single-page style application, you likely don't need to redirect. Instead you would just change your application state when the user logs in. If you do want to change the URL, however, you can simply set the window location using JavaScript in your success callback. For example:

window.location = '/logged_in.html'

Note that on the new page you will need to listen for the auth state as well:

firebase.auth().onAuthStateChanged(function(currentUser) {
  if (currentUser) {
    // the user is logged in, you can bootstrap functionality now
  }
});

In general Firebase applications on the web will work better if you don't structure your app to need hard page loads in between state transitions. Everything can and ideally should be managed using JavaScript without requiring an extra page load.

like image 37
Michael Bleigh Avatar answered Oct 13 '22 11:10

Michael Bleigh


You can assign to location in the JavaScript, e.g. location = 'https://google.com' or location = '/logged-in-page.html'.

like image 33
csander Avatar answered Oct 13 '22 12:10

csander