Fireship · @fireship
Role-Based User Permissions in Firebase
Uploaded August 16, 2017 · Length 7:52
Summary
Implement role-based user permissions in Firebase using Angular and Firebase Authentication.
- firebase role-based permissions
- angular firebase authentication
- firebase user permissions
- firebase database security
- firebase authorization
Transcript preview
The first 2 minutes of the transcript. Select a timestamp to watch that moment on YouTube.
- 0:00
role-based user authorization can give
- 0:02
you fine-grained control over which
- 0:04
actions a user can perform in your app
- 0:06
many apps use this strategy such as
- 0:08
Stack Overflow and reddit to control the
- 0:11
types of data that can be modified by
- 0:13
users in this episode we're going to
- 0:15
implement role based access control with
- 0:17
firebase and angular core our users are
- 0:20
going to have three different roles the
- 0:21
admin role can read and write anything
- 0:23
author role can read and edit but not
- 0:26
delete and the reader can only read data
- 0:28
since we can't actually edit the data on
- 0:31
the firebase object we need to create
- 0:33
our own custom user class will do this
- 0:36
by saving our own custom data to the
- 0:37
real-time database and in the user
- 0:39
object will have a roles object which
- 0:42
can either have an author reader or
- 0:44
admin attribute in the angular app I'm
- 0:46
going to use a typescript interface to
- 0:48
make sure that the user roles can't be
- 0:50
anything other than a reader author or
- 0:52
admin then I'm creating a custom user
- 0:55
class which is where we can define any
- 0:57
custom data we want to add to the user
- 0:58
object by default will pass the
- 1:01
constructor the firebase auth data and
- 1:03
use that to set an email photo URL and
- 1:06
then we'll set the reader value to true
- 1:08
by default so a new user will look like
- 1:10
this when they sign up in the database
- 1:12
so now we can build an off service to
- 1:14
actually log in and log out the user
- 1:16
we're going to use Google OAuth as the
- 1:18
login method so we import the
- 1:20
angularfire database as well as
- 1:22
angularfire
- 1:22
auth and our custom user class and we're
- 1:26
going to set our current user as a
- 1:27
behavior subject instead of the
- 1:29
angularfire
- 1:29
auth observable this will give us more
- 1:31
flexibility when we start working with
- 1:33
router guards inside the service
- 1:35
constructor we subscribe to the
- 1:37
angularfire auth off state observable
- 1:39
and we can add switch map which will
- 1:42
give us access to the auth user ID and
- 1:44
we can return the location in the
- 1:46
database that has this user data which
- 1:48
in this case is a user collection
- 1:50
followed by the user ID if the auth
- 1:53
object is undefined we just return a
- 1:54
null observable then we can call
- 1:57
subscribe and whatever we get back is
- 1:59
what will apply to that behavior subject


