问题
I am building an Android App where I am using different ways for the user to register himself, like Email/Password, Phone, Google, Facebook, Twitter. I also want the users to be able to add one another as their contacts.
If I was using Email and Google only, then it would've been easy to implement this as I could store the User's Email in the DB and use that to identify different users and create Relations between them.
But now, the problem is that a User could register using their Phone Number as well and Facebook accounts could also be registered using Phone Number only. So, I can't just use the Email only as User's unique ID.
What are some of the ways I could achieve the desired result i-e create unique user IDs in the DB so that Users could add one another as Contacts?
回答1:
You can do this:
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
The above will get the currentuser that logged in.
then you can set his userid
in the database, doing this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Users").child(user.getUid());
ref.child("phonenumber").setValue(number);
You would have this database:
Users
userid
name: name_here
phonenumber: number_here
address: address_here
For the contacts simply do this:
DatabaseReference dbRef;
DatabaseReference cont=FirebaseDatabase.getInstance().getReference().child("Contact");
dbRef= cont.child(user.getUid());
dbRef=cont.child("name").setValue(name);
So in the Contact node you will have the userid
and inside of it the names of the contacts that this user has added to the list.
Contact
userid
nameofContact1: name_here
回答2:
I presume you are using firebase for your authentication, since you tagged firebase in your question. Firebase authentication usually fetches the user's name during authentication so you can get those details during sign up, add them to your database and assign a unique id to each user. You can then create a friends node for each user on the system where their friends' ids will be stored. An example of sign up /sign in is shown below:
FirebaseAuth mAuth = FirebaseAuth.getInstance();
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, get available information
final FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
if (user.getEmail() != null) {
//since various methods are available, you may want to use names
String name = user.getDisplayName();
//if email exists, you can try this
user.getEmail();
//otherwise, this is sure to exist but you may want to tell your users
//to complete their profiles later
user.getUid()
}
} else {
//Notify user
}
} else {
//The whole process failed
}
}
});
回答3:
You can use Firebase UID. Simply callFirebaseAuth.getInstance().getUid();
来源:https://stackoverflow.com/questions/47960998/firebase-auth-get-users-by-email-or-phone-number