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

前端 未结 9 494
后悔当初
后悔当初 2020-11-28 04:38

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

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


        
相关标签:
9条回答
  • 2020-11-28 04:45

    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

    0 讨论(0)
  • 2020-11-28 04:48

    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

    0 讨论(0)
  • 2020-11-28 04:50

    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}}}
        // />
    
    0 讨论(0)
  • 2020-11-28 04:53

    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.
      }
    });
    
    0 讨论(0)
  • 2020-11-28 04:55

    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.
    }
    
    0 讨论(0)
  • 2020-11-28 04:58

    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.

    0 讨论(0)
提交回复
热议问题