如何在 Firebase 中在经过身份验证的用户和数据库之间建立链接? [英] How to link between Authenticated users and Database in Firebase?
问题描述
我的 Android 应用中有 Firebase 身份验证.我的问题是如何在经过身份验证的用户(出现在 Firebase 控制台的 Firebase::Auth
选项卡中)和数据库(Firebase::Database
选项卡)之间建立链接.
I have Firebase Authentication in my Android app. My question is how do I link between authenticated users (that appear in Firebase::Auth
tab in the Firebase console) and the database (Firebase::Database
tab).
我需要通过Auth
中出现的User UID
将数据库中的数据与Auth
中的相关用户关联起来,并最终发送查询特定UID
以获取Database
中的相关信息.
I need to link data in the database with the relevant user in Auth
by the User UID
that appears in Auth
, and eventually send queries about a specific UID
to get the relevant info in Database
.
是否有一些自动/内置的东西可以做到这一点,或者每次我对用户进行身份验证时,我是否必须在 Database
中为用户创建一个新条目,然后为它创建一个 ID 字段Auth
?
Is there something automatic / built-in that does that or do I have to create a new entry for a user in Database
each time I authenticate a user and then create an ID field for it with the UID value that appears in Auth
?
在用户管理文档中,它仅解释了将用户添加到Auth
标签并重置他们的密码.
In the User Management docs it explains only about adding users to the Auth
tab and resetting their passwords.
推荐答案
认证后,使用 Firebase 提供的 UID 创建一个 child,并将其值设置为您的用户类:
After authentication, create a child with the UID given by Firebase, and set its value to your user class:
//get firebase user
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
//get reference
DatabaseReference ref = FirebaseDatabase.getInstance().getReference(USERS_TABLE);
//build child
ref.child(user.getUid()).setValue(user_class);
USERS_TABLE 是 root 的直接子级.
USERS_TABLE is a direct child of root.
然后当你想要检索数据时,通过其 UID 获取对用户的引用,监听 addListenerForSingleValueEvent()
(仅调用一次),并通过反射迭代结果:>
Then when you want to retrieve the data, get a reference to the user by its UID, listen for addListenerForSingleValueEvent()
(invoked only once), and iterate over the result with reflection:
//get firebase user
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
//get reference
DatabaseReference ref = FirebaseDatabase.getInstance().getReference(USERS_TABLE).child(user.getUid());
//IMPORTANT: .getReference(user.getUid()) will not work although user.getUid() is unique. You need a full path!
//grab info
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final Profile tempProfile = new Profile(); //this is my user_class Class
final Field[] fields = tempProfile.getClass().getDeclaredFields();
for(Field field : fields){
Log.i(TAG, field.getName() + ": " + dataSnapshot.child(field.getName()).getValue());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
或者没有反射:
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final Profile p = dataSnapshot.getValue(Profile.class);
}
这篇关于如何在 Firebase 中在经过身份验证的用户和数据库之间建立链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!