Role-Based User Permissions in Firebase

Fireship · Intermediate ·🔧 Backend Engineering ·8y ago

Key Takeaways

This video teaches role-based user permissions in Firebase with fine-grained access control

Full Transcript

role-based user authorization can give you fine-grained control over which actions a user can perform in your app many apps use this strategy such as Stack Overflow and reddit to control the types of data that can be modified by users in this episode we're going to implement role based access control with firebase and angular core our users are going to have three different roles the admin role can read and write anything author role can read and edit but not delete and the reader can only read data since we can't actually edit the data on the firebase object we need to create our own custom user class will do this by saving our own custom data to the real-time database and in the user object will have a roles object which can either have an author reader or admin attribute in the angular app I'm going to use a typescript interface to make sure that the user roles can't be anything other than a reader author or admin then I'm creating a custom user class which is where we can define any custom data we want to add to the user object by default will pass the constructor the firebase auth data and use that to set an email photo URL and then we'll set the reader value to true by default so a new user will look like this when they sign up in the database so now we can build an off service to actually log in and log out the user we're going to use Google OAuth as the login method so we import the angularfire database as well as angularfire auth and our custom user class and we're going to set our current user as a behavior subject instead of the angularfire auth observable this will give us more flexibility when we start working with router guards inside the service constructor we subscribe to the angularfire auth off state observable and we can add switch map which will give us access to the auth user ID and we can return the location in the database that has this user data which in this case is a user collection followed by the user ID if the auth object is undefined we just return a null observable then we can call subscribe and whatever we get back is what will apply to that behavior subject if the user is logged in this will be the data from the database and if they're not signed in it'll just be null from here we'll add a method for the user to sign in and sign out I'm just going to go over this quickly because it's the standard or information you'll find in that angularfire to documentation the only difference is when the user logs in we want to update the database with whatever user information we want to save there we can do this by creating a new user object and then we'll check the database to see if the data is already defined and if it's not we'll go ahead and update it with the default data from this class so this code only run when we have a brand new user signing up for the first time with that out of the way we can actually start building some authorization rules our database has some posts in it and we want to limit access to who can create update and delete these posts we can create a post service to handle this logic so we'll import the angularfire database our off service as well as lodash we set a variable user roles which is an array of the roles that are actually assigned to the current user we can define this variable by subscribing to the user from our off service and then we'll map the roles down to an array of strings this will make the code for our rules a little less verbose the next step is to create a couple functions to actually get the data from the database and then we can finally start writing some rules related to this data first we're going to write a helper function which is going to see if there are any matches between two arrays the reason is that every rule is going to have an array of allowed roles and we want to make sure those roles match the actual user roles this makes the authorization logic very straightforward we just define an array of the allowed roles and then we call our helper function to see if there's a match between those roles and the users roles for example that can delete rule only allows admin users so if an author or reader user tries to perform this action it'll return false so we can lock down specific actions in the type script directly by wrapping them in an if statement in this case users can only edit posts if the can edit rule returns true if not it'll just say action prevented and we can also perform the same logic for deleting posts just using the can delete rule if we go into the app we can see we're currently logged in with just the reader role so if we try to edit or delete a post we'll see this action prevented message in the console but if we go into the database and give this user the author role we should get different results so now that we have the author permission we can try to delete a post but we'll still get the same message because we're not authorized to delete but we should have access to edit the post so we click Edit we go in here and we edit the data and it should update in the database when we go back we can confirm the post does have the new text that we just entered then we can go ahead and add the admin role in the database and we should have access to now delete the post when we click delete this time we can see that post is deleted and we don't get any kind of error in the console it's also important to point out that we could just hide the delete button from the Dom altogether and we can do this by using ng F along with the can delete function that we had defined in the post service so just keep that in mind as an option when you're securing data on the front-end another option you have for managing roles is with router guards so here we're going to build a router guard that only allows the author role to access a certain route the logic is very similar to what you just saw on the post service we first subscribe to the current user from our off service and then we map the roles down to a boolean which will return true if they have the author roll and then false if they do not then we can use the rxjs do operator to run some arbitrary code which is useful if you want to redirect the user or raised like a toast message so when a user tries to navigate to this route angular will subscribe to this observable and it will either return true or false if it's false and they won't be able to access that route so we can apply it to individual routes by going into our app router first make sure the guard is in your providers array and then on individual routes you can add a can activate array and add that guard to it if we try to navigate to this route without the authored role we'll see the route is blocked and we'll also get this route prevented message in the console and the last thing we're going to look at is securing the database on the backend we can use firebase database rules to ensure our data integrity even if our front-end JavaScript code is hacked as you can see here I've removed the can delete rule from angular and our user only has the reader role so they shouldn't be able to delete post but we still get an error from firebase because we've set some back-end database rules the rules are kind of hard to read so I recommend going to angular firebase on to get the full code but we'll go through it really quickly here first we set a rule for reading data so we make sure that the user with that auth ID has the reader attribute in the database and we do this by traversing the database with the route variable which is provided by firebase for writing data first we set the rule for the author so we make sure that they're providing new data which means they're not deleting the post and then we traverse the database again making sure that they have the author role on their profile otherwise for admin users we just need to make sure that they have the admin role on their profile and they can create update or delete any data that they want that's it for role based access control of firebase if this video helped you please like and subscribe and if you want the full code head over to angular firebase com and if you want access to exclusive content as well as one on one project consulting consider becoming an angular firebase Pro thanks for watching and I'll talk to you soon [Music]

