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

前端 未结 9 495
后悔当初
后悔当初 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 05:02

    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
        }
    
    0 讨论(0)
  • 2020-11-28 05:07

    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
      }
    }
    
    0 讨论(0)
  • 2020-11-28 05:09

    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.

    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! :)

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