Our Security Rules are getting repetitive with all the logic that we've copy and pasted for the several actions we currently have.
In this lesson, we'll go through our security rules and extract the duplicated rules into functions that we can call.
With this approach, we can eliminate the copy/pasting and make our functions a bit more readable.
Man 1: [0:01] Now we see that this is getting repetitive, so we are copy pasting the same code over and over again. For this, Firebase lets us also create functions inside of the security rules so that we can create functions for this type of code and then just use those functions instead of copy pasting the entire code.
[0:23] We have to declare them using the function keyword and this is going to say isAuthenticated. This function is going to return the request.of is different from [inaudible] . Here I can come and change all of these ones that says request.of is different from [inaudible] for the function isAuthenticated.
[0:53] We can replace the rest with a new function called is DocumentOwner. This one is going to check if the request.of.uid is the same as the id that's coming in the task. For example, for the read, update, and delete operations, I want to get the resource.data.user, and for the create operator, I want to get the request.data.user.
[1:30] I can add a parameter here in the function and I can check against that parameter. When I come here and replace this for the function, I want to say if is authenticated and is if document owner, and in here, I am going to send the resource.data.user.
[1:57] I want to do the exact same thing for both update and delete, and then, for the create, I'm not going to get that user id from the resource, I am going to get it from the request.
[2:13] This way you can see two things. One, you can see how we are separating the authentication rules depending if the user is reading, updating, creating a document or we can also set functions so that we can keep our rules a little bit cleaner.