Firebase & Backbone:使用 uid 作为键时出现问题

Firebase & Backbone: Trouble using uid as a key

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

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

问题发生在它们不存在的时候。他们看到的不是他们的待办事项列表,也不是他们用户 ID 下的空白列表,而是未定义用户的待办事项列表,直到他们点击刷新,然后事情又恢复了。 Firebase url 在点击刷新之前看不到他们的 uid。如果您登录 Google,您可以通过打开隐身 window.

来重现错误

您可以在 http://lacyjpr.github.io/todo-backbone, and my repo at https://github.com/lacyjpr/todo-backbone

查看我的代码中的错误

这是我的验证码:

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

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

您在用户通过身份验证之前调用 .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() 值。

此外,不用担心将 uid 存储在 window 上。 .getAuth() 是缓存的用户,所以没有网络调用来获取数据。