15

我正在尝试自动生成可以保存数据的用户帐户,然后将其提升为正确的用户名/密码帐户。关于最好的方法的任何想法?

我不清楚我是否可以将身份验证提供者从匿名切换到密码。

4

1 回答 1

14

您可以首先使用 Firebase 创建一个匿名登录,然后将该身份验证“uid”密钥存储到某种会话或 cookie(取决于您正在使用的框架)。虽然客户端是匿名的,但您可以将保存的数据链接到此匿名“uid”。

要在用户登录后将数据传输给用户,您需要使用 Firebase 的onAuth()侦听器。这将在用户的身份验证数据更改时通知您。获得新的经过身份验证的 uid 后,您可以将存储的数据链接到该新 uid 并删除您的匿名会话。

这是 Firebase 文档中修改后的示例:

var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com');
firebaseRef.onAuth(function(authData) {
  if (authData) {
    // Client is logged in, so check if it's anonymous or a real user

    if (authData.provider === 'anonymous') {
      // user is anonymous
      // save authData.uid to some local session info, to keep track of data
    } else {
      // user is logged in
      // transfer any data that you had stored from the anonymous session to 
      // this new authUser.uid

  } else {
    // Client is unauthenticated

    // This would be a good spot to create the anonymous login
    firebaseRef.authAnonymously(function(error, authData) {
      if (error) {
        // handle login failure
      } else {
        // you are now anonymously logged in, but you really don't need to do anything
        // here, because your onAuth() listener is already going to catch this auth change
      }
  }
});

当用户更改其身份验证信息时,Firebase 不会告诉您以前的 uid 是什么,因此您确实需要将该匿名 uid 存储在某个地方。您也可以在不创建匿名登录的情况下完成整个操作,只需存储会话数据直到用户登录,但匿名登录提供了更多的一致性。

于 2014-11-10T09:53:29.437 回答