Original Description

Role-based user authorization or access control, will give you fine-grained control over user permissions for Firebase users. In this lesson we are going to give Firebase users 3 different roles - reader, author, and admin. Full Lesson: https://angularfirebase.com/lessons/role-based-permissions-and-authorization-with-firebase-auth/ We will cover all four of these strategies in this lesson. - Hide HTML elements - Prevent actions - Restrict routes with router guards - Create backend Firebase database rules.
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Fireship · Fireship · 40 of 60

1 Angular 4 Development and Production Environments with Firebase
Angular 4 Development and Production Environments with Firebase
Fireship
2 OAuth with Angular and Firebase Tutorial
OAuth with Angular and Firebase Tutorial
Fireship
3 Anonymous Authentication with Angular and Firebase - Lazy Registration
Anonymous Authentication with Angular and Firebase - Lazy Registration
Fireship
4 Angular Router Guards for Firebase Users
Angular Router Guards for Firebase Users
Fireship
5 Angular Firebase CRUD App with NoSQL Database Tutorial
Angular Firebase CRUD App with NoSQL Database Tutorial
Fireship
6 Upload Files from Angular to Firebase Storage
Upload Files from Angular to Firebase Storage
Fireship
7 How to Deploy an Angular App to Firebase Hosting
How to Deploy an Angular App to Firebase Hosting
Fireship
8 Sharing Data between Components in Angular
Sharing Data between Components in Angular
Fireship
9 Loading Spinners for Asynchronous Firebase Data
Loading Spinners for Asynchronous Firebase Data
Fireship
10 Angular 4 Transactional Email with Google Firebase Cloud Functions
Angular 4 Transactional Email with Google Firebase Cloud Functions
Fireship
11 Firebase Database Rules Tutorial
Firebase Database Rules Tutorial
Fireship
12 Autocomplete Search with Angular4 and Firebase
Autocomplete Search with Angular4 and Firebase
Fireship
13 Reddit Inspired Upvoting System with Angular and Firebase NoSQL
Reddit Inspired Upvoting System with Angular and Firebase NoSQL
Fireship
14 Angular Drag-and-Drop File Uploads to Firebase Storage
Angular Drag-and-Drop File Uploads to Firebase Storage
Fireship
15 Text Translation with Firebase Cloud Functions onWrite and Angular 4
Text Translation with Firebase Cloud Functions onWrite and Angular 4
Fireship
16 Custom Usernames with Firebase Authentication
Custom Usernames with Firebase Authentication
Fireship
17 Twitter-Inspired Follow Unfollow Feature with Firebase and Angular 4
Twitter-Inspired Follow Unfollow Feature with Firebase and Angular 4
Fireship
18 Simple Pagination with Firebase and Angular 4
Simple Pagination with Firebase and Angular 4
Fireship
19 How to Connect Firebase Users to their Data - 3 Methods
How to Connect Firebase Users to their Data - 3 Methods
Fireship
20 Add Toast Message Notifications to your Angular App
Add Toast Message Notifications to your Angular App
Fireship
21 Facebook-Inspired Reactions System with Angular and Firebase
Facebook-Inspired Reactions System with Angular and Firebase
Fireship
22 Learn NgModule in Angular with Examples
Learn NgModule in Angular with Examples
Fireship
23 Lazy Loading Components in Angular 4
Lazy Loading Components in Angular 4
Fireship
24 Stripe Checkout Payments with Angular and Firebase - Part 1
Stripe Checkout Payments with Angular and Firebase - Part 1
Fireship
25 Process Stripe Payments with Firebase Cloud Functions - Part 2
Process Stripe Payments with Firebase Cloud Functions - Part 2
Fireship
26 Selling Digital Content in Angular with Stripe Payments - Part 3
Selling Digital Content in Angular with Stripe Payments - Part 3
Fireship
27 Angular 4 Full Text Search with Algolia - Part 1
Angular 4 Full Text Search with Algolia - Part 1
Fireship
28 Algolia with Firebase Cloud Functions - Part 2
Algolia with Firebase Cloud Functions - Part 2
Fireship
29 Firebase Phone Authentication in Angular 4
Firebase Phone Authentication in Angular 4
Fireship
30 Top 7 RxJS Concepts for Angular Developers
Top 7 RxJS Concepts for Angular Developers
Fireship
31 Learn Angular Animations with 5 Examples
Learn Angular Animations with 5 Examples
Fireship
32 Advanced Firebase Data Filtering (Multi-Property)
Advanced Firebase Data Filtering (Multi-Property)
Fireship
33 Realtime Maps with Mapbox + Firebase + Angular
Realtime Maps with Mapbox + Firebase + Angular
Fireship
34 Angular Reactive Forms with Firebase Database Backend
Angular Reactive Forms with Firebase Database Backend
Fireship
35 Send Push Notifications in Angular with Firebase Cloud Messaging
Send Push Notifications in Angular with Firebase Cloud Messaging
Fireship
36 Top 7 Ways to Debug Angular 4 Apps
Top 7 Ways to Debug Angular 4 Apps
Fireship
37 Infinite Scroll with Angular and Firebase
Infinite Scroll with Angular and Firebase
Fireship
38 Use TypeScript with Firebase Cloud Functions
Use TypeScript with Firebase Cloud Functions
Fireship
39 Realtime Graphs and Charts with Plotly and Firebase
Realtime Graphs and Charts with Plotly and Firebase
Fireship
Role-Based User Permissions in Firebase
Role-Based User Permissions in Firebase
Fireship
41 User Presence System in Realtime - Online, Offline, Away
User Presence System in Realtime - Online, Offline, Away
Fireship
42 Location-based Queries with GeoFire and Angular Google Maps
Location-based Queries with GeoFire and Angular Google Maps
Fireship
43 Angular ngrx Redux Quick Start Tutorial
Angular ngrx Redux Quick Start Tutorial
Fireship
44 Angular Ngrx Effects with Firebase Database
Angular Ngrx Effects with Firebase Database
Fireship
45 Progressive Web Apps with Angular
Progressive Web Apps with Angular
Fireship
46 Angular Ngrx with Firebase Google OAuth User Authentication
Angular Ngrx with Firebase Google OAuth User Authentication
Fireship
47 RxJS Quick Start with Practical Examples
RxJS Quick Start with Practical Examples
Fireship
48 Send SMS Text Messages with Twilio and Firebase
Send SMS Text Messages with Twilio and Firebase
Fireship
49 Firebase Database Performance Profiling
Firebase Database Performance Profiling
Fireship
50 Native Desktop Apps with Angular and Electron
Native Desktop Apps with Angular and Electron
Fireship
51 Subscription Payments with Stripe, Angular, and Firebase
Subscription Payments with Stripe, Angular, and Firebase
Fireship
52 Firestore with AngularFire5 Quick Start Tutorial
Firestore with AngularFire5 Quick Start Tutorial
Fireship
53 Angular HTTP Client Quick Start Tutorial
Angular HTTP Client Quick Start Tutorial
Fireship
54 Google Sign-In with Firestore Custom User Data
Google Sign-In with Firestore Custom User Data
Fireship
55 Star Review System from Scratch with Firestore + Angular
Star Review System from Scratch with Firestore + Angular
Fireship
56 Angular Chatbot with Dialogflow (API.ai)
Angular Chatbot with Dialogflow (API.ai)
Fireship
57 Learn @ngrx/entity and Feature Modules
Learn @ngrx/entity and Feature Modules
Fireship
58 Infinite Scroll Pagination with Firestore
Infinite Scroll Pagination with Firestore
Fireship
59 Faster Firestore via Data Aggregation
Faster Firestore via Data Aggregation
Fireship
60 Contentful - CMS for Angular Progressive Web Apps
Contentful - CMS for Angular Progressive Web Apps
Fireship

Related Reads

📰
10 Most Common Mistakes Java Developers Make in Interviews
Learn the common mistakes Java developers make in interviews and how to avoid them to improve your chances of success
Medium · Programming
📰
# C++ Error Messages Translated — 10 Common Compilation & Link Errors Explained
Learn to decipher 10 common C++ error messages for compilation and linking, improving debugging efficiency
Dev.to · Yilong Wu
📰
# Picking What to Read Next: The Trade-offs of Ranked-Choice Voting in a Django App
Learn how to implement ranked-choice voting in a Django app, weighing the trade-offs and complexities involved
Medium · Python
📰
The Ultimate Rust ORM Comparison 2026: Diesel vs SQLx vs SeaORM vs Rusqlite — Pick Your Powerhouse!
Compare top Rust ORMs Diesel, SQLx, SeaORM, and Rusqlite to choose the best fit for your project
Medium · Programming
Up next
Claude Code Tutorial for Non-Coders: Real Business Demo
Maksims Sics
Watch →