feat: Add support for guarding based on request data #173
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
We ran into a use case for guarding endpoints based on request data instead of static data. Specifically, in our
findOne(id: string)controller methods, we want to guard based on whether the requesting user can access the resource with the given id. Previously, we were required to use theAuthzServiceto check the user's access within thefindOnefunction, but mixing decorators and function calls for authorization doesn't seem as clean.This PR adds support for providing a
resourceFromContextfunction during initialization (which acts as the default) and in the guard (which overrides the default).resourceFromContextis given the execution context of the function, so it can access data from the request, and it returns a resource to be enforced against Casbin. The resource that is returned can be a single resource or an array of resources, and aBatchApprovaloption determines approval behavior in the array case. WithBatchApproval.ANY, as long as any of the resources returned fromresourceFromContextpass enforcement, the request continues. WithBatchApproval.ALL, all resources must pass enforcement.I would like to hear thoughts on this use case, and this approach. Are there any apparent or potential problems with this feature or approach? I aimed to maintain existing behavior by default, with this "resource specific guarding" requiring intentional usage to have any effect.