Hi everybody,
I wanted to know if we can have constraints in the route level. I mean defining a route with some constraints (based e.g. on the request sessions data).
Sorry if I do a parallel with rails, but in rails (as explained from here in the guides) we can have constraints on the routes.
The constraints I’m particularly interested in are those based on lambdas.
Let me give you an example use case I had in rails…
I have different kind of users (regular, admins, etc.) where I have its type stored in a session variable once logged in.
Then I can do the following:
constraints lambda { |req| req.session[:user_type] == 'Admin' } do
get '/dashboard', to: 'admin_dashboard#show', as: 'dashboard'
...
end
constraints lambda { |req| req.session[:user_type] == 'User' } do
get '/dashboard', to: 'user_dashboard#show', as: 'dashboard'
...
end
This example is a little extract and might not tell all the story but as you might noticed it’s somehow an authorization mechanism.
I can now have some resources controllers scoped to the type of users and I know that, thanks to the constraints at the route level, I will never have some authorization mishaps.
In more complex situations I can have only the show
action for a user while having the whole resources
actions for an admin.
Doing it like this let me not bother at all at the controller level and hence I don’t have the need to import any authorization package or code a complex custom authorization handler.
In the Router doc page, there is no mention at all of the word constraint.
So, do you know how I can do this?
Note: elixir being functional and Phoenix being based on plugs, I’m pretty sure that I can easily achieve this kind of constraint based routes, thanks to plugs, pipelines, forward
ing routes and pattern matching, right? I just need some guidance.