在Firebase中创建临时匿名用户

乔纳森·K

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

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

达斯汀

您可以先使用Firebase创建匿名登录,然后将该auth“ 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存储在某个地方。通过仅存储会话数据直到用户登录,您还可以完全不用创建匿名登录即可完成整个操作,但是匿名登录提供了更高的一致性。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章