Closed goravbhootra closed 6 years ago
Yes I think this is a reasonable approach, as long as the authorization rules are simple. When your functions become longer the Authorize
DSL might make the code more readable.
The thing I would not do is link authorization directly to controllers, but to keep it within your business logic (context), and just call the context from the controller.
Like Posts.update(id, params, user)
, and then handling authorization in the Posts module.
@jfrolich understand that approach - it has its own advantages.
I like to avoid spreading authorization logic throughout the app. Anyway, created this just for sharing the idea. Pls feel free to close this.
@goravbhootra: It's still possible to combine them in one module and not directly tie them to a controller. Hmm I actually like that. Perhaps an api could be:
Defmodule Authorization
authorize Post do
...rules
end
authorize Comment do
...rules
end
end
Authorization.authorize(%Post{}, user, :read)
Authorization.authorize(%Comment{}, user, :update)
This looks good.
The idea is to leverage on composable and dynamic queries so that when the query actually hits the DB, it scopes out what the user is not allowed to access and fetches the minimal data required.
There will be two kinds of access:
where the data exists but the specific user does not have privileges, we return 404 instead of 403 - its as if the resource does not exist.
Another use case will be whether an end-point can be accessed or not eg. whether user is allowed to create a new resource or dashboard access. If we dont return true, response will be 403.
The advantage of going thru the controllers is that you can still do things without user context, if you need to as well as testing remains sane.
Hi @jfrolich
I wrote custom authorization code for my current project. Posting it here for ideas:
Basically, I am returning scoped queries based on user privileges, that can be merged in controller so that authorization logic is in one place. It also helps re-usability of the controllers methods for different use cases eg. for users with different access levels.
In the above example, I am returning true for all admin actions as admin section (controllers) are different but they could very well return queries without any scopes.
I recently read about dynamic queries. Will try to implement that to clean up the logic further. Still not got time to get to it.
Any suggestions for improvement or discussion regarding above is welcome.