Adding authorization to routes

1.7k Views Asked by At

I cannot seem to find a good example for this. I have for example, a TicketController

I define a ticket resource in my routes.rb.

You only need to be logged in as a customer to GET a ticket, but you must be logged in as an administrator to PUT a ticket.

I currently do this at the controller level. I have a before_action for certain controller methods that check if you are logged in as customer or admin.

I'm wondering what the correct way to do this is. I would think ideally I could require certain authorization for specific actions on a specific resource. For example, the ticket resource GET action only needs to be logged in as a customer whereas the PUT action can only happen if you are an admin.

2

There are 2 best solutions below

1
On BEST ANSWER

Do you know the gems rolify and CanCanCan?

I think they can help you manage authorizations on resources in a single place instead of having to do it in every controller.

0
On

Using cancan gem is a common way to manage user authorizations on different resources. You can go through this railscast which covers the basics of using this gem.

Note: Cancan gem is however not updated since long, so would recommend using cancancan, which has similar functionality and syntax, but is actively supported and updated.