Javascript 如何检测用户是否已登录 Firebase?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37873608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:50:22  来源:igfitidea点击:

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

javascriptwebfirebasefirebase-authentication

提问by Jophin Joseph

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

我在我的 javascript 文件中使用 firebase 节点 api 进行 Google 登录。

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?

这工作正常,用户可以使用他的 Google 凭据登录。当用户再次访问该页面时,弹出窗口再次打开,但由于他已经登录,弹出窗口将关闭,无需用户进行任何交互。有没有办法在提示弹窗之前检查是否已经有登录用户?

回答by bojeil

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

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.
  }
});

回答by Daniel Passos

You can also check if there is a currentUser

您还可以检查是否有currentUser

var user = firebase.auth().currentUser;

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

回答by Qwerty

It is not possibleto tell whether a user willbe signed when a page starts loading, there is a work around though.

这是不可能的,告诉用户是否在页面开始加载签名,还有一个工作,虽然各地。

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

您可以将上次身份验证状态记忆到 localStorage 以在会话之间和选项卡之间保持它。

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 onAuthStateChangedfires). Otherwise, if the localStoragekey is empty, you can show the dialog right away.

然后,当页面开始加载时,您可以乐观地假设用户将自动重新登录并将对话框推迟到您可以确定(即onAuthStateChanged触发之后)。否则,如果localStorage键为空,您可以立即显示对话框。

The firebase onAuthStateChangedevent will fire roughly 2 secondsafter a page load.

firebaseonAuthStateChanged事件将在页面加载后大约2 秒触发。

// 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()
  }
})





我正在使用它 React反应react-router反应路由器。我将上面的代码放入componentDidMountcomponentDidMount我的 App 根组件中。在那里,在渲染中,我有一些PrivateRoutesPrivateRoutes

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

And this is how my PrivateRoute is implemented:

这就是我的 PrivateRoute 的实现方式:

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}}}
    // />

回答by Daniel Vukasovich

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

在这种情况下不需要使用 onAuthStateChanged() 函数。

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.

对于那些面临“返回空值”问题的人,这只是因为您没有等待 firebase 调用完成。

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:

假设您在页面 A 上执行登录操作,然后调用页面 B,在页面 B 上您可以调用以下 JS 代码来测试预期的行为:

  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"

如果用户已登录,则“var user”将包含预期的 JSON 有效负载,如果没有,则它只是“null”

And that's all you need.

这就是你所需要的。

Regards

问候

回答by ravish.hacker

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

另一种方法是使用与 firebase 相同的东西。

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.

例如,当用户登录时,firebase 将以下详细信息存储在本地存储中。当用户返回页面时,firebase 使用相同的方法来确定用户是否应该自动登录。

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

ATTN:因为 firebase 既没有列出也没有推荐。您可以将此方法称为非官方方式。这意味着稍后如果 firebase 更改其内部工作,则此方法可能不起作用。或者简而言之。使用风险自负!:)

回答by Ben Winding

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
  }
}

回答by maudulus

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 trueor false.

如果您允许匿名用户以及使用电子邮件登录的用户,则可以使用firebase.auth().currentUser.isAnonymous,它将返回truefalse

回答by muetzerich

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

使用Firebase.getAuth(). 它返回 Firebase 客户端的当前状态。否则返回值是null这里的文档:https: //www.firebase.com/docs/web/api/firebase/getauth.html

回答by Daniel

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
    }