Firebase android : make username unique

前端 未结 3 1542
不思量自难忘°
不思量自难忘° 2020-11-21 22:43

Parse will shut down at the end of the year, so I decided to start using Firebase. I need to implement a register process with 3 fields : email, username, password (

3条回答
  •  时光取名叫无心
    2020-11-21 23:33

    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.

提交回复
热议问题