Firebase Android: Make Username Unique

Firebase android : make username unique

Part of the answer is to store an index of usernames, that you check against in your security rules:

app : {
users: {
"some-user-uid": {
email: "test@test.com"
username: "myname"
}
},
usernames: {
"myname": "some-user-uid"
}
}

So the usernames node maps a username to a uid. It essentially reads as "username 'myname' is owned by 'some-user-uid'".

With this data structure, your security rules can check if there is already an entry for a given username:

"users": {
"$uid": {
".write": "auth !== null && auth.uid === $uid",
".read": "auth !== null && auth.provider === 'password'",
"username": {
".validate": "
!root.child('usernames').child(newData.val()).exists() ||
root.child('usernames').child(newData.val()).val() == $uid"
}
}
}

This validates that the username isn't claimed by anyone yet OR it is claimed by the current user.

Firebase - Forcing unique usernames

Short Answer:

First register user, then prompt them to put in their username, when they do, create their User-object in your database.

Solution to problem:

If a user for some reasons exits the app while deciding on a username, leading their email to be stored in the authentication-table without a User-object in the database, we have a problem.
To solve this, whenever a user signs in, we can check if their UID exists in the User-table, if it does, great! If not, then we prompt them to enter a username again, and then create the User-object.

How do i prevent duplicate usernames on firebase database

I would recommend you to make your database structure like following:

rootReference
|
-- uid1
|
- username
|
- email
|
- other_details
|
-- uid2
|
- username
|
- email
|
- other_details

This database structure not only would help you make every child unique but it would also help you search for user with particular username or email that you may need to get in future.

This database structure makes it easy to query with orderByChild() and also stores your username and email under uid.

For finding if a username is unique or not, you may use a simple query with orderByChild() like following:

reference.orderByChild("username").equalTo(userNameYouWantToSearch).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

if(dataSnapshot.exists())
// do what you want
}

@Override
public void onCancelled(@NonNull DatabaseError databaseError) { // ToDo: do something for errors

}
)};

In if() statement, you can just tell that userNameYouWantToSearch already exists on database and hence is not unique.

Firebase Database Rules for Unique Usernames

Sorry if i'm late but i ran into a similar problem, i changed my usernames rule to the following which did the trick:

"usernames" : {
"$username": {
".write": "!data.exists() && auth!= null && newData.val() == auth.uid"
}
},
}


Related Topics



Leave a reply



Submit