user3718908x100
user3718908x100

Reputation: 8509

Role-based authentication with Firebase

I am new to Firebase, I am trying to create user authentication. A user object has: username, email, fullname, role, password.

Now I want to be able to create a user with those properties and authenticate using either username/email and password.

After authentication I would like to check the role of the user to determine which part of my app they are allowed to access.

I have no idea how to go about it and the docs mostly deal with only email and password.

Upvotes: 1

Views: 2164

Answers (2)

Callam
Callam

Reputation: 11539

You can structure your database like this to store each user's information using their $uid and keep a list of the usernames claimed by each user so you can have a write rule that prevents overwriting an already existing username in usernames.

So upon registration, you need to sign up with an email and password using FIRAuth then on completion, you will be given a FIRUser. You can then use the uid to write the username, role etc. to the user's location in the database "users/$uid": {"username": "callam", ...} as well as the username individually at the usernames location "usernames/$username": "$uid".

You will need to implement write/validate rules for "users/$uid" and "usernames/$username" to make sure the username hasn't already been taken.

{
    "users": {
        $uid: {
            "username": "callam",
            ...
            "role": "member"
        }
    },
    "usernames": {
        "callam": $uid
    }
}

Upvotes: 1

Nerdy Bunz
Nerdy Bunz

Reputation: 7437

Firebase only supports email + password authentication at the moment, and not username + password. (And, of course, Facebook, Twitter, anonymous, etc.) You can still do you own custom authentication, though.

You can still create your own user objects in the database with those fields that you mentioned: (username, email, fullname, role, password), but those are separate from the authentication part of firebase. This process, I would call "registration," and that's up to you to implement.

If you're wanting to control what parts of the database different users can access then you're talking about database rules.

If you want to control access to different parts of your app itself, then you would just code it that way.

Upvotes: 1

Related Questions