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

Jop*_*eph 78 javascript web firebase firebase-authentication

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

firebase.initializeApp(config);
let provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider);
Run Code Online (Sandbox Code Playgroud)

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

boj*_*eil 83

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

您必须添加身份验证状态更改观察器.

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 这对我来说是不一致的.http://stackoverflow.com/questions/39395158/onauthstatechanged-inconsistent#39395158 (3认同)
  • 使用onAuthStateChanged,有没有办法判断用户是否是新用户? (2认同)

Pas*_*sos 66

您还可以检查是否有currentUser

var user = firebase.auth().currentUser;

if (user) {
  // User is signed in.
} else {
  // No user is signed in.
}
Run Code Online (Sandbox Code Playgroud)

  • 这很奇怪,它适用于我,也许问题是因为auth是异步的并且_ currentUser_尚未更新. (8认同)
  • 即使在立即登录后,这也会为我返回null. (4认同)
  • 从文档中: currentUser 也可能为 null,因为 auth 对象尚未完成初始化。如果您使用观察者来跟踪用户的登录状态,则不需要处理这种情况。 (3认同)

Dan*_*ich 14

在这种情况下,无需使用onAuthStateChanged()函数.

您可以通过执行以下命令轻松检测用户是否已登录:

var user = firebase.auth().currentUser;
Run Code Online (Sandbox Code Playgroud)

对于那些面临"返回null"问题的人来说,这只是因为你没有等待firebase调用完成.

假设您在页面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);
    });
Run Code Online (Sandbox Code Playgroud)

如果用户已登录,那么"var user"将包含预期的JSON有效负载,否则,它将只是"null"

这就是你所需要的.

问候

  • @毛里西奥·西尔维斯特是吗?无论我是否登录,使用 `firebase.auth.currentUser` 都会返回 undefined。只有 auth() 在登录时返回正确的结果。 (3认同)

Qwe*_*rty 12

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

您可以将上一个身份验证状态存储到localStorage中,以在会话之间和选项卡之间持久保存该身份验证

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

页面加载后,firebase onAuthStateChanged事件将在大约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()
  }
})
Run Code Online (Sandbox Code Playgroud)



我在Reactreact-router上使用它。我将上面的代码放入componentDidMount了我的App根组件中。那里,在渲染中,我有一些PrivateRoutes

<Router>
  <Switch>
    <PrivateRoute
      exact path={routes.DASHBOARD}
      component={pages.Dashboard}
    />
...
Run Code Online (Sandbox Code Playgroud)

这是我的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}}}
    // />
Run Code Online (Sandbox Code Playgroud)


rav*_*ker 8

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

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

在此处输入图片说明

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


Ben*_*ing 7

这有效:

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
  }
}
Run Code Online (Sandbox Code Playgroud)


Ahm*_*şek 5

最新库版本的使用示例

import { initializeApp } from "firebase/app";
import { getAuth, onAuthStateChanged } from "firebase/auth";

const firebaseConfig = {
  ...
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

onAuthStateChanged(auth, user => {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
})
Run Code Online (Sandbox Code Playgroud)