The discussion revolves around the best way to enforce permissions in a Rails application, specifically in a controller or constraint. pfaffman is trying to restrict POST requests to a certain route to the owner of a server model, but is unsure of the best approach.
pfaffman initially considers using a custom constraint in pfaffman_constraint.rb to check the path_parameters[:action] and enforce permissions. However, fzngagan suggests using the before_action method to check the condition, and later recommends creating a guardian method to check if a user is allowed to perform a given action.
pfaffman agrees that permissions need to be enforced in the controller or constraint, and fzngagan provides an example of how to use a guardian method to check permissions.
pfaffman decides to explore the guardian method approach and later updates on the difficulty of instantiating the guardian properly in the controller. fzngagan’s suggestion to use a guardian method to check permissions seems to be the recommended approach.
I have a plugin that adds a model, server, which has a user_id field. I want only the owner of the server to be able to make a POST (or maybe it should be a PUT?–the action will do a command-line rebuild of a Discourse instance on their server`; I’m not sure which would be best practice.)
In config/routes.rb is this:
post “/upgrade/:id” => “servers#queue_upgrade”, constraints: PfaffmanagerConstraint.new
Is it recommended to have matches? in pfaffmanager_constraint.rb check the path_parameters[:action] and enforce the permission there or to do it in servers_controller.rb?
Also, I think that what I should really do is move this route under namespace :user, so perhaps after I figure that out this problem will get solved as part of that, but this almost works, and I’d like to move to having other people try this code.
I think you need a guardian method to check if a user is allowed to perform a given action. for e.g. can_upgrade_server?
Also, once you do that, you can use guardian.ensure_can_upgrade_server! method which checks the condition and raises an exception which I think is exactly what you want.