How do I detect if a user is already logged in Firebase?

JavascriptFirebaseFirebase Authentication

Javascript Problem Overview


I'm using the firebase node api in my javascript files for Google login.

firebase.initializeApp(config);
let provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider);

This works fine and the user is able to login with his Google credentials. When the user visits the page again, the popup opens again but since he has already logged in, the popup closes without requiring any interaction from the user. Is there any way to check if there is already a logged in user before prompting the popup?

Javascript Solutions


Solution 1 - Javascript

https://firebase.google.com/docs/auth/web/manage-users

You have to add an auth state change observer.

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

Solution 2 - Javascript

You can also check if there is a currentUser

var user = firebase.auth().currentUser;

if (user) {
  // User is signed in.
} else {
  // No user is signed in.
}

Solution 3 - Javascript

It is not possible to tell whether a user will be signed when a page starts loading, there is a work around though.

>You can memorize last auth state to localStorage to persist it between sessions and between tabs.

Then, when page starts loading, you can optimistically assume the user will be re-signed in automatically and postpone the dialog until you can be sure (ie after onAuthStateChanged fires). Otherwise, if the localStorage key is empty, you can show the dialog right away.

The firebase onAuthStateChanged event will fire roughly 2 seconds after a page load.

// User signed out in previous session, show dialog immediately because there will be no auto-login
if (!localStorage.getItem('myPage.expectSignIn')) showDialog() // or redirect to sign-in page

firebase.auth().onAuthStateChanged(user => {
  if (user) {
    // User just signed in, we should not display dialog next time because of firebase auto-login
    localStorage.setItem('myPage.expectSignIn', '1')
  } else {
    // User just signed-out or auto-login failed, we will show sign-in form immediately the next time he loads the page
    localStorage.removeItem('myPage.expectSignIn')

    // Here implement logic to trigger the login dialog or redirect to sign-in page, if necessary. Don't redirect if dialog is already visible.
    // e.g. showDialog()
  }
})



I am using this with React and react-router. I put the code above into componentDidMount of my App root component. There, in the render, I have some PrivateRoutes

<Router>
  <Switch>
    <PrivateRoute
      exact path={routes.DASHBOARD}
      component={pages.Dashboard}
    />
...

And this is how my PrivateRoute is implemented:

export default function PrivateRoute(props) {
  return firebase.auth().currentUser != null
    ? <Route {...props}/>
    : localStorage.getItem('myPage.expectSignIn')
      // if user is expected to sign in automatically, display Spinner, otherwise redirect to login page.
      ? <Spinner centered size={400}/>
      : (
        <>
          Redirecting to sign in page.
          { location.replace(`/login?from=${props.path}`) }
        </>
      )
}

    // Using router Redirect instead of location.replace
    // <Redirect
    //   from={props.path}
    //   to={{pathname: routes.SIGN_IN, state: {from: props.path}}}
    // />

Solution 4 - Javascript

There's no need to use onAuthStateChanged() function in this scenario.

You can easily detect if the user is logged or not by executing:

var user = firebase.auth().currentUser;

For those who face the "returning null" issue, it's just because you are not waiting for the firebase call to complete.

Let's suppose you perform the login action on Page A and then you invoke Page B, on Page B you can call the following JS code to test the expected behavior:

  var config = {
    apiKey: "....",
    authDomain: "...",
    databaseURL: "...",
    projectId: "..",
    storageBucket: "..",
    messagingSenderId: ".."
  };
  firebase.initializeApp(config);

    $( document ).ready(function() {
        console.log( "testing.." );
        var user = firebase.auth().currentUser;
        console.log(user);
    });

If the user is logged then "var user" will contain the expected JSON payload, if not, then it will be just "null"

And that's all you need.

Regards

Solution 5 - Javascript

This works:

async function IsLoggedIn(): Promise<boolean> {
  try {
    await new Promise((resolve, reject) =>
      app.auth().onAuthStateChanged(
        user => {
          if (user) {
            // User is signed in.
            resolve(user)
          } else {
            // No user is signed in.
            reject('no user logged in')
          }
        },
        // Prevent console error
        error => reject(error)
      )
    )
    return true
  } catch (error) {
    return false
  }
}

Solution 6 - Javascript

One another way is to use the same thing what firebase uses.

For example when user logs in, firebase stores below details in local storage. When user comes back to the page, firebase uses the same method to identify if user should be logged in automatically.

enter image description here

ATTN: As this is neither listed or recommended by firebase. You can call this method un-official way of doing this. Which means later if firebase changes their inner working, this method may not work. Or in short. Use at your own risk! :)

Solution 7 - Javascript

If you are allowing anonymous users as well as those logged in with email you can use firebase.auth().currentUser.isAnonymous, which will return either true or false.

Solution 8 - Javascript

There are technically 3 possibilities with promises:

// 1) best option, as it waits on user...

const isLoggedIn: any = await new Promise((resolve: any, reject: any) =>
this.afa.onAuthStateChanged((user: any) =>
  resolve(user), (e: any) => reject(e)));

console.log(isLoggedIn);

// 2) may experience logging out state problems...

const isLoggedIn2 = await this.afa.authState.pipe(first()).toPromise();

console.log(isLoggedIn2);

// 3) technically has a 3rd option 'unknown' before user is loaded...

const isLoggedIn3 = await this.afa.currentUser;

console.log(isLoggedIn3);


// then do something like (depending on your needs) with 1, 2, or 3:

if (!!isLoggedIn) {
  // logged in
}

Also note, the example is angular, but you can replace this.afa with firebase.auth()

Solution 9 - Javascript

use Firebase.getAuth(). It returns the current state of the Firebase client. Otherwise the return value is nullHere are the docs: https://www.firebase.com/docs/web/api/firebase/getauth.html

Solution 10 - Javascript

First import the following

import Firebase
import FirebaseAuth

Then

    // Check if logged in
    if (Auth.auth().currentUser != null) {
      // User is logged in   
    }else{
      // User is not logged in
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJophin JosephView Question on Stackoverflow
Solution 1 - JavascriptbojeilView Answer on Stackoverflow
Solution 2 - JavascriptDaniel PassosView Answer on Stackoverflow
Solution 3 - JavascriptQwertyView Answer on Stackoverflow
Solution 4 - JavascriptDaniel VukasovichView Answer on Stackoverflow
Solution 5 - JavascriptBen WindingView Answer on Stackoverflow
Solution 6 - Javascriptravish.hackerView Answer on Stackoverflow
Solution 7 - JavascriptmaudulusView Answer on Stackoverflow
Solution 8 - JavascriptJonathanView Answer on Stackoverflow
Solution 9 - JavascriptmuetzerichView Answer on Stackoverflow
Solution 10 - JavascriptDanielView Answer on Stackoverflow