Defining the User roles in Firebase

守給你的承諾、 提交于 2019-12-25 09:05:33

问题


In my Android app with Firebase as backend, I am planning to have three roles based on Security. User, Editor, Administrator

Anyone signing-up using Facebook is granted the User role by default.

  • The User can read anything but has very limited write permissions (provide reviews).
  • The Editor can read anything and has more write permissions than the user (create articles, provide reviews).
  • The Administrator can create/Delete Editors.

The Administrator can upgrade the role of an User to an Editor and vice-versa. Hence creating the User roles and Editor roles is taken care of. But, how to create an Administrator in the first place?

Regards


回答1:


That depends on what makes someone an administrator. If you want to explicitly manage the list of administrators up front, you could simply look them up in the Firebase Console and copy their uid into your security rules.

".write": "auth.uid == 'theUidThatYouLookedUp"

Or one level better would be to keep a read-only list of administrator in the database and refer to that in the rule:

".write": "root.child('admins').child(auth.uid).exists()"

But often there is something in the app that determines whether someone is an administrator. E.g.: the creator of a chat room is its administrator. In this case you'd store the admin for that chat room when you create the chat room.

"chatRooms": {
  "$chatRoomId": {
    ".write": "root.child('chatRoomOwners').child($chatRoomId).val() == auth.uid"
  }
}



回答2:


Firebase just launched support for role based access on any user via custom user claims on the ID token: https://firebase.google.com/docs/auth/admin/custom-claims

You would define the admin access rule:

{
  "rules": {
    "adminContent": {
      ".read": "auth.token.role === 'admin'",
      ".write": "auth.token.role === 'admin'",
    }
  }
}

Set the user role with the Admin SDK:

// Set admin privilege on the user corresponding to uid.
admin.auth().setCustomUserClaims(uid, {role: 'admin'}).then(() => {
  // The new custom claims will propagate to the user's ID token the
  // next time a new one is issued.
});

This will propagate to the corresponding user's ID token claims.

To parse it from the token on the client, you need to base64 decode the ID token's payload.

You can upgrade/downgrade users as needed. Setting editor role follows the same concept.



来源:https://stackoverflow.com/questions/39236163/defining-the-user-roles-in-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!