3

我使用 Firebase 和 TodoMVC 作为另一个项目的概念证明,为每个用户创建了登录名和唯一的待办事项列表。我正在使用 Firebase 和 Google 来登录用户,当一切正常时,他们会获得一个独特的持久待办事项列表。

当用户已经通过浏览器登录 Google 时,一切正常(我认为)。

当他们不是时,问题就会发生。他们看到的是未定义用户的待办事项列表,而不是他们的待办事项列表,或者他们的用户 ID 下的空白列表,直到他们点击刷新,然后事情又恢复了。Firebase url 在刷新之前看不到他们的 uid。如果您已登录 Google,则可以通过打开隐身窗口来复制错误。

您可以在http://lacyjpr.github.io/todo-backbone看到我的代码中的错误,在https://github.com/lacyjpr/todo-backbone看到我的 repo

这是我的验证码:

 // Authenticate with Google
 var ref = new Firebase(<firebase url>);
  ref.onAuth(function(authData) {
    if (authData) {
      console.log("Authenticated successfully");
    } else {
      // Try to authenticate with Google via OAuth redirection
      ref.authWithOAuthRedirect("google", function(error, authData) {
        if (error) {
          console.log("Login Failed!", error);
        }
      });
    }
  })

// Create a callback which logs the current auth state
function authDataCallback(authData) {
  if (authData) {
    console.log("User " + authData.uid + " is logged in with " +               authData.provider);
  uid = authData.uid;
} else {
  console.log("User is logged out");
 }
}

这是获取 UID 以用作 firebase 密钥的代码:

// Get the uid of the user so we can save data on a per user basis
var ref = new Firebase(<firebase url>);
var authData = ref.getAuth();

if (authData) {
  var uid = authData.uid;
  console.log(uid);
}

// The collection of todos is backed by firebase instead of localstorage
var TodoList = Backbone.Firebase.Collection.extend({

// Reference to this collection's model.
model: app.Todo,

// Save all of the todos to firebase
url: <firebase url> + uid,

提前感谢您提供的任何建议!

4

1 回答 1

2

.getAuth()在对用户进行身份验证之前调用。

您的应用程序严重依赖于uid正常工作。因此,在您的情况下,您希望在用户成功通过身份验证后启动应用程序的 Backbone 部分。

您可以修改您的 app.js 以仅在用户通过身份验证时启动。

// js/app.js

var app = app || {};
var ENTER_KEY = 13;

$(function() {

  var ref = new Firebase(<firebase url>);
  var authData = ref.getAuth();
  if (authData) {
    ref.authWithOAuthRedirect("google", function(error, authData) {
      if (error) {
        console.log("Login Failed!", error);
      } else {
        // kick off app
        new app.AppView();
      }
    });
  } else {
     new app.AppView();
  }

});

虽然这可行,但它不是理想的解决方案。但是没有其他选择,因为您没有登录屏幕。

理想情况下,您希望为用户提供一个登录位置,然后您就可以访问该.getAuth()值。

另外,不用担心存储uidwindow. .getAuth()是缓存的用户,所以没有网络调用来获取数据。

于 2015-12-29T12:08:04.750 回答