我应该如何在Firebase中记录和跟踪用户状态?

huangapple go评论58阅读模式
英文:

How should I record and track a user status in firebase?

问题

我正在尝试跟踪每个用户是否是高级会员。我正在使用Firebase身份验证。

我需要使用Firebase-Admin来执行此操作(使用.setCustomerUserClaims)吗?目前我只是使用Firebase/app。

是否有更好的方法?
也许我可以将用户的UID上传到FireStore以及一个Premium布尔值,当用户登录时从FireStore中获取高级布尔状态?但这将需要在用户每次登录时从数据库中额外获取一次,而Firebase-Admin的解决方案只需要与FireStore交互一次,即在注册时。

这是我的第一个项目,我不确定是否应该使用Firebase-Admin。这是一个合理的担忧吗?

谢谢!

英文:

I'm trying to track whether each user is a premium member or not. I'm using Firebase authentication.

Do I need to use Firebase-Admin to do this (using .setCustomerUserClaims). At the moment I'm just using Firebase/app.

Is there a better way?
Perhaps I could upload the User's UID to FireStore along with a Premium Boolean value, and when the user logs in pull the premium boolean status from the Firestore? But this would require an extra fetch from the database each time the user logs in, whereas the Firebase-Admin solution would only require one interaction with Firestore, upon registration.

This is my first project and I'm hesitant to use Firebase-Admin. Is this a legitimate concern?

Thanks!

答案1

得分: 1

自定义声明和将其存储在Firestore中都是有效的选项。它们之间没有明显的优劣之分。一切都取决于您的用例和其他需求(我们无法知道的东西,甚至您自己可能还不知道)。

需要记住的事项:

  • 自定义声明会随每个请求一起发送到服务器。
    这很方便,因为它们在每个请求中都是立即可用的。
    但这也意味着您需要在每个请求中添加这些信息,这可能不是理想的。
  • 自定义声明在ID令牌刷新时会被刷新,ID令牌会自动每小时刷新一次。
    因此,如果您需要在ID令牌自动刷新之前检测到订阅状态的更改,您将需要进行额外的API调用。
  • 将信息存储在Firestore中意味着您需要执行额外的调用来查找它。
    另一方面,每当您查找时,它都会始终为您提供最新的值。

通常,我会将自定义声明用于很少更改的状态(例如,某人是否是管理员),并对于不符合此情况的内容使用Firestore。

英文:

Both storing the subscript status as a custom claim and storing it in Firestore are valid options. Neither of them is pertinently better than the other. It all depends on your use-case and other needs (stuff we can't know, and you might not even know yet either).

Things to keep in mind:

  • Custom claims are sent with every request to the server.
    This is great, because they're readily available with each request.
    This is not great, because it means you're adding the info to each request.
  • Custom claims are refreshed when the ID token is refreshed, which happens automatically once an hour.
    So if your subscription status change needs to be detected before the ID token is auto-refreshed, you will need to make an additional API call.
  • Storing the info in Firestore means that you need to perform an extra call to look it up.
    On the other hand, it'll always give you the latest value when you look it up

I'd typically use a custom claim for something that is either status or changes rarely (e.g. whether somebody is an admin), and use Firestore for things that do not fit that bill.

huangapple
  • 本文由 发表于 2023年5月29日 05:27:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76353670.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定